clear all clc %一步转移概率矩阵 P=[0.70.30000000 0.700.3000000 00.700.300000 000.700.30000 0000.700.3000 00000.700.300 000000.700.30 0000000.700.3 000000001]; p=P^1000; p(1,9)%理论值 num=0;%记录到达状态9的次数 fori=1:100000%实验次数 state=1;%初始状态为1 forj=1:1000%1000步 if state==1 ifrand()<0.3 state=2; end elseif state==9 state=9; else ifrand()<0.3 state=state+1; else state=state-1; end end if state==9 num=num+1; break; end end end num/100000%仿真值
state=1;%初始状态 num=0;%达到次数 result=0;%需要经过的步数 for k=1:100000%仿真10000次 state=1; fori=1:100000000%设定最大步数(越大越好) if state==1 ifrand()<0.3 state=2; end elseif state==9 state=9; else ifrand()<0.3 state=state+1; else state=state-1; end end if state==9 num=num+1; result=result+i;%记录总的步数 break; end end end