jeudi 25 avril 2019

Hidden Markov Model not working properly, unknown logic/syntax error in MATLAB code

I have created this code from scratch. I want to make a plot and/or histogram of my "Observed" and "State" (these are 2 matrices). Some problem occurs at the 200th iteration, where my State matrix just becomes all 0's, there is no data being input into the State matrix. Can anyone troubleshoot the code? My possible states are {1,2,3}. The error might be occurring at the line:

State(k) = randsample(N, 1, true, A(State(k-1),:));

BUT, maybe there are incorrect subtleties throughout code I am unaware of. MATLAB and HMM are very new to me. Thank you!

%Initialize A,pi,T

N = 3; # of states
%A is transition prob matrix
A = [.99,.005,.005;.005,.990,.005;.005,.005,.990];
%pi is initial state vector
pi = [1/3,1/3,1/3];
%T is # of observations per simulation
T = 1000;
%n is # of simulations
n = 5;
%Allocate space for the state matrix
State = zeros(n,T);
Observe = zeros(n,T);
%Create dummy emission matrix, must be row stochastic 
B = ones(n,T)./T;
%loop over # of simulations
for i=1:1:n
    x = rand(1);
    if x <= (1/3)
        State(i,1) = 1;
    elseif x > (1/3) && x <= (2/3)
        State(i,1) = 2;
    else
        State(i,1) = 3;
    end
    if State(i,1) == 1
        b = -1;
    elseif State(i,1) == 2
        b = 0;
    else
        b = 1;
    end
    Observe(i,1)= normrnd(b,1);
    for k=2:1:T
        %Possible state 1,2,3
        State(k) = randsample(N, 1, true, A(State(k-1),:));
        if State == 1
            c = -1;
        elseif State == 2
            c = 0;
        else
            c = 1;
        end
        Observe(i,k)= normrnd(c,1);
    end
end




Aucun commentaire:

Enregistrer un commentaire