44

Suppose I have an array, a = [2 5 4 7]. What is the function returning the maximum value and its index?

For example, in my case that function should return 7 as the maximum value and 4 as the index.

gnovice
  • 125,304
  • 15
  • 256
  • 359
Yuseferi
  • 7,931
  • 11
  • 67
  • 103
  • 9
    Write `max` at the command line and press F1 for help (if on a Windows system, other systems will use another key) and read the documentation. – High Performance Mark Nov 23 '12 at 14:27
  • There are many tutorials out there to get you the basic Matlab functions familiar :) [Mathworks](http://www.mathworks.com/academia/student_center/tutorials/mltutorial_launchpad.html) – bonCodigo Nov 23 '12 at 14:35
  • [Matlab's documentation](http://www.mathworks.com/help/matlab/index.html) (also the available launching `doc` in the command window) contains almost anything you will ever need to know about matlab functions, examples and tutorials. – Cavaz Nov 23 '12 at 14:57

7 Answers7

85

The function is max. To obtain the first maximum value you should do

[val, idx] = max(a);

val is the maximum value and idx is its index.

NKN
  • 6,482
  • 6
  • 36
  • 55
Acorbe
  • 8,367
  • 5
  • 37
  • 66
16

For a matrix you can use this:

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

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

Mohsen
  • 314
  • 1
  • 4
  • 14
10

In case of a 2D array (matrix), you can use:

[val, idx] = max(A, [], 2);

The idx part will contain the column number of containing the max element of each row.

NKN
  • 6,482
  • 6
  • 36
  • 55
Rupal Sonawane
  • 119
  • 1
  • 4
5

You can use max() to get the max value. The max function can also return the index of the maximum value in the vector. To get this, assign the result of the call to max to a two element vector instead of just a single variable.

e.g. z is your array,

>> [x, y] = max(z)

x =

7

y =

4

Here, 7 is the largest number at the 4th position(index).

NKN
  • 6,482
  • 6
  • 36
  • 55
bonCodigo
  • 14,268
  • 1
  • 48
  • 91
5

3D case

Modifying Mohsen's answer for 3D array:

[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)
user3804598
  • 355
  • 5
  • 9
0

This will return the maximum value in a matrix

max(M1(:))

This will return the row and the column of that value

[x,y]=ind2sub(size(M1),max(M1(:)))

For minimum just swap the word max with min and that's all.

Mojtaba Ahmadi
  • 1,044
  • 19
  • 38
oumarkh
  • 11
  • 1
0

For example:

max_a = max(a)
a.index(max_a)
Pobaranchuk
  • 839
  • 9
  • 13