[Rcpp-devel] Returning Armadillo matrices with dimnames
Dirk Eddelbuettel
edd at debian.org
Thu May 2 22:06:50 CEST 2013
On 2 May 2013 at 14:33, Sameer D'Costa wrote:
| Thanks for the reply Dirk.
|
| On Thu, May 2, 2013 at 12:53 PM, Dirk Eddelbuettel <edd at debian.org> wrote:
| >
| > Hi Sameer,
| >
| > On 2 May 2013 at 10:16, Sameer D'Costa wrote:
| > | Hi,
| > |
| > | I am trying to return several Armadillo matrices back to R and to set
| > | the names for the rows and the columns of each matrix. I have tried
| > | converting each Armadillo matrix to a NumericMatrix and then setting
| > | the dimnames on that before returning a list to R. This seems to work
| > | (see snippet below) however I am not sure if this is the right way to
| > | go or if I am converting the matrices properly or if extra copies are
| > | being made. Any advice will be appreciated.
| >
| > That looks pretty good. I would simply change to things:
| >
| > -- on entry, create an Armadillo matrix "two-step-way" we have been using
| > here a lot (and which is used eg in fastLm.cpp): create a NumericMatrix
| > from SEXP (no copies), then instantiate arma::mat() using the begin()
| > iterator, row, cols and FALSE --- and that way you are sure that only
| > pointers to the original memory get copied, and the content itself should
| > not.
| > -- on exit, do the reverse: do you Armadillo calculations, then access the
| > memory behind the arma matrix (also guaranteed to be contiguous) to
| > instantiate an Rcpp NumericMatrix. Then set the attributes as you do
| > below and return it.
|
| I understand how to do the entry based on what fastLm.cpp is doing.
| I'm more interested in the exit because in my real work I have the
| matrices generated in c++ itself. I put the entry code just to have a
| self contained inline example to send to the list. However, I'm not
| sure how to do the exit in the way you describe. Would you be able to
| tell me how to use the relevant NumericMatrix constructor or point me
| to an example somewhere? Thanks.
>From a quick look at the header file Matrix.h it seems that
template <typename Iterator>
Matrix( const int& nrows_, const int& ncols, Iterator start ) ;
should be what you are after. (The various types are just typedefs to the
templated variants of Matrix for int, double, char, ...)
But do check the source file to be sure and maybe do a quick performance for
both 'small' and 'large' matrices -- run-time should be constant if there are
only pointer copies.
Dirk
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list