I have a simple recursive procedure to populate a matrix which can be made easier by populating row by row. i.e. calculating the row and copying it to the matrix. I can’t find a way of making it work and returning the matrix of stacked rows. I can do the calculation elementwise but that’s rather unnatural given the theory.
P = [0.8 0.1 0.1; 0.1 0.7 0.2; 0.05 0.05 0.9]
init_vec = [0.1 0.8 0.1]
function Find_L(init_vec, P)
L = zeros(3,3)
L[1,:] = init_vec
[L[t,:] = transpose(P)*L[t-1,:] for t in 2:size(P,2)]
return L
end
Is there a nice way of doing something like this that returns a matrix?
As @DNF says, though I think that’s an abuse of array comprehension. It creates a useless array that is immediately thrown away, and it obfuscates the meaning of the code. What’s wrong with a plain old for loop?
function Find_L(init_vec, P)
L = zeros(3,3)
L[1,:] = init_vec
for i = 2:size(P,2)
L[i,:] = transpose(P)*L[i-1,:]
end
return L
end
The loop @sijo wrote is much clearer and easier to read. Change the orientation to avoid transpose, use a loop, and stand up to your supervisor They will respect you more if you do