嵌套在MATLAB中的循环错误或索引错误

问题描述 投票:0回答:1

我从头开始创建了这段代码。我想制作我的“观察”和“状态”(这些是2个矩阵)的图和/或直方图。在第200次迭代中出现了一些问题,其中我的状态矩阵变为全0,没有数据输入到状态矩阵中。任何人都可以解决代码问题吗?我可能的状态是{1,2,3}。

更新:当我调整我的n值时,它会调整它将填充多长的T值。所以,n = 5,只运行T的1/5,n = 1,运行T的整个长度。我需要一个nxT矩阵(5X1000)。问题在于我设置for循环的方式。我仍然无法解决错误。

%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
matlab loops random hidden-markov-models
1个回答
0
投票
State(k) = randsample(N, 1, true, A(State(k-1),:));

该行在状态(k-1)内的位置1中缺少索引(i)。它应该是:

State(i,k) = randsample(N, 1, true, A(State(i,k-1),:));
© www.soinside.com 2019 - 2024. All rights reserved.