Reputation: 128
I have a M
×N
matrix A
, and a M
×1
index vector ind
. I want to get a N
×1
vector c
where c(i) = A(ind(i),i)
for i
=1
,2
,...,N
.
For example, let
A = hilb(5);
ind = [2,3,1,4,2]';
How can I get vector c
?
Upvotes: 0
Views: 44
Reputation: 112759
That's what sub2ind
does:
c = A(sub2ind(size(A), ind(:).', 1:numel(ind)));
You can also do it manually to increase speed a little:
c = A((0:numel(ind)-1) * size(A,1) + ind(:).');
To understand how this works, read on linear indexing.
Upvotes: 2