Reputation: 85
I got the following problem: In my code I want a matrix-...-matrix-vector in a for loop. In every loop I want to get an additional matrix to multiply with, e.g. i=1: P1*z and i=2: P1*P2*z etc. This is my code so far. Obviously it is just computing: i=1: P1*z, i=2: P2*z etc...
for ii = 1:10
% Projection on last_z
projected_last_z = projection(:,:,ii) * last_z;
end
Upvotes: 0
Views: 56
Reputation: 1048
You must do compute the value always in the same variable if you want to keep the results
n = 10;
projected_last_z = 1;
for ii = 1:n
projected_last_z = projected_last_z * projection(:,:,ii);
end
projected_last_z = projected_last_z * last_z;
The loop is
loop 1 : projected_last_z = P1
loop 2 : projected_last_z = P1 * P2
...
loop 10 : projected_last_z = P1 * P2 * ... * P10
Then you multiply the final result by last_z
Upvotes: 1
Reputation: 18488
It is usually considered bad practice to create new variables in a loop as you want. Better to collect all the results in a cell array or so:
n = 10;
results = cell(1, n); % preallocate some space
for i = 1:n
results{i} = some_calculation(i);
end;
You can then retrieve the result of the k-th iteration using results{k}
.
Upvotes: 1