0

I have to calculate maximum of every unique pair of elements in matrix. So here is my code:


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

The problem comes when I try to store values in a matrix. For example:

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

This throws an error:

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))

How to store values from a = max(resultsMat(i,j),copyMat(q,p)) in a matrix?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
ITm
  • 3
  • 2
  • 1
    What research have you done already? From what it seems `a` is a scalar, so storing that in a matrix should be easy and can be found on the internet – Nathan Aug 20 '20 at 12:16
  • @Nathan, Already tried to find on internet but no lucky. Tried to find also on mtllab official documentation.. – ITm Aug 20 '20 at 12:19
  • Then it is not clear to me what you actually want. You want the value of `a` stored in a matrix lets call it `M`? – Nathan Aug 20 '20 at 12:26
  • Yes, all calculated values of "a". – ITm Aug 20 '20 at 12:35
  • So what's the desired result exactly, in your example? – Luis Mendo Aug 20 '20 at 18:25

1 Answers1

1

You need a larger (probably multi-dimensional) matrix, as every (i,j) location has a maximum vs any (q,p) location. This means that for every element in your first matrix, you obtain a full matrix of the same size. Saving as

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

would do this. Then, given any combination of i,j,q,p, it returns the maximum.

Be sure to preallocate

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

for speed.


Two notes:

  • Don't use i or j as indices/variables names, as they denote the imaginary unit. Using those can easily lead to hard to debug errors.

  • Initialise matrix_with_results, i.e. tell MATLAB how large it will be before going into the loop. Otherwise, MATLAB will have to increase its size every iteration,which is very slow. This is called preallocation.

Adriaan
  • 17,741
  • 7
  • 42
  • 75