title: Returning bunch of matrices using RCPP in C++ in an efficient way using a list
body: <p>I am trying to return a bunch of matrices using RCPP. My code below is extremely inefficient. I would like to know if the following code can be efficient.</p>
  
  <pre><code>#include &lt;RcppArmadillo.h&gt;
  // [[Rcpp::depends(RcppArmadillo)]]
  
  // [[Rcpp::export]]
  Rcpp::List hello( 
      const arma::rowvec&amp; g,
      const int&amp; n, 
      const int&amp; p,
      const arma::mat&amp; S,
      const arma::mat&amp; zc,
      const arma::rowvec&amp; dl){
    Rcpp::List ht(n);
  
    for(int t=0; t &lt; n;++t){
  
      arma::mat hhat(p,n);
      hhat.fill(0.0);
      for(int i = 0;i &lt; n; ++i){
        arma::mat h(p,1);
        h.fill(0.0);
        if (t &gt; i){
          for(int u=i;u &lt;= t; ++u){
            arma::rowvec zr = zc.rows(i,i);
            h += exp(arma::as_scalar(g*zr.t())) * (zr.t() - S.cols(u,u))*dl(u);
          }
        }
        hhat.cols(i,i) = h;
      }
      ht[t] = hhat;
    }
  
    // Specify list length
    Rcpp::List res(1);
    res[0] = ht;
  
    return(res);
  }
  </code></pre>
  
  <p>Here is the example. </p>
  
  <pre><code>g=c(1,2.1,3.1)
  n=1600
  p=3
  S = matrix(rnorm(4800),nrow=3,ncol=1600)
  dl=runif(1600)
  z=matrix(runif(4800),nrow=1600,ncol=3)
  ptm=proc.time();kkk= hello(g=g,n=n,p=p,S = S,zc=z,dl = dl);proc.time()-ptm;
   user  system elapsed 
    31.25    0.00   31.30 
  </code></pre>
  
  <p>Any help would be appreciated.</p>
  
  <p>Following the updated code. Initially I was returning list of a list. Now it returns a list. This reduces the computing time by 10 seconds. I hope this code can be improved further.</p>
  
  <pre><code>#include &lt;RcppArmadillo.h&gt;
  // [[Rcpp::depends(RcppArmadillo)]]
  
  // [[Rcpp::export]]
  Rcpp::List hello( 
      const arma::rowvec&amp; g,
      const int&amp; n, 
      const int&amp; p,
      const arma::mat&amp; S,
      const arma::mat&amp; zc,
      const arma::rowvec&amp; dl){
    Rcpp::List ht(n);
  
  
    for(int t=0; t &lt; n;++t){
  
      arma::mat hhat(p,n);
      hhat.zeros();
      for(int i = 0;i &lt; n; ++i){
        arma::mat h(p,1);
        // h.fill(0.0);
        h.zeros();
        if (t &gt; i){
          for(int u=i;u &lt;= t; ++u){
            //arma::rowvec zr = zc.rows(i,i);
            h += exp(arma::as_scalar(g*zc.row(i).t())) * (zc.row(i).t() - S.col(u))*dl(u);
          }
        }
        hhat.col(i) = h;
      }
      ht[t] = hhat;
    }
  
    // Specify list length
    // Rcpp::List res(1);
    // res[0] = ht;
  
    return(ht);
  }
  </code></pre>
  
  <p>The formula that I am trying to implement is given below.<a href="https://i.stack.imgur.com/WPxA8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WPxA8.png" alt="enter image description here"></a></p>