Skip to content

Instantly share code, notes, and snippets.

@timriffe
Created November 21, 2011 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriffe/1384076 to your computer and use it in GitHub Desktop.
Save timriffe/1384076 to your computer and use it in GitHub Desktop.
Pancho Help with crazy iterating things
library(lattice)
nfases <- 4 #nombre de intervals
npasosxint <- 5 #nombre de passes en cada interval
xmax <- 5 #mida matriu
ymax <- 5 #mida amtriu
Avfasenorm <- 1 #quantitat incrementada si no hi ha cap 20
Avfase <- c(1:4,0) # hacemos la vida mas facil
finalmat <-matrix(4,nrow=ymax,ncol=ymax) #matriz objetivo final, detodo 4
# how many trials and iterations:
ntrials <- 25
numrep <- 300
# iteration counter for each trial
nits <- rep(NA,length(ntrials))
for (z in 1:ntrials){
# redefine new mat at each trial
mat <- matrix(sample(1:20,xmax*ymax,replace=TRUE),ncol=xmax)
# matrix of NAs by default
counts <- matrix(nrow=numrep,ncol=5)
colnames(counts) <- 0:4
mat2 <- mat*0
repet <- 0
for (i in 1:numrep){
if (any(mat==20)){
mat <- mat + matrix(Avfase[ceiling(mat / npasosxint)],ncol=xmax)
mat[mat > 20] <- 1
}
else {
mat <- mat+1
}
mat2 <- floor(mat/npasosxint)
counts[i,] <- c(sum(mat2==0),sum(mat2==1),sum(mat2==2),sum(mat2==3),sum(mat2==4))
repet <-repet+1
# si esta condicion cumple, paramos el 'for' sin problemas:
if (all(mat==4)){
#cat("we did it!, just",repet,"iterations!")
break # esto es la salida
}
}
nits[z] <- repet
# cortar todas la filas NA (basado en la primera columna solo)
counts <- counts[!is.na(counts[,1]),]
print(levelplot(t(counts),main=paste("trial",z,",",repet,"iterations")))
Sys.sleep(1)
}
# summary of converged trials
summary(nits[nits<300])
# proportion that didn't converge:
sum(nits==numrep)/ntrials
# overal distribution
hist(nits)
# distribution of converged:
hist(nits[nits<200])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment