文档介绍:%function [chain,state]=markov(T,n,s0,V);
%function [chain,state]=markov(T,n,s0,V);
% chain generates a simulation from a Markov chain of dimension
% the size of T
%
% T is transition matrix
% n is number of periods to simulate
% s0 is initial state (initial probabilities)
% V is the quantity corresponding to each state
% state is a matrix recording the number of the realized state at time t
%
% Original author: Tom Sargent
% Comments added by Qiang Chen
[r c]=size(T); % r is # of rows, c is # of columns of T
if nargin == 1; % "nargin" refers to "number of arguments in". So only T is provided in this case
V=[1:r];
s0=1;
n=100;
end;
if nargin == 2; % both T and n are provided
V=[1:r];
s0=1;
end;
if nargin == 3; % T, n and S0 are provided
V=[1:r];
end;
% check if the transition matrix T is square
if r ~= c;
disp('error using markov function');
disp('transition matrix must be square');
return; % break the program and return
end;
% check if each row of T sums up to 1
for k=1:r;
if sum(T(k,:)) ~= 1;
disp('error using markov function')
disp(['row ',num2str(k),' does not sum to one']); % "num2str" converts numbers to a string.
disp(' it sums to :');
disp([ sum(T(k,:)) ]);
disp(['normalizing row ',num2str(k),'']);
T(k,:)=T(k,:)/sum(T(k,:));
end;
end;
[v1 v2]=size(V);
if v1 ~= 1 | v2 ~=r % "|" means "or"
disp('error using markov function');