Finding the 3rd largest element in an array.

8 vues (au cours des 30 derniers jours)
Eran Sandman
Eran Sandman le 9 Avr 2017
Modifié(e) : Stephen23 le 9 Avr 2017
I've been thinking about sorting the array and extracting the 3rd element , or using max command while everytime i delete the data from a temporary array. But i'm wondering ... How do i find the 3rd largest element in an array using a loop/if or some sort of this stuff.
Thanks, Eran.
  3 commentaires
Jan
Jan le 9 Avr 2017
Modifié(e) : Stephen23 le 9 Avr 2017
@Eran: See this to influence the output to the command window:
doc format
Stephen23
Stephen23 le 9 Avr 2017
"i get variables like '1.285e+4' . how can i sort this out ?"
Sort what out? What is the problem?

Connectez-vous pour commenter.

Réponses (2)

dpb
dpb le 9 Avr 2017
Just go with the first option; the latter sorts the array three separate times. Unless the array size is humongous should be "adequately fast enough".
There's no problem, E formatting is simply an output artifact; doubles are doubles in internal memory storage and everything numerical is a double by default in Matlab unless you specifically cast to some other storage class such as single or in32 or the like.

Jan
Jan le 9 Avr 2017
Modifié(e) : Jan le 9 Avr 2017
x = rand(1, 1000);
% Method 1:
y = sort(x, 'descend');
y(3)
% Method 2:
y = x;
[dum, index] = max(y);
y(index) = -inf;
[dum, index] = max(y);
y(index) = -inf;
y3 = max(y)
% Method 3:
v = -inf(1, 3);
for k = 1:numel(x)
v = sort([v(1:3), x(k)], 'descend');
end
v(3)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by