Sparse matrices
Limited support
armadillo4r, as of v0.5.0, supports the
dgCMatrix class from the Matrix package. This
class is a sparse matrix class that stores the matrix in a compressed
column format.
The strategy for an efficient conversion from R to C++ and vice versa
is to create an indexing of the non-zero elements of the input matrix
and then use this indexing to create dgCMatrix (R) or
SpMat (Armadillo/C++) object.
Note that cpp4r does not provide sparse matrices as it
is the case for the dense data types doubles_matrix<>
or integers_matrix<>. armadillo4r uses
SEXP to provide a method to convert dgCMatrix
objects to SpMat objects and vice versa using some
properties of S4 objects.
Here is an example of how to convert a dgCMatrix object
to a SpMat object and re-import it to R:
[[cpp4r::register]] SEXP sum_matrices_(SEXP x) {
``````cpp
// Convert from dgCMatrix to SpMat
``````cpp
SpMat<double> A = as_SpMat(x);
``````cpp
``````cpp
// Create a matrix B with a diagonal of random numbers
``````cpp
SpMat<double> B(A.n_rows, A.n_cols);
``````cpp
for (uword i = 0; i < A.n_rows; ++i) {
``````cpp
B(i, i) = randu<double>();
``````cpp
}
``````cpp
``````cpp
A += B; // Add the two matrices
``````cpp
``````cpp
// Convert back to dgCMatrix and return
``````cpp
return as_dgCMatrix(A);
``````cpp
}