Hi,<br><br>I'm trying to use Rcpp to speed up some nasty <span style="font-family:courier new,monospace">for</span> loops in my R code (Ubuntu 12.04, R 2.15.2, Rcpp 0.10.1, gcc 4.6.3). However, I'm a newbie to C and to Rcpp, and I'm having trouble returning the correct output. Basically, I input an R matrix to an inline (using Rcpp plugin) C function that runs through each element of the matrix and performs some calculations to generate an array (float). When I run the program in C, it calculates the correct values. However, when I run it in R, it give erratic results. Here is example code that results in the same problem:<br>
<span style="font-family:courier new,monospace">test_src <- '<br>Rcpp::NumericMatrix my_matrix(a); // input matrix<br>int num_rows = my_matrix.nrow(), num_cols = my_matrix.ncol(); // extract matrix dimensions<br>
float my_sum[50];<br>float my_sum2[50];<br>Rcpp::NumericVector my_expr(num_cols); // output array<br><br> for(int i = 0; i < num_rows; i++) {<br> for(int j = 0; j < num_cols; j++) {<br> my_sum[j] = my_sum[j] + my_matrix(i,j); // sum columns<br>
my_sum2[j] = (my_sum[j] + j); // sum columns plus the column index<br> }<br> }<br> for(int j = 0; j < num_cols; j++) {<br> my_expr[j] = my_sum[j] / my_sum2[j]; // divide sum by sum2<br>
}<br>return my_expr;<br>'<br>test_func <- cxxfunction(signature(a = "numeric"), test_src, plugin = "Rcpp")<br><br>my_matrix <- matrix(c(0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0), nrow = 5, ncol = 8)<br>
<br>test_func(my_matrix)</span><br><br>When I run this, I get:<br><span style="font-family:courier new,monospace">1.0000000 0.6666667 NaN NaN 1.0000000 0.2857143 0.3333333 0.3000000<br></span><br>If I run the following in C:<br>
<span style="font-family:courier new,monospace">int num_rows = 5, num_cols = 8;<br>int my_matrix[5][8];<br>float my_sum[50];<br>float my_sum2[50];<br>float my_expr[50];<br>int my_matrix[5][8] = {<br> {0, 1, 1, 0, 1, 0, 0, 1},<br>
{1, 0, 0, 0, 0, 0, 0, 1},<br> {0, 0, 1, 0, 1, 1, 1, 1},<br> {0, 1, 1, 0, 0, 0, 1, 1},<br> {0, 0, 1, 0, 1, 1, 1, 0}<br>};<br><br>int main () {<br> for(int i = 0; i < num_rows; i++) {<br> for(int j = 0; j < num_cols; j++) {<br>
my_sum[j] = my_sum[j] + my_matrix[i][j]; // sum columns<br> my_sum2[j] = (my_sum[j] + j); // sum columns plus the column index<br> }<br> }<br> for(int j = 0; j < num_cols; j++) {<br> my_expr[j] = my_sum[j] / my_sum2[j]; // divide sum by sum2<br>
printf("%f\t", my_expr[j]);<br> }<br>}</span><br><br>I get<br><span style="font-family:courier new,monospace">1.000000 0.666667 0.666667 0.000000 0.428571 0.285714 0.333333 0.363636</span><br>
<br>I'm sure that there is something simple that I am doing wrong. Any suggestions?<br><br>Thanks,<br>Jeff<br>