[Rcpp-devel] Strange behavior of NumericMatrix

Steve Lianoglou mailinglist.honeypot at gmail.com
Sat Sep 3 08:51:23 CEST 2011


Hi,

On Sat, Sep 3, 2011 at 12:54 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:
> Hi,
>
> Just starting to learn about Rcpp tonight (Using it through the inline library)
>
> I'm attempting to construct a matrix and then fill it with values as I iterate through my function.  The results are wrong.  Am I accessing the cells of the matrix incorrectly?

You are accessing the cells just fine, but you are using the wrong operator.

"^" is a bitwise OR in C++

You are in need of the `pow` function, ie:

R> library(inline)
R> fx <- cxxfunction(
  signature(),
  plugin="Rcpp",
  body="
    Rcpp::NumericMatrix out_xx(10, 4);
    for(int i = 1; i != 10; i++){
      out_xx(i,0) = i;
      out_xx(i,1) = pow(i,2);
      out_xx(i,2) = pow(i,3);
      out_xx(i,3) = pow(i,4);
    }
    return Rcpp::wrap(out_xx);
  ")

R> fx()

      [,1] [,2] [,3] [,4]
 [1,]    0    0    0    0
 [2,]    1    1    1    1
 [3,]    2    4    8   16
 [4,]    3    9   27   81
 [5,]    4   16   64  256
 [6,]    5   25  125  625
 [7,]    6   36  216 1296
 [8,]    7   49  343 2401
 [9,]    8   64  512 4096
[10,]    9   81  729 6561

-steve

> The idea was to have an integer in the first position of each row, and then the polynomials in the subsequent positions.
>
> Any suggestions?
>
> ----------------------------
>
> Here is my test code:
>
> Test2 <- cxxfunction(
>        signature(),
>        plugin="Rcpp",
>        body="
>
>                Rcpp::NumericMatrix out_xx(10, 4);
>                for(int i = 1; i != 10; i++){
>                        out_xx(i,0) = i;
>                        out_xx(i,1) = i^2;
>                        out_xx(i,2) = i^3;
>                        out_xx(i,3) = i^4;
>
>                }
>                return Rcpp::wrap(out_xx);
>
>        "
> )
>
> -----------------------------
>> Test2()
>      [,1] [,2] [,3] [,4]
>  [1,]    0    0    0    0
>  [2,]    1    3    2    5
>  [3,]    2    0    1    6
>  [4,]    3    1    0    7
>  [5,]    4    6    7    0
>  [6,]    5    7    6    1
>  [7,]    6    4    5    2
>  [8,]    7    5    4    3
>  [9,]    8   10   11   12
> [10,]    9   11   10   13
>
>
> --
> Noah Silverman
> UCLA Department of Statistics
> 8117 Math Sciences Building #8208
> Los Angeles, CA 90095
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>



-- 
Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact


More information about the Rcpp-devel mailing list