Anybody know how to make this code faster, more efficient (esp. the loop part)? It gets really slow with large n and large matrices.
It is a population model of an organism that has prob 0.55 of finding the right circumstances to mate (coming out of the ground and having enough moon light to find each other, no moon light = reduced reproduction). Its a published model I want to adapt and use so I'm reviewing the code.. but I think it probably not as efficient as it could be (involves matrix multiplication in a loop). Any idea's???
#initial config
mat=matrix(
c(0.4,0,2,20,
0.1,0.4,0,0
,0,0.1,0.65,0
,0,0,0.001,0.75)
,byrow=T,ncol=4)
fmat=matrix(
c(0.4,0,19,199,
0.1,0.4,0,0
,0,0.1,0.65,0
,0,0,0.001,0.75)
,byrow=T,ncol=4)
n=400
fvector=c(0,sample(c(0,1),n,prob=c((1-0.55),0.55), replace=T))
N1=matrix(seq(1000,1,-(1000/dim(mat)[1])))
i=1
N=matrix(ncol=(length(N1)+1),nrow=n+1)
N=data.frame(N);N[1,]=c(t(N1),sum(N1))
colnames(N)=c(1:length(N1),"T")
#step 1
i=i+1
if(fvector[i]==0) New.N=mat%*%N1 else New.N=fmat%*%N1
N[i,]=c(t(New.N),sum(New.N))
########## Start actual loop##########################
while(i<(n+1)){
i=i+1
if(fvector[i]==0) New.N=mat%*%New.N else New.N=fmat%*%New.N
N[i,]=c(t(New.N),sum(New.N))
}
#THANKS!!
The true ideals of great philosophies always seem to get lost somewhere along the road..
|
|