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

4 次查看(过去 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