ann
ann

Reputation: 41

Sum of matrix element in Rcpp

I am NewBie to Rcpp and R. I tried to compute the edge count or the wedge count from a adjacency matrix. For that I write the followin code in Rcpp.


#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double wedge_cnt_cpp(NumericMatrix x){
  
  size_t  n = x.nrow();
  double temp = 0.0;
  
  for(size_t i=0; i<n; i++){
    for(size_t j=0; j<n; j++){
      for(size_t k=0; k<n; k++)
      temp = temp + x[i][j]*x[j][k];
    }
  }
    return temp;
}

This code gives the following error

subscripted value is not an array, pointer, or vector

I'm unable to detect the error, any kind of help appreciated.

Upvotes: 0

Views: 195

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102599

I think you should use x(i,j) instead of x[i][j], and return double type temp to play it say if your input is double. For example

library(Rcpp)

sourceCpp(
    code = "
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double wedge_cnt_cpp(NumericMatrix x){

  size_t  n = x.nrow();
  double temp = 0;

  for(size_t i=0; i<n; i++){
    for(size_t j=0; j<n; j++){
      for(size_t k=0; k<n; k++)
      temp = temp + x(i, j) * x(j,k);
    }
  }
    return temp;
}"
)

and you will see

> set.seed(0)

> (A <- matrix(sample.int(4), 2))
     [,1] [,2]
[1,]    2    4
[2,]    1    3

> (B <- matrix(runif(4), 2))
          [,1]      [,2]
[1,] 0.9082078 0.8983897
[2,] 0.2016819 0.9446753

> wedge_cnt_cpp(A)
[1] 46

> wedge_cnt_cpp(B)
[1] 4.117935

Upvotes: 0

Related Questions