title: Recursive function: Save output of every call to list
body: <p>I would like to save the output of every function call of the following recursive function to a list.  Moreover, I need to know which (j,l)-pair correspond to which entry of the resulting list.</p>
  
  <p>I have created a stripped down version to reproduce the problem.  Please let me know if I should provide more information to help solve the problem.  Any help is highly appreciated.  Thank you.</p>
  
  <pre><code>#the recursive function
  phi &lt;- function(phik,j,l,k,d) {
    if(j==0) {
      diag(d)
    }
    else{
      if(j==1) {
        if(l&gt;k) {
          0 * diag(d)
        }
        else{
          phik[[l]]      
        }      
      }
      else {
        if(l&gt;k) {
          0 + phi(phik,j-1,l,k,d) %*% phik[[1]]
        }
        else {
          phi(phik,j-1,l+1,k,d) + phi(phik,j-1,l,k,d) %*% phik[[1]]
        }      
      }
    }
  }
  
  #related stuff
  set.seed(123456)
  phik &lt;- vector(mode="list", length=3)
  phik[[1]] &lt;- matrix(rnorm(n=16,mean=0,s=1),nrow=4)
  phik[[2]] &lt;- matrix(rnorm(n=16,mean=0,s=1),nrow=4)
  phik[[3]] &lt;- matrix(rnorm(n=16,mean=0,s=1),nrow=4)
  d &lt;- nrow(phik[[1]])
  k &lt;- length(phik)
  
  #function call
  phiout &lt;- phi(phik,j=10,l=1,k=k,d=d)
  </code></pre>