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.
> 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
9.2 Accessing to Matrix elements
() 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.
// Creating a 5x5 numerical matrix NumericMatrix m( 5, 5 ); // Retrieving the element of row 0 and column 2 double x = m( 0 , 2 ); // Copying the value of row 0 to the vector v NumericVector v = m( 0 , _ ); // Copying the value of column 2 to the vector v NumericVector v = m( _ , 2 ); // Copying the row (0 to 1) and column (2 to 3) to the matrix m2 NumericMatrix m2 = m( Range(0,1) , Range(2,3) ); // Accessing matrix element as vector m; // This points to the same element as m(0,1)
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
9.3 Member functions
Matrix is actually
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
9.3.4 column( i )
Return a reference
Vector::Column to the
9.3.5 fill_diag( x )
Fill diagonal elements with scalar value
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
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”.