【问题标题】:Finding index of element matching condition of matrix - Matlab查找矩阵元素匹配条件的索引 - Matlab
【发布时间】:2015-05-13 19:54:49
【问题描述】:

给定一个矩阵 Z(i,j),使其映射到两个数组 X(i) 和 Y(j)。 我试图在一定范围内找到 Z 的元素(以及相应的 X 和 Y)。

我现在正在使用逻辑索引执行以下操作。给定这个例子

 X = 1:5;
 Y = 1:5;
 Z =    [17    24     1     8    15
         23     5     6    14    16
          4     6    13    20    22
         10    12    19    21     3
         11    18    25     2     9]
 Z((X>1 & X<4),Y==3)

这很好用,但现在我希望从这个特定范围内找到返回值的最小值,

我做什么

min(Z((X>1 & X<4),Y==3))

但是现在我如何取回对应的 X 和 Y 值的最小值呢?由于我的逻辑索引返回一个数组,所以到目前为止我尝试过的所有方法都返回答案数组中最小值的索引,而不是原始 Z 矩阵。

我不能用

[row col] = find(Z==min(Z((X>1 & X<4),Y==3)))

因为重复。我的替代方案是什么?

【问题讨论】:

    标签: matlab matrix find matrix-indexing


    【解决方案1】:

    要检索原始索引,您必须在xy(我将它们放入数组cXcY)上保留两个条件的索引的内存,然后使用该函数ind2sub.

    注意:您的代码有点混乱,因为x 代表行 和y 列,但我在我的 回答。

    在实践中,这给出了:

    % --- Definition
    X = 1:5;
    Y = 1:5;
    Z =    [17    24     1     8    15
            23     5     6    14    16
             4     6    13    20    22
            10    12    19    21     3
            11    18    25     2     9];
    
    % --- Get the values of interest
    cX = find(X>1 & X<4);
    cY = find(Y==3);
    v = Z(cX,cY);
    
    % --- Get position of the minimum in the initial array
    [~, I] = min(v(:));
    [Ix, Iy] = ind2sub([numel(cX) numel(cY)], I);
    
    i = cX(Ix);      % i = 2
    j = cY(Iy);      % j = 3
    

    最好的,

    【讨论】:

    • @Divakar:感谢您的称赞,尤其是来自bsxfun 大师!
    • 哈哈,bsxfun 很有趣!我只是希望更多的人开始喜欢它!
    • 如果我在浪费时间输入我的之前阅读了所有答案... :-)
    【解决方案2】:

    一种方法 -

    %// Calculate all indices of the grid created with those two X-Y conditions
    idx = bsxfun(@plus,(find(Y==3)-1)*size(Z,1),find((X>1 & X<4)).') %//'
    
    %// Get the index corresponding to minimum from that grided Z
    [~,min_idx] = min(Z(idx(:)))
    
    %// Get corresponding X-Y indices by using indices calculated earlier
    [indX,indY] = ind2sub([numel(X) numel(Y)],idx(min_idx))
    

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 2013-09-13
      • 1970-01-01
      • 2013-01-03
      • 2012-11-19
      • 2023-04-09
      • 1970-01-01
      • 2015-07-29
      • 2016-04-20
      相关资源
      最近更新 更多