Transition Matrix that compares two elements to the next two elements.

Hi all, I am trying to modify this code to create a transition matrix that compares two elements to the next two elements. As of now the code successfully compares two elements to the next one element. I have been trying to modify it, but have not had any luck. Any help would be greatly appreciated. Thanks.
close all
clc
dataset = [1 2 1 1 1 2 2 2 1 1 1 2 2];
precision = 1;
markovChain = (round(dataset/precision)).*precision;
%number of states
Nstates = max(markovChain);
%get Norder-contiguous sequences of the markov chain
ngrams = [];
for i = 0:1
ngrams = [ngrams, circshift(markovChain,[0 -1*(i)])'];
end
ngrams = cellstr(num2str( ngrams));
ngrams = ngrams(1:end-2);
%create all combinations of Norder-contiguous sequences
[x{1:2}] = ndgrid(1:Nstates);
%format x to cell
evalStr = ['xCell = cellstr(num2str(['];
for i = 1:2
evalStr = [evalStr 'x{' num2str(i) '}(:) '];
end
evalStr = [evalStr ']));'];
eval(evalStr);
%map ngrams to numbers
[gn,~,g]=unique([xCell;ngrams]);
s1 = g(Nstates^2+1:end);
%states following the ngrams
s2 = markovChain(3:end);
%get transition matrix
tm = full(sparse(s1,s2,1,Nstates^2,Nstates^2) );
transitionMatrix = bsxfun(@rdivide, tm, sum(tm,2));

9 个评论

Can you post the expected result. There may be a better solution then modifying your code
The expected matrix would be a N^2 x N^2 where N would be the number of states.
I did it by hand and the expected result should be [0 1 0 0; 0.5 0 0 0.5; 1 0 0 0; 0.5 0 0.5 0] where the element in the firs row first col would be the transition from the two elements [1 1] to the next two elements [1 1].
where the element in the firs row firs col would [1 1]. What does that mean? Can you explain what do you mean by comparison
So in the set of data, the subset [1 1] will transition to [1 1] zero times, to [1 2] twice, to [2 1] zero times, and to [2 2] twice. Then those numbers are divided by the total number of times a change occurs from [1 1] which would be 4. I calculated the expected result incorrectly before, it should be [0 0.5 0 0.5; 0.5 0 0 0.5; 1 0 0 0; 0.5 0 0.5 0]
For the first column of the result it's clear, what about the second one?
Well that is the firs row. The second row would be the transitions from [1 2] to [1 1], to [1 2], to [2 1] and to [2 2]. The third row would be the transitions from [2 1] to the above. and The last would be the transitions form [2 2].

请先登录,再进行评论。

 采纳的回答

a=[1 2 1 1 1 2 2 2 1 1 1 2 2];
b=[0 1 0 0; 0.5 0 0 0.5; 1 0 0 0; 0.5 0 0.5 0];
state=[1 1;1 2;2 1;2 2];
q=zeros(4);
for k=1:4
for p=1:4
q(p,k)=numel(strfind(a,[state(k,:) state(p,:)]));
end
q(:,k)=q(:,k)/sum(q(:,k));
end
q
The result
q =
0 0.5000 1.0000 0.5000
0.5000 0 0 0
0 0 0 0.5000
0.5000 0.5000 0 0

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by