在Matlab中构造多阶马尔可夫链转移矩阵 [英] Constructing a multi-order Markov chain transition matrix in Matlab

查看:256
本文介绍了在Matlab中构造多阶马尔可夫链转移矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将6个状态的一阶转换矩阵非常优雅地构造为跟随

A first-order transition matrix of 6 states can be constructed very elegantly as follows

 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.

这是我的问题,如何优雅地构造一个二阶转换矩阵? 我想出的解决方案如下

So here is my problem, how do you construct a second-order transition matrix elegantly? The solution I came up with is as follows

 [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

是否存在一/两线无回路替代方案?

Is there a one/two-liner, no-loop alternative?

-

我尝试将我的解决方案与Amro的解决方案进行比较,方法是"x = round(5 * rand([1,1000])+ 1);"

I tried comparing my solution against Amro's with "x=round(5*rand([1,1000])+1);"

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

有什么不同! 仅供参考, grp2idx 是可以在线获取.

What a difference! FYI, grp2idx is available online.

推荐答案

尝试以下操作:

%# 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中构造多阶马尔可夫链转移矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆