How to find second largest value in an array?
Mostrar comentarios más antiguos
Hi
I want to find the second largest and minimum value in array? A=[1;10;15;30;40;50;100].I want to get the result as Second minimum value=10 and second largest value=50 Help me plz...
1 comentario
Walter Roberson
el 7 de Jun. de 2013
What do you want to do if there are multiple instances of the maximum or minimum?
Respuesta aceptada
Más respuestas (5)
Fernando
el 17 de Nov. de 2014
Editada: Walter Roberson
el 14 de Oct. de 2017
function [ y ] = second_min( x )
y = min(x(x>min(x)));
end
&
function [ y ] = second_max( x )
y = max(x(x<max(x)));
end
6 comentarios
Shuang Liu
el 14 de Oct. de 2017
beautiful
surendra bala
el 30 de En. de 2018
Thanks
Satya G
el 6 de Feb. de 2019
Could you please explain how "max(x(x<max(x)))" works?
x<max(x) is giving array of all ones and one zero. How these will be used ?
Aäron Penders
el 26 de Feb. de 2019
Editada: Aäron Penders
el 26 de Feb. de 2019
@Satya G, in case this isn't cleared up yet, i'll explain. It works exactly as you said. "x<max(x)" gives a logical array of ones where x is less than the maximum, and zero where the maximum is found. The zero therefore corresponds to the maximum. Next you give this logical array as an input argument to the data x itself, which returns all values of x where the logical array is equal to one. The value of the maximum where the logical index is zero, is left out. Afterwards the final max() finds the maximum of the above, which corresponds to the second maximum. Look up logical indexing in matlab for more details.
Quite a clever solution, props.
Srinivasa Rao Konda
el 10 de Oct. de 2020
How to find out the index of second largest element?
Walter Roberson
el 10 de Oct. de 2020
Define second largest. In the array [1,2,3,3] what is the second largest? Is it 2 or is it 3?
Steven Lord
el 6 de Nov. de 2017
13 votos
1 comentario
A=[1;10;15;30;40;50;100];
Amax2 = maxk(A,2); Amax2(2)
Amin2 = mink(A,2); Amin2(2)
Walter Roberson
el 7 de Jun. de 2013
for K = A
if sum(A > K) == 1
disp(K)
end
end
1 comentario
per isakson
el 7 de Jun. de 2013
I got your point.
Dedaunan Rimbun
el 5 de Nov. de 2017
Editada: Dedaunan Rimbun
el 5 de Nov. de 2017
I think this one is the best. It has some pros:
- You can specify the largest, second largest, third largest, and so on.
- You can also see the index
Note: I just modify what Walter Roberson suggest.
for k=1:s %s is the number highest number will be shown
k2=0;
for K = A'
k2=k2+1;
if sum(A > K) == k-1
M(k,1)=K;
I(k,1)=k2;
end
end
end
Anil Kumar
el 29 de Jun. de 2022
try this
a=A(:,1);
[p,q]=max(a);
b=A(q,1);
[p1,q1]=max(a(a~=b))
Categorías
Más información sobre Surface and Mesh Plots en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!