Chapter 9 Matrix

9.1 Creating Matrix object

Matrix object can be created in several ways.

In addition, a matrix object in R is actually a vector that the number of rows and columns are set in the attribute dim. Thus, if you created a vector with attribute dim in Rcpp and return it to R, it will be treated as a matrix.

Execution result

> rcpp_matrix()
     [,1] [,2]
[1,]    1    3
[2,]    2    4

However, even if you set a value to attribute dim of a vector object, the type of the object remains Vector type in Rcpp code. Thus, if you want to convert it to Matrix type in Rcpp, you need to use as<T>() function.

9.2 Accessing to Matrix elements

By using () operator, you can get from and assign to the values of elements of a Matrix object by specifying its column number and row number. As in the case of vectors, row numbers and column numbers in Matrix start with 0. If you want to access to a specific row or column, use the symbol _.

You can also use the [] operator to access an element as a vector connecting the columns of a matrix.

9.2.1 Accessing as reference to row, column and sub matrix

Rcpp also provides types that hold “references” to specific part of a matrix.

Assigning a value to a “reference” object of a matrix is equivalent to assigning the value to its original matrix. For example, assigning a value to col will assign a value to the column 1 of m.

9.3 Member functions

Since Matrix is actually Vector, Matrix basically has the same member functions as Vector. Thus, member functions unique to Matrix are only presented below.

9.3.1 nrow() rows()

Returns the number of rows.

9.3.2 ncol() cols()

Returns the number of columns.

9.3.3 row( i )

Return a reference Vector::Row to the ith row.

9.3.4 column( i )

Return a reference Vector::Column to the ith column.

9.3.5 fill_diag( x )

Fill diagonal elements with scalar value x.

9.3.6 offset( i, j )

Returns the numerical index in the original vector of the matrix corresponding to the element of row i and column j.

9.4 Static member functions

Matrix basically has the same static member function as Vector. The static member functions unique to Matrix are shown below.

9.4.1 Matrix::diag( size, x )

Returns a diagonal matrix whose number of rows and columns equals to “size” and the value of the diagonal element is “x”.