passerby51
passerby51

Reputation: 955

Rcpp function always returns the zero matrix

I have written a Rcpp function to compute the cosine similarity, between columns of a matrix:

#include <Rcpp.h>
using namespace Rcpp;

// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar)

// For more on using Rcpp click the Help button on the editor toolbar

// [[Rcpp::export]]
NumericMatrix mysimil(NumericMatrix X, NumericVector norms) {
  int nrow = X.nrow(), ncol = X.ncol();
  NumericMatrix out(nrow, ncol);

  for (int i = 0; i < nrow; i++) {
    for (int j = i+1; j < ncol; j++) {
      out(i,j) <- sum(X(_,i)*X(_,j))/(norms[i]*norms[j]);
      out(j,i) <- out(i,j);
    }
  }
  return out;
}

The norms argument will contain the norms of each column when calling the function. The output however is always the zero matrix. Can someone tell me what is going wrong here?

Upvotes: 1

Views: 373

Answers (1)

jbaums
jbaums

Reputation: 27398

The warning that sourceCpp returns when you compile the code (i.e. warning: value computed is not used [-Wunused-value]) suggests that there was a problem with assignment.

Indeed, when assigning values to out, you are using the R assignment operator, <-, instead of the C/C++ operator =. Your <- is still valid C++ code and is treated as an inequality (x <- y is equivalent to x < -y). In this case, your expression asks:

is out(i,j) less than -sum(X(_,i) * X(_,j)) / (norms[i]*norms[j])?

(ideone example)

Correct the operator and values should be assigned correctly.

Upvotes: 7

Related Questions