[Rcpp-devel] Help with SubMatrix test case
Douglas Bates
bates at stat.wisc.edu
Sat Dec 4 15:32:42 CET 2010
On Fri, Dec 3, 2010 at 11:00 PM, Christian Gunning <xian at unm.edu> wrote:
>> | The first three look correct to me:
>> | i) assign 3, 4, 5
>> | ii) copy row 0 as 1
>> | iii) copy col 3 to 4
>> |
>> | but I am also a little puzzled by the last submatrix.
>> |
>> | I'm sure Romain will weigh in in a few hours.
>
>> In the mean time, we can of course use the trusted Armadillo library and the
>> RcppArmadillo converters:
>>
>> R> src2 <- '
>> + NumericMatrix xx(4, 5);
>> + xx(0,0) = 3;
>> + xx(0,1) = 4;
>> + xx(0,2) = 5;
>> + xx(1,_) = xx(0,_);
>> + xx(_,3) = xx(_,2);
>> + arma::mat mm( xx.begin(), 4, 5, false );
>> + arma::mat sm = mm.submat(0,0,2,3);
>> + return(wrap(sm));
>> + '
>> R> myfun2 <- cxxfunction( , src2, plugin='RcppArmadillo')
>> R> aa2 <- myfun2()
>> R> aa2
>> [,1] [,2] [,3] [,4]
>> [1,] 3 4 5 5
>> [2,] 3 4 5 5
>> [3,] 0 0 0 0
>> R>
>>
>> That looks more like it.
>>
>
> Interesting. Here's a fully-formed example:
>
> src3 <- '
> int rr = 4, cc = 5;
> List ret;
> NumericMatrix xx(rr, cc);
> RNGScope scope;
> NumericVector zz = rnorm(rr*cc);
> for (int i = 0; i<rr*cc; i++) {
> xx[i] = zz[i];
> }
A minor point but I think it is more STLish to write that loop as
std::copy(zz.begin(), zz.end(), xx.begin());
For large matrices, calling xx[i] and zz[i] for each element could add
some overhead.
> xx(1,_) = xx(0,_);
> xx(_,1) = xx(_,0);
>
> ret["fullmat"] = xx;
> NumericMatrix yy1 = xx( Range(0,2), Range(0,3) ) ;
> ret["submat"] = yy1;
>
> NumericVector zz2 = xx( _, 1);
> ret["col"] = zz2;
>
> arma::mat mm( xx.begin(), rr, cc, false );
> arma::mat sm = mm.submat(0,0,2,3);
> ret["arma"] = wrap(sm);
> return(ret);
> '
>
> myfun3 <- cxxfunction( , src3, plugin='RcppArmadillo')
> aa3 <- myfun3()
>
> identical(aa3$col, aa3$fullmat[,2])
> [1] TRUE
> identical(aa3$arma, aa3$fullmat[1:3,1:4])
> [1] TRUE
> identical(aa3$submat, aa3$arma)
> [1] FALSE
>
> -christian
>
> --
> A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!
> _______________________________________________
> 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
>
More information about the Rcpp-devel
mailing list