2012-06-17 6 views
8

una matrice di transizione di primo ordine di 6 stati può essere constructed very elegantly as seguecostruzione di una Markov matrice di transizione catena multi-ordine in Matlab

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. 

Così qui è il mio problema, come si fa a costruire una matrice di transizione del secondo ordine elegantemente? La soluzione mi è venuta è come segue

[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 

c'è un uno/due-liner, no-loop alternativa?

-

Edit: ho provato a confronto la mia soluzione contro Amro di con "x = round (5 * rand ([11.000]) + 1);"

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

Che differenza! FYI, grp2idx è disponibile online.

risposta

8

provare quanto segue:

%# sequence of states 
x = [1 6 1 6 4 4 4 3 1 2 2 3 4 5 4 5 2 6 2 6 2 6]; 
N = max(x); 

%# extract contiguous sequences of 2 items from the above 
bigrams = cellstr(num2str([x(1:end-2);x(2:end-1)]')); 

%# all possible combinations of two symbols 
[X,Y] = ndgrid(1:N,1:N); 
xy = cellstr(num2str([X(:),Y(:)])); 

%# map bigrams to numbers starting from 1 
[g,gn] = grp2idx([xy;bigrams]); 
s1 = g(N*N+1:end); 

%# items following the bigrams 
s2 = x(3:end); 

%# transition matrix 
tm = full(sparse(s1,s2,1,N*N,N)); 
spy(tm) 

transition matrix

+0

Signore, tu sei il re di Matlab @ Stack Exchange. Anche di domenica! – teng

+2

@tedteng: lol thanks :) La funzione [GRP2IDX] (http://www.mathworks.com/help/toolbox/stats/grp2idx.html) fa parte della casella degli strumenti Statistiche, ma è possibile sostituire quella chiamata con [UNIQUE ] (http://www.mathworks.com/help/techdoc/ref/unique.html): '[gn, ~, g] = unique ([xy; bigrams], 'stable');' – Amro

+0

Sarebbe facile estendere questo metodo a 2 dimensioni ** x **? – HCAI

Problemi correlati