Reputation: 3
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?
Upvotes: 0
Views: 106
Reputation: 18177
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.
Upvotes: 1