<div dir="ltr">You can avoid one copy operation by declaring X as<div><br></div><div> const MSpMat X(as<MSpMat>(xx_));</div><div><br></div><div>As it is you are allocating storage for a copy of the sparse matrix which will not be modified and hence does not need to be copied.</div>
</div><div class="gmail_extra"><br><br><div class="gmail_quote">On Tue, Dec 10, 2013 at 11:33 AM, Dirk Eddelbuettel <span dir="ltr"><<a href="mailto:edd@debian.org" target="_blank">edd@debian.org</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><br>
On 9 December 2013 at 22:14, Søren Højsgaard wrote:<br>
| Dear all,<br>
| Using RcppEigen I've created a function for converting a sparse matrix (a dgCMatrix) to a standard dense matrix:<br>
|<br>
| typedef Eigen::SparseMatrix<double> SpMatd;<br>
| typedef Eigen::MappedSparseMatrix<double> MSpMat;<br>
|<br>
| // [[Rcpp::export]]<br>
| SEXP do_dgCMatrix2matrix ( SEXP XX_ ){<br>
|   S4 DD(wrap(XX_));<br>
|   List dn = clone(List(DD.slot("Dimnames")));<br>
|   SpMatd X(as<SpMatd>(XX_));<br>
|   Eigen::MatrixXd dMat;<br>
|   dMat = Eigen::MatrixXd( X );<br>
|   NumericMatrix Xout(wrap(dMat));<br>
|   Xout.attr("dimnames") = dn;<br>
|   return Xout;<br>
| }<br>
|<br>
| The function does what I expect it to, but I am curious about how many times I really create some sort of "copy" of my input matrix and when all I do is put a small layer of "vernish" over my input matrix?<br>

|<br>
| 1) dMat is dense matrix, and that must (I guess) refer to new "object"??<br>
|<br>
| 2) X is a sparse matrix, and I suppose it is a new object??<br>
|<br>
| 2') If I had declared it to be MSpMat, then it would really just be the input object with a few bells and whistles??<br>
|<br>
| 3) But how about DD and Xout? Are they new objects (in terms of memory usage)?<br>
|<br>
| Put differently, if my input matrix occupies B bytes of memory, how many times B have I then created along the way?<br>
<br>
Unsure. You really need to look.<br>
<br>
For sure when i) clone is called, ii) each time you pass from sparse to dense<br>
and back.  For the others, you need to dig deeper.<br>
<span class="HOEnZb"><font color="#888888"><br>
Dirk<br>
<br>
--<br>
Dirk Eddelbuettel | <a href="mailto:edd@debian.org">edd@debian.org</a> | <a href="http://dirk.eddelbuettel.com" target="_blank">http://dirk.eddelbuettel.com</a><br>
_______________________________________________<br>
Rcpp-devel mailing list<br>
<a href="mailto:Rcpp-devel@lists.r-forge.r-project.org">Rcpp-devel@lists.r-forge.r-project.org</a><br>
<a href="https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel" target="_blank">https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel</a><br>
<br>
</font></span></blockquote></div><br></div>