Armadillo subsetting

January 2, 2013

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

A StackOverflow question asked how convert from arma::umat to arma::mat. The former is format used for find and other logical indexing.

For the particular example at hand, a call to the conv_to converter provided the solution. We rewrite the answer here using the newer format offered by Rcpp attributes and its sourceCpp() function.

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp ;

// [[Rcpp::export]]
arma::mat matrixSubset(arma::mat M) {
    // logical conditionL where is transpose larger?
    arma::umat a = trans(M) > M;   
    arma::mat  N = arma::conv_to<arma::mat>::from(a);
    return N;
M <- matrix(1:9, 3, 3)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    0    0
[3,]    1    1    0

This generalizes to other uses, and the vector or matrix of unsigned ints can be used inside the elem() member function. Here were we return all values of M * M' that are greater or equal to 100.

// [[Rcpp::export]]
arma::vec matrixSubset2(arma::mat M) {
    arma::mat Z = M * M.t();
    arma::vec v = Z.elem( arma::find( Z >= 100 ) );
    return v;

The result:

[1,]  108
[2,]  108
[3,]  126

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)