One line updating of rows of a matrix

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?

You forgot to return L from the function.

1 Like

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
1 Like

Mostly a supervisor who likes my code to read in a certain way. I agree there shouldn’t be anything wrong with the above.

Yep that’s a typo. Thanks

Also, keep in mind that Julia arrays are column major, so it is faster and more natural to work with columns than rows.

2 Likes

The loop @sudete 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

3 Likes