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

find 3 max element in an array and their indices

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

Best Answer

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)