MATLAB: Hidden Markov Models - Computing Beta

Formula

Implementation

function b = beta_dynamic(M,p,B,v)
    
    [N, ~] = size(M);
    T = length(v);
    %create matrix of betas
    b = zeros(N, T);
    %initialize last column to 1
    b(:,end) = 1;
    %calculate betas right to left
    for t = T-1:-1:1
        for j = 1:N
            b(j,t) = sum(b(:,t+1) .* M(j,:)' .* B(:,v(t+1)));
        end
    end    
end