在没有for循环的情况下在Matlab中选择给定指定列的矩阵条目

时间:2011-10-12 19:07:52

标签: matlab vector

  

可能重复:
  MATLAB indexing question
  How to extract non-vertical column from matrix in Matlab

我觉得应该有一种简单的方法来做我想做的事,但我无法弄清楚这一点。

INPUT n x t矩阵M的实数和n x 1向量I的索引

输出n x 1向量PP(i) = M( i, I(i) )

显然如何使用for循环执行此操作,但这是Matlab,n很大。有没有办法对这个问题进行矢量化并避免for循环?

1 个答案:

答案 0 :(得分:2)

这是一个使用线性索引的简单,快速,矢量化解决方案。

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

实施例

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
相关问题