0

I'm fairly new with R and I can't get my head around a for loop. I've developed a big markov model based on a loop (now I know it's not the most efficient way but no time to change it now). the final outcome of the model is a pair of matrices for each value of one parameter j. A sample of what I'm trying to do is

for (j in 1:10){ x<-3:13 y<-rep(x[j],10) a<-matrix(y,5,2) y<-rep(2,10) b<-matrix(y,5,2) outcome<-array(0,dim=c(5,2,10)) outcome[,,j]<-a*b } outcome 

that is: saving in the third dimension of the array the output of every loop. But as I see it saves only the last loop in the last dimension of the array. The model is much more complex so that I can't really change the basic structure but only find a way of saving its outputs. Any thoughts? hope it's clear and any help would be really appreciated!

1
  • 1
    PS. Stack snippets don't yet run for R code. Commented Sep 21, 2014 at 19:48

1 Answer 1

2

Remove the outcome<-array(0,dim=c(5,2,10)) from the loop! You're initialising the array to zero at each iteration; that's why all the matrices except the last one are zero. Put this before you start the loop and it will work fine.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.