# [Rcpp-devel] Push back to a matrix

Noah Silverman noahsilverman at ucla.edu
Mon Sep 5 19:04:22 CEST 2011

```Good idea.  Thank You!!

--
Noah Silverman
UCLA Department of Statistics
8117 Math Sciences Building #8208
Los Angeles, CA 90095

On Sep 5, 2011, at 9:46 AM, Douglas Bates wrote:

> On Mon, Sep 5, 2011 at 11:31 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:
>> Hi,
>> Using Rcpp through inline.
>> I want to return a matrix, but I don't know the size beforehand.  (My code
>> loops through a large data set accumulating certain statistics.)
>> With a NumericVector, I can use push_back() to just add values to the end of
>> the vector as they occur.  Is there similar functionality for a
>> NumericMatrix?
>> Alternately, I could store all my generated statistics in several vectors
>> (6-7) and then, when complete with my loop, glue them together into a
>> matrix.  But, this seems inefficient.
>
> Not really.  The inefficient method is using push_back() on an Rcpp
> object because it requires copying the existing vector to new storage
> every time you add an element.
>
> My suggestion is to use std::vector<double> objects to accumulate the
> results, then allocate the Rcpp::NumericMatrix and copy the results
> into columns of that matrix.  Because the matrix will be in
> column-major ordering you can do the copying using std::copy which is
> reasonably efficient and less error prone than other methods.
> However, this suggestion, like all other cases of determining
> efficient ways to perform a calculation, should be benchmarked against
> other methods.
>
>> Here is a rough example of what I'm trying to do.
>> ------------------------------
>> int n = inputData.size();
>> Rcpp::NumericMatrix output;
>> for(int i=0; i != n; i++){
>> // generate some stats with a lot of code not shown
>> foo = mean(stuff);
>> bar = min(stuff);
>> baz = max(stuff);
>> // etc...
>> output.push_back(foo, bar, baz);
>> )
>> return output;
>> -------------------------------
>>
>> --
>> 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
>>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110905/940a211b/attachment.htm>
```