Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of max and min value in an array

Tags:

How can I find the index of the maximum element in an array without looping?

For example, if I have:

a = [1 2 999 3];

I want to define a function indexMax so that indexMax(a) would return 3.

Likewise for defining indexMin.

like image 752
Evgeni Sergeev Avatar asked Jan 28 '13 06:01

Evgeni Sergeev


People also ask

How do you find the maximum and minimum of an array in C?

The function getresult( int arr[],int n) is to find the maximum and minimum element present in the array in minimum no. of comparisons. If there is only one element then we will initialize the variables max and min with arr[0] . For more than one element, we will initialize max with arr[1] and min with arr[0].

How do you find the max and min of an array in Java?

int min = array[0]; This statement is executed at a time when array[0] is zero. You have not read any values at this point, so initialize your min and max values with: int max = Integer.


2 Answers

The built-in max function has this functionality when two output arguments are specified:

a = [1 2 999 3];
[the_max, index_of_max] = max(a)

the_max =

   999


index_of_max =

     3

Likewise for min.

like image 135
Evgeni Sergeev Avatar answered Oct 04 '22 22:10

Evgeni Sergeev


As pointed by Evgeni max and min can return the argmax and argmin as second arguments.
It is worth while noting that you can use these functions along specific dimensions:

 A = rand(4); % 4x4 matrix
 [ row_max row_argmax ] = max( A, [], 2 ); % max for each row - 2nd dimension
 [ col_min col_argmin ] = min( A, [], 1 ); % min for each column - 1st dimension

Note the empty [] second argument - it is crucial max( A, [], 2 ) is not at all equivalent to max( A, 2 ) (I'll leave it to you as a small exercise to see what max( A, 2 ) does).

The argmax/argmin returned from these "along dimension" calls are row/col indices.

like image 20
Shai Avatar answered Oct 04 '22 23:10

Shai