在Matlab中构建多阶马尔可夫链转移矩阵

8

一个由6个状态组成的一阶转移矩阵可以通过以下方式优雅地构建

 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=round(5*rand([1,1000])+1);”比较我的解决方案和Amro的。

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

有很大的不同! FYI,grp2idx 可在网上使用。

1个回答

9
请尝试以下方法:
%# 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


先生,您是 Stack Exchange 上的 Matlab 之王,甚至在周日也是如此! - pangyuteng
2
@tedteng:哈哈谢谢:) GRP2IDX 函数是统计工具箱的一部分,但你可以用UNIQUE来替换它:[gn,~,g] = unique([xy;bigrams], 'stable'); - Amro
将这个方法扩展到二维 x 上会容易吗? - HCAI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接