Una matriz de transición de primer orden de 6 estados puede ser constructed very elegantly as siguela construcción de una matriz de transición de la cadena de múltiples orden de Markov en Matlab
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.
Así que aquí es mi problema, ¿cómo se construye una matriz de transición de segundo orden ¿esmeradamente? La solución que se me ocurrió es el siguiente
[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
¿Hay un uno/dos-liner, sin bucle alternativa?
-
Editar: Probé comparando mi solución contra Amro de con "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.
¡Qué gran diferencia! FYI, grp2idx está disponible en línea.
Señor, usted es el rey de Matlab @ Stack Exchange. ¡Incluso los domingos! – teng
@tedteng: lol gracias :) La función [GRP2IDX] (http://www.mathworks.com/help/toolbox/stats/grp2idx.html) es parte de la caja de herramientas Estadísticas, pero podría reemplazarla con [ÚNICO ] (http://www.mathworks.com/help/techdoc/ref/unique.html): '[gn, ~, g] = unique ([xy; bigrams], 'stable');' – Amro
¿Sería? ¿Es fácil extender este método a un ** ** ** bidimensional? – HCAI