Using Nx1 vector as index to extract values from an NxM matrix and create an Nx1 vector
24 views (last 30 days)
Show older comments
Hi. I will try to explain my title:
I have an NxM matrix, e. g.
M = [1 2 3; 4 5 6; 7 8 9];
and an Nx1 index vector, e. g.
I = [2; 3; 1];
I would like to create a vector V using I as an index for M to extract values from M so that
V(i) = M(i,I(i))
without using a loop, if possible.
So the resulting vector V in this example would result as:
V = [2; 6; 7];
Thanks for any help or hints!
0 Comments
Accepted Answer
Star Strider
on 8 Apr 2015
Use the sub2ind function to create a linear index:
M = [1 2 3; 4 5 6; 7 8 9];
I = [2; 3; 1];
J = sub2ind(size(M), [1:3]', I);
V = M(J)
produces:
V =
2
6
7
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!