フィルターのクリア

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

16 ビュー (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by