RosscoAP
RosscoAP

Reputation: 33

Matrix indexing via integer vector

I want to access non-consecutive matrix elements and then pass the sub-selection to (for instance) the sum() function. In the example below I get a compile error about invalid conversion. I am relatively new to Rcpp, so I am sure the answer is simple. Perhaps I am missing some type of cast?

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

double sumExample() {
    // these are the matrix row elements I want to sum (the column in this example will be fixed)
    IntegerVector a = {2,4,6}; 
    // create 10x10 matrix filled with random numbers [0,1]
    NumericVector v = runif(100);
    NumericMatrix x(10, 10, v.begin()); 
    // sum the row elements 2,4,6 from column 0
    double result = sum( x(a,0) );
    return(result);
}

Upvotes: 3

Views: 186

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368389

You were close. Indexing uses [] only -- see this write up at the Rcpp Gallery -- and you missed the export tag. The main issue is that compound expresssion are sometimes too much for the compiler and the template programming. So it works if you take it apart.

Corrected Code

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
double sumExample() {
    // these are the matrix row elements I want to sum
    // (the column in this example will be fixed)
    IntegerVector a = {2,4,6};
    // create 10x10 matrix filled with random numbers [0,1]
    NumericVector v = runif(100);
    NumericMatrix x(10, 10, v.begin());
    // sum the row elements 2,4,6 from column 0
    NumericVector z1 = x.column(0);
    NumericVector z2 = z1[a];
    double result = sum( z2 );
    return(result);
}

/*** R
sumExample()
*/

Demo

 R> Rcpp::sourceCpp("~/git/stackoverflow/56739765/question.cpp")

 R> sumExample()
 [1] 0.758416
 R>

Upvotes: 3

Related Questions