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

조회 수: 7 (최근 30일)
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.

채택된 답변

Bård Skaflestad
Bård Skaflestad 2012년 1월 30일
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);

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by