Filter löschen
Filter löschen

How to Select one element from each row of a matrix A based on a column matrix B.

16 Ansichten (letzte 30 Tage)
Hello Everyone,
I need to select one element from each row of matrix A of size 6400 X 8 based on another column matrix of size 6400 X 1.
For e.g. lets say A( 6400X8) = [ 1 0 1 0 0 0 1 1; 0 1 0 1 1 1 0 0; 1 0 1 0 0 0 1 0; 0 1 0 0 0 0 0 1; 1 0 0 1 0 0 1 1; 1 0 1 0 0 0 1 0; ...... ..... ];
and let B (6400X1) = [ 6; 7; 1; 4; 5; 8; .; .; .; ]; Now I need a matrix C which has elements from each row of matrix A based on matrix B.
A( 6400X8) = [ 1 0 1 0 0(0) 1 1;
0 1 0 1 1 1 (0)0;
(1) 0 1 0 0 0 1 0;
0 1 0 (0)0 0 0 1;
1 0 0 1 (0)0 1 1;
1 0 1 0 0 0 1 (0);
......;
......;
];
Therefore C = [ 0; 0; 1; 0; 0; 0; .; .; .; .; ];
Please help me. Thanks in advance.

Akzeptierte Antwort

Bård Skaflestad
Bård Skaflestad am 30 Jan. 2012
So, if I understand correctly, your vector B contains column indices (i.e., numbers between 1 and size(A,2) inclusive) such that you want to extract the elements C(i)=A(i,B(i)) for all i=1:size(A,1). Is that correct?
If so, this is a perfect case for linear indexing. Much more about this technique can be found in Steve Eddins' blog at http://blogs.mathworks.com/steve/2008/02/08/linear-indexing/. In this case I'd write something along the lines of
I = (1 : size(A, 1)) .';
J = reshape(B, [], 1);
k = sub2ind(size(A), I, J);
C = A(k);

Weitere Antworten (1)

Sean de Wolski
Sean de Wolski am 30 Jan. 2012
You could use sub2ind():
idx = sub2ind(size(A),(1:numel(B)).',B); %not tested in ML
AB = A(idx);
for more info:
doc sub2ind

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by