【问题标题】:How to "chop up" matrix in Matlab using combination of logical indexing and slicing?如何结合使用逻辑索引和切片在 Matlab 中“切碎”矩阵?
【发布时间】:2013-07-24 17:41:38
【问题描述】:

我有一个类似这样的矩阵 M:

M = [   1, 2, 3, 0, 0;
        1, 2, 0, 0, 0;
        2, 3, 4, 5, 0;
        4, 5, 6, 0, 0;
        1, 2, 3, 4, 5;
    ]

我正在尝试获取 A 中每一行的最右侧非零值的列向量,但仅适用于第一列 == 1 的行。

我能够计算行的过滤器:

r = M( :, 1 ) == 1;
> r = [ 1; 1; 0; 0; 1 ]

我有一组“M 中每一行最右边的非零值”的索引:

> c = [ 3, 2, 4, 3, 5 ]

如何将这些组合到 A 的切片中以获得我正在寻找的东西?我正在寻找类似的东西:

A( r, c )
> ans = [ 3; 2; 5 ]

但出于某种原因,这样做会得到一个 3x3 矩阵。

【问题讨论】:

  • 您找到解决问题的答案之一了吗?如果是,请检查它旁边的标记。
  • A=M?你得到的是 3x3 还是 3x5 矩阵(见我的回答)。

标签: matlab


【解决方案1】:

我能想到的最短方法如下:

% Get the values of the last non-zero entry per row
v = M(sub2ind(size(M), 1:size(M,1), c))

% Filter out the rows that does not begin with 1.
v(r == 1)

【讨论】:

    【解决方案2】:

    这似乎可行(我假设已经执行了定义r,c 的其他操作):

    M(sub2ind(size(A),find(r==1).',c(r==1))).'
    

    问题和解决方案的简短解释:

    M( r, c )
    

    由于逻辑和下标索引的混合,给出了一个 3 x 5 矩阵(不是所需的 3 x 1)。 r 中的逻辑索引用r==1 挑选出A 中的行。同时行数组c根据数字索引从每一行中挑选出元素:

    ans =
    
         3     2     0     3     0
         0     2     0     0     0
         3     2     4     3     5
    

    您真正想要的是索引到每行中以1 开头的最右边的非零元素。该解决方案使用线性索引(数字)从矩阵中获取正确的元素。

    【讨论】:

    • 你的意思是M(sub2ind(size(M),find(r==1).',c(r==1)))
    • @Luis Mendo:谢谢,是的,我在素描时单独执行了转置操作。
    • @LuisMendo 听起来不是很挑剔,但如果 M 很复杂怎么办? ...我知道,我知道 :-D
    【解决方案3】:

    我认为这应该可以解决问题。我想知道是否有更优雅的方式来做到这一点。

    % get only rows u want, i.e. with first row == 1
    M2 = M(r,:);
    
    % get indices of
    % "the rightmost non-zero value of each row in M" 
    % for the rows u want 
    indicesOfinterest = c(r==1);
    
    
    noOfIndeciesOfinterest = numel(indicesOfinterest);
    
    % desired output column vector
    output = zeros(noOfIndeciesOfinterest, 1);
    
    % iterate through the indeces and select element in M2
    % from each row and column indicated by the indice.
    for idx = 1:noOfIndeciesOfinterest
        output(idx) = M2(idx, indicesOfinterest(idx));
    end
    
    output % it is [3; 2 ; 5]
    

    【讨论】:

      【解决方案4】:

      你可以使用

      arrayfun(@(x) M(x,c(x)), find(r))
      

      但除非你需要rc作其他用途,否则你可以使用

      arrayfun(@(x) M(x,find(M(x,:),1,'last')), find(M(:,1)==1))
      

      【讨论】:

        【解决方案5】:

        这是一种使用线性索引的方法:

        N = M';
        lin_index = (0:size(N,1):prod(size(N))-1) + c;
        v = N(lin_index);
        v(r)
        

        【讨论】:

          猜你喜欢
          • 2023-03-04
          • 1970-01-01
          • 2022-07-10
          • 2012-07-10
          • 2013-07-20
          • 1970-01-01
          • 2022-07-21
          • 1970-01-01
          • 2022-10-15
          相关资源
          最近更新 更多