如何获得两个二维矩阵的元素对之间的最大值?

How to obtain the maximum between element-pairs of two 2D matrices?

我必须计算矩阵中每对唯一元素的最大值。所以这是我的代码:


resultsMat = [
6   4   4;
0   2   6;
7   7   1;
5   1   73
];

copyMat = resultsMat;
for i=1:size(resultsMat,1)
        for j=1:size(resultsMat,2)
             for q=1:size(resultsMat,1)
                 for p=1:size(resultsMat,2)
                        if i== q && j ~= p
                        a = max(resultsMat(i,j),copyMat(q,p))
                        end
                 end
             end
        end
end

当我尝试将值存储在矩阵中时出现问题。例如:

[val ind] =  max(resultsMat(i,j),copyMat(q,p))

这会引发错误:

Error using max
MAX with two matrices to compare and two output arguments is not supported.

Error in Untitled2 (line 18)
                        [a, b] = max(resultsMat(i,j),copyMat(q,p))

如何将 a = max(resultsMat(i,j),copyMat(q,p)) 的值存储在矩阵中?

您需要一个更大的(可能 multi-dimensional)矩阵,因为每个 (i,j) 位置相对于任何 (q,p) 位置都有最大值。这意味着对于第一个矩阵中的每个元素,您都会获得一个相同大小的完整矩阵。另存为

matrix_with_results(i,j,q,p) = a

会这样做。然后,给定 i,j,q,p 的任意组合,它 returns 最大值。

一定要预分配

matrix_with_results = zeros(size(resultsMat,1),size(resultsMat,2),size(resultsMat,1),size(resultsMat,2))

为了速度。


两个注意事项:

  • 不要使用 ij 作为 indices/variables 名称,as they denote the imaginary unit。使用这些很容易导致难以调试的错误。

  • 初始化matrix_with_results,即在进入循环之前告诉 MATLAB 它将有多大。否则,MATLAB 每次迭代都必须增加其大小,这非常慢。这叫做preallocation.