Furkan Gözükara
Furkan Gözükara

Reputation: 23870

How to get the largest element index in matlab array

Here is a simple double array:

array=[3 1 1]

Largest element index is 1

or:

array=[3 9 1]

Largest element index is 2

How can I get the largest element index?

Upvotes: 14

Views: 15276

Answers (4)

Goyal Vicky
Goyal Vicky

Reputation: 1299

In Octave If
A =
   1   3   2
   6   5   4
   7   9   8

1) For Each Column Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],1)
max_values =
   7   9   8
indices =
   3   3   3


2) For Each Row Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],2)
max_values =
   3
   6
   9
indices =
   2
   1
   2

Similarly For minimum value

>> [min_values,indices] =min(A,[],1)
min_values =
   1   3   2

indices =
   1   1   1

>> [min_values,indices] =min(A,[],2)
min_values =
   1
   4
   7

indices =
   1
   3
   1

Upvotes: 1

Fabio Campinho
Fabio Campinho

Reputation: 1022

If you need to get the max value of each row you can use:

array = [1, 2, 3; 6, 2, 1; 4, 1, 5];
[max_value max_index] = max(array, [], 2)

%3, 3
%6, 1
%5, 3

Upvotes: 1

Isaac
Isaac

Reputation: 3616

My standard solution is to do

index = find(array == max(array), 1);

which returns the index of the first element that is equal to the maximum value. You can fiddle with the options of find if you want the last element instead, etc.

Upvotes: 3

Tim
Tim

Reputation: 14174

Use the second output argument of the max function:

[ max_value, max_index ] = max( [ 3 9 1 ] )

Upvotes: 33

Related Questions