20

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.

1
  • 1
    There is a problem with this question. @EvgeniSergeev does want to find the index of the max or min value in an array. He is using the name "argmax" for it (and the made up function "argmax(a)"). But argmax is something different (en.wikipedia.org/wiki/Arg_max). Therefor this question is really confusing if you are really looking for an argmax function in MATLAB. Commented Jan 18, 2017 at 20:11

3 Answers 3

24

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.

Sign up to request clarification or add additional context in comments.

Comments

22

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.

4 Comments

Solution to the exercise: max(X, Y) is an element-wise max (just like .* is an element-wise multiply) ... with the usual scalar behaviour, viz. sizes of X and Y must be the same or one of them can be a scalar.
Mmmm ... it's good getting all those points. I just haven't decided how am I going to spend it yet.
@EvgeniSergeev - hide them under your bed!
That doesn't leave much I could say in reply.
7

Just as an alternative solution, you might try this:

a = rand(1,1000);
min_idx = find(a == min(a));

Obviously, the same procedure is applicable in the case of max.

I hope this helps.

1 Comment

This is useful in cases where there may be several equal-maximum elements and one wishes to get all of their indices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.