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

标签 matlab matrix transition probability markov-chains

6 个状态的一阶转移矩阵可以是constructed very elegantly as跟随

 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. 

有什么不同! 仅供引用,grp2idx可在线获取。

最佳答案

尝试以下操作:

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

关于matlab - 在 Matlab 中构建多阶马尔可夫链转移矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11072206/

相关文章:

Java vector : how to quickly "symmetrify" a large chunk of a huge sparse matrix

matlab - MATLAB中的低通滤波器返回NaN值

matlab - RBF 神经网络

matlab - 将图像分成不重叠和重叠的 block

r - 如何生成一个矩阵来存储集合的所有非空子集

javascript - 如何使用 justify-content 对容器中的插入和删除进行动画处理?

matlab: 'copy figure' 的命令行等效项是什么?

c++ - 从结构转换为浮点*

jquery - 向后运行的 CSS 过渡

css - 过渡期间闪烁的固定背景