# Dimension of the transition matrix dim=2 # Parameter definition a=0.2; b=0.4; # Definition of the transition matrix P=matrix(c(1-a,a,b,1-b),nrow=dim,ncol=dim,byrow=TRUE) # Number of time steps N=100 # Encoding of chain values Z=array(N+1); for(ll in seq(1,N)) { Z[1]=sample(dim,size=1,prob=P[2,]) # Random simulation of Z[j+1] given Z[j] for (j in seq(1,N)) Z[j+1]=sample(dim,size=1,prob=P[Z[j],]) Y=array(N+1); S=0; # Computation of the average over the l first steps for(l in seq(1,N+1)) { Z[l]=Z[l]-1; S=S+Z[l]; Y[l]=S/l; } X=array(N+1); for(l in seq(1,N+1)) { X[l]=l-1; } par(mfrow=c(2,1)) plot(X,Y,type="l",yaxt="n",xaxt="n",xlim=c(0,N),xlab="",ylim= c(0,1),ylab="",xaxs="i", col="black",main="",bty="n") segments(0,a/(a+b),N,a/(a+b)) axis(2,pos=0,at=c(0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0)) axis(1,pos=0,at=seq(0,N,10),outer=TRUE) plot(X,Z,type="o",xlab="",ylab="",xlim=c(0,N),yaxt="n",xaxt="n",xaxs="i", col="black",main="",pch=20,bty="n") axis(1,pos=1,at=seq(0,N+1,10),outer=TRUE,padj=-4,tcl=0.5) axis(1,pos=0,at=seq(0,N+1,10),outer=TRUE) axis(2,las=2,at=0:1) readline(prompt = "Pause. Press to continue...") } #MCMC poisson.metro=function(lambda,i,n) #i:starting value { y=seq(n) for(k in 1:n) { u1=runif(1) j =if(u1<.5) ifelse(i==0,i,i-1) else i+1 #symm. random walk if i>0 r =switch(i+2-j,lambda/j,1,i/lambda) u2 =runif(1) new=if(r>=1) j else {if(u2