开发者

Pick out entries of a matrix given specified columns in Matlab without a for loop [duplicate]

This question already has answers here: Closed 11 years ago.

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜