%%Thanks to David Warde-Farley for writing this code. genlength=1500; LA=length(alphabet); outstr=[]; state=ceil(rand(1,1)*K); fprintf('\nGenerating string from hidden Markov model...\n') for i = 1:genlength % Choose an output outputprobs = E(:,state)'; therand2=rand(1,1); for q = 1:LA if (therand2 > sum(outputprobs(1:q-1)') & therand2 < sum(outputprobs(1:q)')) outstr = [outstr, alphabet(q)]; break; end; end; % Figure out who we should move to next... it's important to note which % axis means which, otherwise you might end up with your generated % string backwards. stateprobs = P(state, :)'; therand=rand(1,1); for j = 1:K if (therand > sum(stateprobs(1:j - 1)) & therand <= sum(stateprobs(1:j))) state = j; % fprintf('Moving to state %d\n', state) break; end; end; end; fprintf('\n%s\n',outstr);