Pick one element from each row without using loop

  • Follow


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
0
Reply William 1/5/2010 6:29:05 PM

C = A((1:n) + (B.'-1).*n);
0
Reply Matt 1/5/2010 6:47:04 PM


"William " <huyichuan@gmail.com> wrote in message <hi00dh$10i$1@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
0
Reply Jos 1/5/2010 9:55:20 PM

2 Replies
224 Views

(page loaded in 0.015 seconds)


Reply: