% This code simulates a n-state Markov chain up to T periods.  The user
% must supply a n x n transition matrix P, the state vector z, the initial state and T.  Written by Philip Shaw,
% Fordham University, 2018.
function[zsim]=markovsim(P,z,T,state);

kz=length(z); %calculate the number of possible states
state0=z(state); %initialize the state
for i=1:T-1
    U=rand; %generate a draw from a uniform random variable on [0,1]
    for j=1:kz %loop over all possible states
        temp(j,1)=sum(P(state,1:j)); %sum over columns 1:j
        ind(j,1)=(U<=temp(j)); %find if sum of columns from 1:j is >=U
        indf=find(ind==1); 
    end
    state=indf(1); %update state based upon new draw
    zsim(i,1)=z(state); %store the new draw
end 
zsim=[state0;zsim]; %the simulated series for z


