代码之家  ›  专栏  ›  技术社区  ›  Gacek

MATLAB中最大值指标矩阵的生成

  •  6
  • Gacek  · 技术社区  · 16 年前

    使用 MATLAB

        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 回复  |  直到 16 年前
        1
  •  7
  •   Mikhail Poda    16 年前

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

    D          = rand(8,4)
    
    [val, sub] = max(D)    
    ind        = sub2ind( size(D), sub, 1:4 )
    
    res        = false( size(D) )
    res( ind ) = true
    
        2
  •  8
  •   Shai    13 年前

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

    或者更优雅地说:

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

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

    M( cumsum(M)>1 ) = false
    

    max() 函数返回的索引)。

        3
  •  1
  •   desktable    16 年前

    我已经为原始问题编写了一个扩展,它可以处理任意多维数组并沿任意指定维度搜索最大值。

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

    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
    

     1     0     0
     0     1     1
     0     0     0