Konstruktion einer Markov-Kettenübergangsmatrix mit mehreren Ordnungen in Matlab

Eine Übergangsmatrix erster Ordnung aus 6 Zuständen kann seinsehr elegant gebaut wie folgt

 x = [1 6 1 6 4 4 4 3 1 2 2 3 4 5 4 5 2 6 2 6 2 6]; % the Markov chain
 tm = full(sparse(x(1:end-1),x(2:end),1)) % the transition matrix.

Also hier ist mein Problem, wie konstruieren Sie eine Übergangsmatrix zweiter Ordnung elegant? Die Lösung, die ich gefunden habe, lautet wie folgt

 [si sj] = ndgrid(1:6);
 s2 = [si(:) sj(:)]; % combinations for 2 contiguous states
 tm2 = zeros([numel(si),6]); % initialize transition matrix
 for i = 3:numel(x) % construct transition matrix
   tm2(strmatch(num2str(x(i-2:i-1)),num2str(s2)),x(i))=...
   tm2(strmatch(num2str(x(i-2:i-1)),num2str(s2)),x(i))+1;
 end

Gibt es eine Ein / Zwei-Liner-No-Loop-Alternative?

-

Edit: Ich habe versucht, meine Lösung mit der von Amro zu vergleichen: "x = round (5 * rand ([1,1000]) + 1)".

 % ted teng's solution
 Elapsed time is 2.225573 seconds.
 % Amro's solution
 Elapsed time is 0.042369 seconds. 

Was für ein Unterschied! Zu Ihrer Information,grp2idx ist online verfügbar.

Antworten auf die Frage(1)

Ihre Antwort auf die Frage