I have two loops and one is significantly faster, although they use similar constructs. I can’t figure out how to speed up the second one:
## Forward recursion alpha[1,: ] = p .* B[1,: ] c = 1.0 / sum(alpha[1,: ]) alpha[1,: ] *= c @inbounds for t in 2:T alpha[t,: ] = (alpha[t-1,: ]' * A) * diagm(B[t,: ]) c[t] = 1.0 / sum(alpha[t,: ]) alpha[t,: ] *= c[t] end log_likelihood = -sum(log.(c)) ## Backward recursion beta[T,: ] = ones(N) @inbounds for t in (T-1):-1:1 beta[t,: ] = (A * B[t+1,: ]) .* beta[t+1,: ] .* c[t] end
The first loop takes ~1.2s and the second one takes ~32s when run in global scope REPL. Why is the second one so much slower?