GTX
GTX

Reputation: 13

Convert a for loop into a vector (vectorization)

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?

Upvotes: 1

Views: 1561

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Yes, there is:

A = B(sub2ind([n,m], (1:n).', C));

Upvotes: 2

shoelzer
shoelzer

Reputation: 10708

It depends on functions A, B, and C, but this might work:

j = 1:n;
A = B(j, C(j));

Upvotes: 0

Related Questions