使用 min 索引

Using indexies of min

我的问题是我已经对图片中的点与三个静态点进行了一些距离计算。我想知道哪个距离最小,并将像素值写入第二个数组。我使用 min() 来获取索引,但我不知道如何使用这些索引访问图片。我稍微简化了代码:

data = rand(5, 5, 3);          # distances of a 5x5 image to 3 different points
[~, mi] = min(data, [], 3);    # which of the distances is the minimum
result = picture(mi);          # write pixel values to result

我知道这只会给我 picture(1:3, 1, 1) 的值,所以前三个像素,我没有找到合适的函数来转换索引。我怎样才能做到这一点并避免编写循环?

编辑

澄清一下。 mi 可能是

data = rand(3, 3, 2)
data = 
ans(:, :, 1) = 
    0.316498   0.054937   0.606390
    0.537073   0.231184   0.790371
    0.770788   0.334282   0.522369

ans(:,:,2) =
   0.843369   0.051667   0.227570  
   0.452298   0.407662   0.648079
   0.450546   0.398068   0.281694

[~, mi] = min(data, [], 3)
mi =
   1   2   2
   2   1   2
   2   1   2

data(mi)
ans =
   0.31650   0.53707   0.53707
   0.53707   0.31650   0.53707
   0.53707   0.31650   0.53707

如您所见,我仅使用 data(1)data(2) 访问这些索引,这基本上是 data(1, 1, 1)data(2, 1, 1),但我想要以下结果

0.31650    0.051667   0.227570  
0.452298   0.231184   0.648079
0.450546   0.334282   0.281694

min in this context is giving you the slice of your matrix where the minimum occurs, which is the expected result but not necessarily the most useful one. You can use sub2ind with meshgrid to generate linear indices 的 return 访问最低点的位置:

tmp = rand(3, 3, 2);
[mins, mi] = min(tmp, [], 3);

[r, c, ~] = size(tmp);  % Get number of rows & columns
[y, x] = meshgrid(1:r, 1:c);  % Generate x,y pairs
lidx = sub2ind(size(tmp), x(:), y(:), mi(:));  % Generate linear indices

% Test out the linear indices
mins_lidx = reshape(tmp(lidx), r, c);  % Reshape to the slice size

在哪里

>> all(mins(:)==mins_lidx(:))

ans =

  logical

   1

如果需要,您也可以只使用下标 [x(:), y(:), mi(:)],但在这种情况下似乎更笨重。