Daniel@0: function S = sample_mc_endstate(startprob, trans, endprob) Daniel@0: % SAMPLE_MC_ENDSTATE Generate a random sequence from a Markov chain until enter the endstate. Daniel@0: % seq = sample_mc(startprob, trans, endprob) Daniel@0: Daniel@0: % add an end state Daniel@0: Q = size(trans,1); Daniel@0: transprob = zeros(Q,Q+1); Daniel@0: end_state = Q+1; Daniel@0: for i=1:Q Daniel@0: for j=1:Q Daniel@0: transprob(i,j) = (1-endprob(i)) * trans(i,j); Daniel@0: end Daniel@0: transprob(i,end_state) = endprob(i); Daniel@0: %assert(approxeq(sum(transprob(i,:)), 1)) Daniel@0: end Daniel@0: Daniel@0: S = []; Daniel@0: S(1) = sample_discrete(startprob); Daniel@0: t = 1; Daniel@0: p = endprob(S(t)); Daniel@0: stop = (S(1) == end_state); Daniel@0: while ~stop Daniel@0: S(t+1) = sample_discrete(transprob(S(t),:)); Daniel@0: stop = (S(t+1) == end_state); Daniel@0: t = t + 1; Daniel@0: end Daniel@0: S = S(1:end-1); % don't include end state