How to Select one element from each row of a matrix A based on a column matrix B.
Show older comments
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.
Accepted Answer
More Answers (1)
Sean de Wolski
on 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
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!