资源描述:
《马尔可夫编程matlab》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、%function[chain,state]=markov(T,n,s0,V);%function[chain,state]=markov(T,n,s0,V);%chaingeneratesasimulationfromaMarkovchainofdimension%thesizeofT%%Tistransitionmatrix%nisnumberofperiodstosimulate%s0isinitialstate(initialprobabilities)%Visthequantitycorre
2、spondingtoeachstate%stateisamatrixrecordingthenumberoftherealizedstateattimet%%Originalauthor:TomSargent%CommentsaddedbyQiangChen[rc]=size(T);%ris#ofrows,cis#ofcolumnsofTifnargin==1;%"nargin"refersto"numberofargumentsin".SoonlyTisprovidedinthiscaseV=[1:
3、r];s0=1;n=100;end;ifnargin==2;%bothTandnareprovidedV=[1:r];s0=1;end;ifnargin==3;%T,nandS0areprovidedV=[1:r];end;%checkifthetransitionmatrixTissquareifr~=c;disp('errorusingmarkovfunction');disp('transitionmatrixmustbesquare');return;%breaktheprogramandre
4、turnend;%checkifeachrowofTsumsupto1fork=1:r;ifsum(T(k,:))~=1;disp('errorusingmarkovfunction')disp(['row',num2str(k),'doesnotsumtoone']);%"num2str"convertsnumberstoastring.disp('itsumsto:');disp([sum(T(k,:))]);disp(['normalizingrow',num2str(k),'']);T(k,:
5、)=T(k,:)/sum(T(k,:));end;end;[v1v2]=size(V);ifv1~=1
6、v2~=r%"
7、"means"or"disp('errorusingmarkovfunction');disp(['statevaluevectorVmustbe1x',num2str(r),''])ifv2==1&v2==r;disp('transposingstatevaluationvector');V=V';%changeittoacolumnvectorelse;return;end;en
8、difs0<1
9、s0>r;disp(['initialstate',num2str(s0),'isoutofrange']);disp(['initialstatedefaultingto1']);s0=1;end;%ThesimulationofMarkovchainformallystartsfromhere%T%rand('uniform');X=rand(n-1,1);%generate(n-1)randomnumbersdrawnfromuniformdistributionon[0,1],
10、eachnumbertobeusedinonesimulation.s=zeros(r,1);%initiatethestatevector"s"tobearx1zerovectors(s0)=1;%changethe"s0"thelementof"s"to1cum=T*triu(ones(size(T)));%"triu(ones(size(T)))"generatesanuppertriangularmatrixwithallelementsequalto1%cumisarxrmatrixwhos
11、eithcolumnisthecumulativesumfromthe1stcolumntotheithcolumn%theithrowofcumisthecumulativedistributionforthenextperiodgiventhecurrentstate.fork=1:length(X);%"length(X)"returnsthesizeofthelongestdimensionofX."k"indicatesthekthsimula