Question
Rcpp matrix: loop over rows, one column at a time
This is my first time trying Rcpp and this very simple problem is giving me trouble. I want to use nested for loops to operate on individual values of a matrix, one column at a time. The script I'm aiming for would look something like this:
src <- '
Rcpp::NumericMatrix Am(A);
int nrows = Am.nrow();
int ncolumns = Am.ncol();
for (int i = 0; i < ncolumns; i++){
for (int j = 1; j < nrows; j++){
Am[j,i] = Am[j,i] + Am[j-1,i];
}
}
return Am;
'
fun <- cxxfunction(signature(A = "numeric"), body = src, plugin="Rcpp")
fun(matrix(1,4,4))
The desired output would be this:
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 3 3
[4,] 4 4 4 4
The problem is obviously in this line, where I don't know how to refer to individual elements of the matrix.
Am[j,i] = Am[j,i] + Am[j-1,i];
Apologies if this is a stupid newbie question. Any hint would be appreciated!