2

How do I find the index of the 2 maximum values of a 1D array in MATLAB? Mine is an array with a list of different scores, and I want to print the 2 highest scores.

5
  • 2
    Use sort and pick the last two values Commented Sep 19, 2015 at 15:21
  • hey, thank you, but as i did sorting, than the indexes are changing, could you be more specific? Commented Sep 19, 2015 at 15:22
  • What's the desired output? The values, the indices, or both? Commented Sep 19, 2015 at 15:29
  • Possible duplicate of Index of max and min value in an array Commented Jan 18, 2017 at 20:28
  • @Spen I disagree with that proposed duplicate, as the solutions there only give one index, which is indeed quite easy with the second output of min and max. Getting the second maximum value requires either an extension of the duplicate's answers (see beaker's answer for that) or a different approach altogether (see Luis' sort method). Commented Jun 11, 2018 at 12:00

3 Answers 3

3

You can use sort, as @LuisMendo suggested:

[B,I] = sort(array,'descend');

This gives you the sorted version of your array in the variable B and the indexes of the original position in I sorted from highest to lowest. Thus, B(1:2) gives you the highest two values and I(1:2) gives you their indices in your array.

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

Comments

2

I'll go for an O(k*n) solution, where k is the number of maximum values you're looking for, rather than O(n log n):

x = [3 2 5 4 7 3 2 6 4];
y = x; %// make a copy of x because we're going to modify it
[~, m(1)] = max(y);
y(m(1)) = -Inf;
[~, m(2)] = max(y);

m =

   5   8

This is only practical if k is less than log n. In fact, if k>=3 I would put it in a loops, which may offend the sensibilities of some. ;)

Comments

1

To get the indices of the two largest elements: use the second output of sort to get the sorted indices, and then pick the last two:

x = [3 2 5 4 7 3 2 6 4];
[~, ind] = sort(x);
result = ind(end-1:end);

In this case,

result =
     8     5

Comments

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.