MATLAB store indices maximum in logical matrix

时间:2017-10-03 09:01:12

标签: arrays matlab multidimensional-array matrix-indexing

Lets say I have a 4 dimensional matrix, from which I would like to retrieve the maximum values over the 2nd and 3rd dimension.

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

How could I use ind_2 and ind_3 to obtain a logical 4 dimensional matrix, where a 1 entry means this entry is maximum in the 2nd and 3rd dimension?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这是一种使用线性索引并使用来自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(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