From: William on
Hi all,

I have an n-by-m matrix A, an n-by-1 vector B, and following code to generate vector C:

for i=1:n
C(i) = A(i,B(i));
end

Is there any way to avoid using loop in this case?

Thanks!

William
From: Matt Fig on
C = A((1:n) + (B.'-1).*n);
From: Jos (10584) on
"William " <huyichuan(a)gmail.com> wrote in message <hi00dh$10i$1(a)fred.mathworks.com>...
> Hi all,
>
> I have an n-by-m matrix A, an n-by-1 vector B, and following code to generate vector C:
>
> for i=1:n
> C(i) = A(i,B(i));
> end
>
> Is there any way to avoid using loop in this case?
>
> Thanks!
>
> William

Assuming that all elements of B are within [1,m], you can use SUB2IND as follows:

A = magic(6)
B = [3 2 5 1 2 1] % pick element (1,3) (2,2) (3,5) etc.
C = A(sub2ind(size(A), 1:size(A,1) , B))

hth
Jos