2012-06-17 117 views
8
構建多階Markov鏈轉移矩陣

6個州的一階轉移矩陣可以constructed very elegantly as如下在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. 

因此,這裏是我的問題,你如何構建一個二階轉移矩陣優雅? 我想出瞭解決的方法是如下

[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 

是否有一個單/雙內膽,無環的選擇?

-

編輯: 我試圖針對荷銀與比較我的解決辦法 「X =輪(5 *蘭特([1,1000])+ 1);」

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

有什麼區別! 僅供參考,grp2idx在線提供。

回答

8

嘗試以下操作:

%# 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

先生,你是Matlab的@棧交易所之王。即使在星期天! – teng

+2

@tedteng:lol謝謝:) [GRP2IDX](http://www.mathworks.com/help/toolbox/stats/grp2idx.html)函數是統計工具箱的一部分,但您可以用[UNIQUE ](http://www.mathworks.com/help/techdoc/ref/unique.html):'[gn,〜,g] = unique([xy; bigrams],'stable');' – Amro

+0

會是容易將此方法擴展到2維** x **? – HCAI