Armadillo subsetting

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

#include <RcppArmadillo.h>
// [[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)
M


     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

matrixSubset(M)


     [,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:

matrixSubset2(M)


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

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)