【问题标题】:Extract values from 2d array with indices from another array (without loops)从具有另一个数组的索引的二维数组中提取值(无循环)
【发布时间】:2017-05-22 07:47:51
【问题描述】:

我有一个数组[2; 3] 和一个矩阵[ 1 3 4 5; 2 4 9 2]。 现在我想从第一行中提取第二个元素,从第二行中提取第三个元素,从而获得[3 ; 9]。我设法通过循环来完成它,但由于我使用的是更大的数组,所以我想避免这些。

【问题讨论】:

    标签: matlab find indices


    【解决方案1】:

    您可以使用 sub2ind 将每个列下标(连同它们的行下标)转换为 linear index,然后使用 that 来索引到您的矩阵。

    A = [1 3 4 5; 2 4 9 2];
    cols = [2; 3];
    
    % Compute the linear index using sub2ind
    inds = sub2ind(size(A), (1:numel(cols)).', cols);
    
    B = A(inds)
    %   3   
    %   9
    

    或者,您可以自己计算线性索引,这将比 sub2ind 更高效

    B = A((cols - 1) * size(A, 1) + (1:numel(cols)).');
    %   3
    %   9   
    

    【讨论】:

      【解决方案2】:

      利用diag函数,可以得到优雅的单行解法:

      A = [1 3 4 5; 2 4 9 2];
      cols = [2; 3];
      
      B = diag(A(:,cols))
      %   3
      %   9
      

      diag(A(:,cols)) 的作用如下:

      1. A(:,cols) 选择Acols 列,A(:,cols)k 列对应Acols(k) 列,给出[3 4; 4 9]
      2. diag 返回此矩阵的对角元素,因此在位置 k 处返回 A(:,cols) 的第 k 对角元素,即 A(k,cols(k))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-04
        • 1970-01-01
        • 2012-04-10
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2016-09-19
        • 2016-08-26
        相关资源
        最近更新 更多