c++rc++11rcpprcpp11

Create diagonal matrix in Rcpp but the result is wrong


The code is supposed to create a diagonal matrix with value 1.

// [[Rcpp::export]]
NumericMatrix filterOne(int g_size){

    NumericMatrix filter(g_size, g_size);   
    int ptr, ptr2;

    for(ptr=0;ptr<g_size;ptr++){
        Rcout << ptr << endl;
        filter[ptr, ptr] = 1;       
    }
    
    // the following printing is
    // for checking the content
    for(ptr=0;ptr<g_size;ptr++){    
        for(ptr2=0;ptr2<g_size;ptr2++){         
            Rcout << ptr+1 << " - " << ptr2+1 << " : " << filter[ptr, ptr2] <<  endl;
        }
    }

return filter;
}

So I call x = filterOne(3) in R environment, and the result is :

0
1
2
1 - 1 : 1
1 - 2 : 1
1 - 3 : 1
2 - 1 : 1
2 - 2 : 1
2 - 3 : 1
3 - 1 : 1
3 - 2 : 1
3 - 3 : 1

It seems that all cells have the value 1. Then, simply type x to see the returned matrix value in RGUI:

     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    0    0
[3,]    1    0    0

How can this comes?

Please let me know if someone uses the same code but can generate the correct result. Many thanks.


Solution

  • I think the issue is with how you have accessed the NumericMatrix elements. You should use ( ) instead of [ ]. The following works:

    // [[Rcpp::export]]
    NumericMatrix filterOne(int g_size){
      NumericMatrix filter(g_size, g_size);   
      int ptr, ptr2;
      
      for(ptr=0;ptr<g_size;ptr++){
        filter(ptr, ptr) = 1;       
      }
      
      return filter;
    }
    
    > filterOne(3)
         [,1] [,2] [,3]
    [1,]    1    0    0
    [2,]    0    1    0
    [3,]    0    0    1