求矩阵元素匹配条件的索引 - Matlab

Finding index of element matching condition of matrix - Matlab

给定一个矩阵 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的最小值呢?由于我的逻辑索引 returns 一个数组,到目前为止我尝试过的所有方法 returns 答案数组中最小值的索引,而不是原始 Z 矩阵。

我不会用

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

因为重复。我有什么选择?

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

NB: your code is a little bit confusing since x stands for the lines and y for the columns, but I have kept the same convention in my answer.

在实践中,这给出了:

% --- 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

最佳,

一种方法-

%// 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))