Tuesday, July 15, 2014

Subsetting matrices in armadillo

Here are some tests for subsetting a matrix in armadillo: by columns, by rows or by both:

C++ code:

// [[Rcpp::export]]
arma::mat testcols(arma::mat x, arma::Col idx) {
 arma::mat xsub;
 xsub = x.cols(idx-1);
 return xsub;
}
// [[Rcpp::export]]
arma::mat testrows(arma::mat x, arma::Col idx) {
 arma::mat xsub;
 xsub = x.rows(idx-1);
 return xsub;
}
// [[Rcpp::export]]
arma::mat testcr(arma::mat x, arma::Col ridx, arma::Col cidx) {
 arma::mat xsub;
 xsub = x.submat(ridx-1, cidx-1);
 return xsub;
}

In R:

> sourceCpp("main.cpp")
> matrix(1:16, 4)
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16
> y1 = testcols(matrix(1:16, 4), c(1, 3))
> y1
     [,1] [,2]
[1,]    1    9
[2,]    2   10
[3,]    3   11
[4,]    4   12
> y2 = testrows(matrix(1:16, 4), c(1, 3))
> y2
     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    3    7   11   15
> y3 = testcr(matrix(1:16, 4), c(2, 4), c(2, 4))
> y3
     [,1] [,2]
[1,]    6   14
[2,]    8   16

0 comments: