MATLAB 在逻辑矩阵中存储索引最大值

MATLAB store indices maximum in logical matrix

假设我有一个 4 维矩阵,我想从中检索第 2 维和第 3 维的最大值。

A = rand(4, 4, 4, 4);
[max_2, in_2] = max(A, [], 2);
[max_3, in_3] = max(max_2, [], 3);

如何使用 ind_2ind_3 获得逻辑 4 维矩阵,其中 1 条目表示该条目在第 2 维和第 3 维中最大?

我会使用这种方法:

A = rand(4, 4, 4, 4); % example data
B = permute(A, [1 4 2 3]); % permute dims 2 and 3 to the end
B = reshape(B, size(A,1), size(A,4), []); % collapse last two dims
C = bsxfun(@eq, B, max(B, [], 3)); % maximize over collapsed last dim
C = reshape(C, size(A,1), size(A,4), size(A,2), size(A,3)); % expand dims back
C = permute(C, [1 3 4 2]); % permute dims back. This is the final result

这是一种使用线性索引并使用来自 max 函数的 argmax 索引的方法,因此在最大值 -

并列的情况下它只会考虑第一个 argmax
% Get size parameters
[m,n,p,q] = size(A);

% Reshape to merge second and third dims
[~, in_23] = max(reshape(A,m,[],q), [], 2);

% Get linear indices equivalent that could be mapped onto output array
idx1 = reshape(in_23,m,q);
idx2 = bsxfun(@plus,(1:m)', m*n*p*(0:q-1)) + (idx1-1)*m;

% Initialize output array an assign 1s at linear indices from idx2
out = false(m,n,p,q);
out(idx2) = 1;

示例说明

1) 输入数组:

>> A
A(:,:,1,1) =
     9     8
     9     1
A(:,:,2,1) =
     2     9
     8     1
A(:,:,1,2) =
     1     7
     8     1
A(:,:,2,2) =
     8     5
     9     7

2) 重塑数组以获得更好的可视化效果:

>> reshape(A,m,[],q)
ans(:,:,1) =
     9     8     2     9
     9     1     8     1
ans(:,:,2) =
     1     7     8     5
     8     1     9     7

3) 问题是从每一行中取最大值。为此,我们将 idx2 作为线性索引:

>> idx2
idx2 =
     1    13
     2    14

回顾reshape版本,我们选择了(括号内的)-

>> reshape(A,m,[],q)
ans(:,:,1) =
    [9]     8     2     9
    [9]     1     8     1
ans(:,:,2) =
     1     7     [8]     5
     8     1     [9]     7

因此,仔细观察,我们发现第一行有两个 9s,但我们只选择了第一个。

4) 最后,我们将它们分配到初始化为逻辑零的输出数组中:

>> out
out(:,:,1,1) =
     1     0
     1     0
out(:,:,2,1) =
     0     0
     0     0
out(:,:,1,2) =
     0     0
     0     0
out(:,:,2,2) =
     1     0
     1     0