问题
For those super experts out there, I was wondering if you see a quick way to convert the following "for" loop into a one-line vector calculation that is more efficient.
%Define:
%A size (n,1)
%B size (n,m)
%C size (n,1)
B = [2 200; 3 300; 4 400];
C = [1;2;1];
for j=1:n
A(j) = B( j, C(j) );
end
So to be clear, is there any alternative way to express A, as a function of B and C, without having to write a loop?
回答1:
Yes, there is:
A = B(sub2ind([n,m], (1:n).', C));
回答2:
It depends on functions A, B, and C, but this might work:
j = 1:n;
A = B(j, C(j));
来源:https://stackoverflow.com/questions/19122715/convert-a-for-loop-into-a-vector-vectorization