在MATLAB中创建最大值索引矩阵

时间:2010-01-17 15:19:16

标签: matlab matrix max

使用MATLAB,我有一个大小为8行x N列的值数组。我需要创建一个相同大小的矩阵,它计算每列中的最大值,并在包含最大值的单元格中放置1,在其他地方放置0。

一个小例子。让我们假设我们有一个值数组D:

    D =
      0.0088358   0.0040346   0.40276     0.0053221
      0.017503    0.011966    0.015095    0.017383
      0.14337     0.38608     0.16509     0.15763
      0.27546     0.25433     0.2764      0.28442
      0.01629     0.0060465   0.0082339   0.0099775
      0.034521    0.01196     0.016289    0.021012
      0.12632     0.13339     0.11113     0.10288
      0.3777      0.19219     0.005005    0.40137

然后,这种矩阵D的输出矩阵将是:

    0    0    1    0
    0    0    0    0
    0    1    0    0
    0    0    0    0
    0    0    0    0
    0    0    0    0
    0    0    0    0
    1    0    0    1

有没有办法在没有从max函数中捕获索引的向量,然后使用for循环将其放在正确的位置?

3 个答案:

答案 0 :(得分:8)

单行答案:

M = D==repmat(max(D),size(D,1),1)

或更优雅:

M = bsxfun(@eq, D, max(D))

更新

根据评论,如果您想要安全并抓住意外的非唯一最大值,请添加以下声明:

M( cumsum(M)>1 ) = false

这将确保在多个最大值的情况下,只有第一个出现在输出矩阵中具有相应的一个(这相当于max()函数的返回索引的行为)。

答案 1 :(得分:7)

可能有更好的方法,我的第一种方法是:

D          = rand(8,4)

[val, sub] = max(D)    
ind        = sub2ind( size(D), sub, 1:4 )

res        = false( size(D) )
res( ind ) = true

答案 2 :(得分:1)

我已经编写了原始问题的扩展,可以处理任意多维数组并在任何指定维度上搜索最大值。

我用它来解决博弈论中的纳什均衡问题。希望其他人会觉得有帮助。

A = rand([3 3 2]);
i = 1; % specify the dimension of A through which we find the maximum

% the following codes find the maximum number of each column of A
% and create a matrix M of the same size with A
% which puts 1 in the cell that contains maximum value, and 0 elsewhere.

[Amax pos] = max(A, [], i);
% pos is a now 1x3x3 matrix (the ith dimension is "shrinked" by the max function)

sub = cell(1, ndims(A));
[sub{:}] = ind2sub(size(pos), (1:length(pos(:)))');
sub{i} = pos(:);

ind = sub2ind(size(A), sub{:});
M = false(size(A));
M(ind) = true;

示例:

A(:,:,1)=

0.0292    0.4886    0.4588
0.9289    0.5785    0.9631
0.7303    0.2373    0.5468

A(:,:,2)=

0.5211    0.6241    0.3674
0.2316    0.6791    0.9880
0.4889    0.3955    0.0377

M(:,:,1)=

 0     0     0
 1     1     1
 0     0     0

M(:,:,2)=

 1     0     0
 0     1     1
 0     0     0
相关问题