How to select 2nd largest number (or largest if no 2nd largest)
Mostrar comentarios más antiguos
I need to find the second largest number in a vector but the number of elements from 4 to 1 so sometimes there is no second largest number (only the largest number) and in this case I can use the largest number.
I started with b=sort(a) c=(b(:,end-1)
but obviously I get an error when there is only 1 element.
Sorry if I am missing the obvious here!
1 comentario
Julie
el 3 de Oct. de 2011
Respuesta aceptada
Más respuestas (2)
Wayne King
el 30 de Sept. de 2011
Hi Julie, one simple way is
N = 1;
x = randn(N,1);
b = sort(x,'descend');
if (length(b)>1)
b(2)
else
b(1)
end
1 comentario
Wayne King
el 30 de Sept. de 2011
Obviously, you can change N above to something greater than 1, e.g. N = 4
Jan
el 30 de Sept. de 2011
There are some methods:
b = sort(a);
c = b(max(1, end-1));
Or:
b = sort(a, 'descending');
c = b(max(2, length(b)));
Or:
if length(a) == 1
c = a;
else
b = sort(a, 'descending');
c = b(2);
end
Categorías
Más información sobre Matrices and Arrays 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!