From: William on 5 Jan 2010 13:29 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 5 Jan 2010 13:47 C = A((1:n) + (B.'-1).*n);
From: Jos (10584) on 5 Jan 2010 16:55 "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
|
Pages: 1 Prev: MEX file for MSC VisualNastran in Matlab 2009 Next: GNUmex and C++ no Output |