# max

Largest element

### [M, I] = max(A)

• When A is a scalar, M is equal to A.
• When A is a vector, M is the largest element of A.
• When A is a matrix or a multidimensional array, an element of M is equal to the largest element of the corresponding vector of A along its first non-singleton dimension. I is the position of that largest element in the direction of the non-singleton dimension.

### [M, I] = max(A, [ ], k)

• This is the same as the previous cases, except that each element of M corresponds to a vector of A along its k-th dimension.
• [] is the empty matrix.

### max(A, B)

• A and B should have same sizes.
• It performs elementwise comparison of A and B, and returns the larger element.
• If one of the arguments is scalar, this function compares the scalar with each element of the other argument.

Note

When comparing two numbers by max, if one of them is NaN, the other non-NaN number is returned. If both are NaN, it returns NaN.

Example 1: Find maximum values and their indices along the 3rd dimension.

a=randi(10,3,3,3)

% Finding maximum values along the 3rd dimension, stored in M.
[M,I]=max(a,[],3)

a(:, :, 1) =

3.000   2.000   6.000
4.000   8.000   8.000
7.000   7.000   8.000

a(:, :, 2) =

5.000   10.00   1.000
2.000   7.000   8.000
8.000   4.000   3.000

a(:, :, 3) =

6.000   5.000   10.00
9.000   6.000   5.000
6.000   10.00   3.000

M =
6.000   10.00   10.00
9.000   8.000   8.000
8.000   10.00   8.000

I =
3.000   2.000   3.000
3.000   1.000   1.000
2.000   3.000   1.000


Example 2 Comparing two matrices.

a=randi(10,3,3)
b=randi(10,3,3)
max(a,b)

a =
3.000   3.000   8.000
1.000   6.000   9.000
8.000   8.000   10.00

b =
8.000   9.000   3.000
4.000   4.000   4.000
10.00   6.000   7.000

ans =
8.000   9.000   8.000
4.000   6.000   9.000
10.00   8.000   10.00