0

I want to create a 2 dimensional array of 100,000 by 100,000 that contains values of Cp. so i get Cp[1,] ,Cp[2,] , Cp[3,] and so on then find all the mean for Cp[1,] and store it as meanCp[1], mean of Cp[2,] and store as meanCp[2]. Is there a better and faster way of doing this than i have here?

K=0.5
x=numeric()
stdCp=numeric()
meanCp=numeric()
u0=0
Cp <- matrix(0,100000,100000)
for (j in 1:100000) {
  x=rnorm(100000,0,1)
  for (i in 1:100000) {    
    if (j==1){
     Cp[j,i]= max(0,x[i]-(u0+K))
    } else {
       Cp[j,i]= max(0,x[i]-(u0+K)+Cp[j-1,i])
    }
  }
 meanCp[j]=mean(Cp[j,])
 stdCp[j]=sd(Cp[j,])
}
meanCp

so for example meanCp[1] gives me a value between 0.19 and 0.20

user3327637
  • 109
  • 6
  • 1
    the inner for loop can be replaced with the much faster `pmax()`, and the calculation of meanCp and stdCp can be accomplished with the much faser `rowMeans()`, as in the updated response to [this answer](http://stackoverflow.com/questions/30017316/for-loop-taking-forever-possible-to-apply/30017970#30017970) – Jthorpe May 15 '15 at 05:52
  • How much memory do you have to do a thing like this? Did you realize that allocating a 100000*100000 matrix needs about 70Gb? – nicola May 15 '15 at 06:19
  • yes u are right. it gives error message with 100,000 X100000. Error: cannot allocate vector of size 7.5 Gb In addition: Warning messages: 1: In matrix(0, 10000, 1e+05) : Reached total allocation of 3988Mb: see help(memory.size) – user3327637 May 15 '15 at 07:20

1 Answers1

0

you can take reference at colMeans function. Some other functions in the same help html would be also useful.