Kotsos
Kotsos

Reputation: 329

How to find the maximum of multiple arrays in MATLAB?

Let's say we have an array x. We can find the maximum value of this array as follows:

maximum = max(x);

If I have two arrays, let's say x and y, I can find the array that contains the maximum value by using the command

maximum_array = max(x, y);

Let's say that this array is y. Then, I can find the maximum value by using the max command with argument y, as before with x:

maximum_value = max(y);

This two-step procedure could be performed with the following compact, one-liner command:

maximum_value = max(max(x, y));

But what happens when we have more than 2 arrays? As far as I know, the max function does not allow to compare more than two arrays. Therefore, I have to use max for pairs of arrays, and then find the max among the intermediate results (which involves also the use of additional variables). Of course, if I have, let's say, 50 arrays, this would be - and it really is - a tedius process.

Is there a more efficient approach?

Upvotes: 3

Views: 7526

Answers (2)

Divakar
Divakar

Reputation: 221504

Approach #1

Concatenate column vector versions of them along dim-2 with cat and then use maximium values with max along dim-2 to get the max.

Thus, assuming x, y and z to be the input arrays, do something like this -

%// Reshape all arrays to column vectors with (:) and then use cat
M = cat(2,x(:),y(:),z(:))

%// Use max along dim-2 with `max(..,[],2)` to get column vector 
%// version and then reshape back to the shape of input arrays
max_array = reshape(max(M,[],2),size(x))

Approach #2

You can use ndims to find the number of dimensions in the input arrays and then concatenate along the dimension that is plus 1 of that dimension and finally find max along it to get the maximum values array. This would avoid all of that reshaping back and forth and thus could be more efficient and a more compact code as well -

ndimsp1 = ndims(x)+1                         %// no. of dimensions plus 1
maxarr = max(cat(ndimsp1,x,y,z),[],ndimsp1)  %// concatenate and find max

Upvotes: 3

TroyHaskin
TroyHaskin

Reputation: 8401

I think the easiest approach for a small set of arrays is to column-ify and concatenate:

maxValue = max([x(:);y(:)]);

For a large number of arrays in some data structure (e.g. a cell array or a struct), I simple loop would be best:

maxValue = max(cellOfMats{1}(:));
for k = 2:length(cellOfMats)
    maxValue = max([maxValue;cellOfMats{k}(:)]);
end

For the pathological case of a large number of separate arrays with differing names, I say "don't do that" and put them in a data structure or use eval with a loop.

Upvotes: 1

Related Questions