0

Possible Duplicate:
MATLAB indexing question
How to extract non-vertical column from matrix in Matlab

I feel like there should be a simple way to do what I want, but I cannot figure this out.

INPUT: an n x t matrix M of reals and an n x 1 vector I of indices

OUTPUT: an n x 1 vector P such that P(i) = M( i, I(i) )

It's obvious how to do this with a for loop, but this is Matlab and n is large. Is there a way to vectorize this problem and avoid the for loop?

Community
  • 1
  • 1
PengOne
  • 48,188
  • 17
  • 130
  • 149

1 Answers1

2

Here's a simple, fast, vectorized solution using linear indexing.

indx = (1:n)' + (I-1)*n; %'
P=M(indx);

Example:

M = randi(10,[3,4]);     %# test matrix

M =

     9    10     3    10
    10     7     6     2
     2     1    10    10

n = size(M,1);
I = [3,1,4]';            %'# index vector
indx = (1:n)' + (I-1)*n; %'
P = M(indx)

P =

 3
10
10
Community
  • 1
  • 1
abcd
  • 41,765
  • 7
  • 81
  • 98