How to find 3 maximum element in array and their indices without sorting

1 view (last 30 days)
Hi everybody
I have an array like this(its data type is double):
a = {1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1}
I want to return 3 or more maximum element with their indices without any changes in the original form of "a" (like sorting it)
thanks in advance
  3 Comments
mhm
mhm on 21 Jan 2016
I dont want to sort this array and in addition I need their indices in the original array.
so do you have any solution for this problem?
thanks in advance
Stephen23
Stephen23 on 21 Jan 2016
"I dont want to sort this array "
Yes you do. Sorting means putting those values into order. You want to select some depending on their order, ergo you want to sort the values. You are contradicting yourself.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 21 Jan 2016
Edited: Guillaume on 21 Jan 2016
You can call max three times, each time removing the element you found, but see my comment above, you are effectively sorting the set
a = [1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1];
elemrequired = 3;
sorteda = zeros(1, elemrequired)
sortedindices = zeros(1, elemrequired)
for iter = 1:elemrequired
[sorteda(iter), sortedindices(iter)] = max(a);
a(sortedindices(iter)) = nan;
end
You are effectively emulating the first elemrequired steps of an inefficient sort algorithm (selection sort).
This is of course simpler, and probably faster:
a = [1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1];
elemrequired = 3;
[sorteda, sortedindices] = sort(a, 'descend');
sorteda = sorteda(1:elemrequired)
sortedindices = sortedindices(1:elemrequired)
  1 Comment
Guillaume
Guillaume on 21 Jan 2016
Edited: Guillaume on 21 Jan 2016
"I dont want to sort this array" "I want to return 3 or more maximum element": I'll repeat: you can call it whatever you want, finding 3 or more maximum element, mathematically, is the definition of sorting.
"I need their indices in the original array": I've edited my answer to return that. The code does not use sort but is in effect reproducing the first steps of a selection sort. There is no way around it.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!