2012-09-15 106 views
0

我有一個矩陣X,它由我從馬爾可夫鏈得到的一些序列組成。我有5個州1,2,3,4,5。因此,例如,第1行是一個序列,第2行是一個單獨的獨立序列。計算一個字符串出現在一個序列中的次數

4 4 4 4 4 5 3 0 0 0 
    1 4 2 2 2 2 3 4 0 0 
x= 4 4 1 2 1 3 1 0 0 0 
    2 4 4 2 4 3 3 5 0 0 
    4 4 5 4 2 1 2 4 3 5 

我想計數狀態1..5之間的轉換次數。即。 1to1,1to2,1to3,1to4,1to5。 2to1等 例如。 1to1發生0次。但是4to4發生6次。等等。 我們可以忽略零點,它們是導入excel文件時的一個假象。

例如this問題,但在那裏,序列已連接。如果您需要進一步澄清,請告訴我。

+1

其實,你有7個4to4轉換(4在第1,1 3日,1 4和1 5日)... –

回答

3

這裏的代碼,你想要做什麼:

N = max(max(X));         %# Number of states 
[P, Q] = meshgrid(1:N, 1:N); 
Y = [X, zeros(size(X, 1), 1)]';     %# Pad for concatenation 
count_func = @(p, q)numel(strfind(Y(:)', [p, q])); %# Counts p->q transitions 
P = reshape(arrayfun(count_func, P, Q), N, N) 

簡短說明:的X所有線路,一個長的矢量Y(填充是必要的,這樣有在相鄰行沒有不希望的轉變)。 pq保存用於狀態轉換的所有可能的組合,並且count_func針對特定的pqY中的轉換的次數進行計數。 arrayfun針對pq的所有可能的組合調用count_func並相應地產生矩陣P

對於示例,該代碼產生矩陣P

P = 
    0 2 1 1 0 
    2 3 0 3 0 
    1 1 1 2 1 
    1 3 1 7 1 
    0 0 2 2 0 

其中P(m, n)指示轉變從個狀態到Ñ個狀態數。


編輯:如果你有興趣在尋找2步轉移矩陣(即個狀態→Ĵ個狀態→個狀態)在後續的問題,你只需要稍微改變count_func,就像這樣:

count_func = @(p, q)numel(strfind(Y(:)', [p, q, p])); 

這應該產生:

P = 

    0 1 0 0 0 
    1 2 0 1 0 
    1 0 0 0 0 
    0 0 0 3 0 
    0 0 0 1 0 
+0

我看到什麼這段代碼的確如此,但它抱怨由於某種原因只需要一行。你是否使用上述矩陣作爲輸入?問候, – HCAI

+0

我再次運行此代碼,它的工作原理。你能告訴我哪一行直接觸發錯誤嗎? –

+0

這是'findstr'函數。給我strfind'一樣的。使用findstr時出錯 輸入字符串必須有一行。 (y)()),[p(u),q(u)])) – HCAI

1

另一種解決方案:

%# Define the example data: 
x = [ 
4 4 4 4 4 5 3 0 0 0 
1 4 2 2 2 2 3 4 0 0 
4 4 1 2 1 3 1 0 0 0 
2 4 4 2 4 3 3 5 0 0 
4 4 5 4 2 1 2 4 3 5 
]; 

%# Number of different states. 
N = max(max(x)); 

%# Original states. 
OrigStateVector = repmat((1:N)', N, 1); 

%# Destination states corresponding to OrigStateVector. 
DestStateVector = reshape(repmat((1:N)', 1, N)', N^2, 1); 

%# Pad rows of x with zeros and reshape it to a horizontal vector. 
xVector = reshape([ x, zeros(size(x,1),1) ]', 1, numel(x)+size(x,1)); 

%# Compute the number of state transitions and store the result in ResultMatrix. 
ResultMatrix = reshape(cellfun(@(z) numel(z), arrayfun(@(x,y) strfind(xVector, [x y]), OrigStateVector, DestStateVector, 'UniformOutput', false)), N, N)'; 

ResultMatrix = 
0  2  1  1  0 
2  3  0  3  0 
1  1  1  2  1 
1  3  1  7  1 
0  0  2  2  0 
相關問題