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

在Matlab中构造多阶马尔可夫链转移矩阵,matlab,matrix,transition,probability,markov-chains,Matlab,Matrix,Transition,Probability,Markov Chains,6个状态的一阶转移矩阵如下所示 这就是我的问题,如何优雅地构造二阶转移矩阵? 我想出的解决办法如下 [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

6个状态的一阶转移矩阵如下所示

这就是我的问题,如何优雅地构造二阶转移矩阵? 我想出的解决办法如下

 [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
是否有一个/两个班轮,无回路替代方案

--

编辑: 我试着将我的解决方案与Amro的“x=round(5*rand([11000])+1)”进行比较

真不一样! 仅供参考,可在线获取。

请尝试以下操作:

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

先生,您是Matlab@Stack Exchange之王。甚至在星期天@tedteng:lol谢谢:)该函数是统计工具箱的一部分,但您可以将该调用替换为:
[gn,~,g]=unique([xy;bigrams],'stable')将此方法扩展到二维x是否容易?
 % ted teng's solution
 Elapsed time is 2.225573 seconds.
 % Amro's solution
 Elapsed time is 0.042369 seconds. 
%# 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)