RandomBear
RandomBear

Reputation: 128

How to select one element from each column of a matrix to from a new vector?

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

Answers (1)

Luis Mendo
Luis Mendo

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

Related Questions