secons max number in a vector

Hi I need to find maximum and second maximum number in a vector. Can you please help?
For max, its max(X), but for second max I am unable to figure out.
Your help is appreciated
P

 Respuesta aceptada

Rick Rosson
Rick Rosson el 24 de Nov. de 2011

0 votos

a = max(X);
Y = X(X ~= a);
b = max(Y);

4 comentarios

bym
bym el 24 de Nov. de 2011
wouldn't that be
Y = (X(X ~= a)); % ??
Jan
Jan el 25 de Nov. de 2011
Yes, proecsm, now it is revealed that Rick thinks in C.
@Rick: This is a nice example for the limitations of Matlab. MAX(X) searchs the complete vector for the largest element. X~=a creates a LOGICAL vector of the same size as X and X(X~=a) processes the complete vector again. The temporary Y occupies almost as much memory as X. Finally the complete vector Y is searched.
If the input vector does not match in the processor cache, waiting for the slow RAM will be a brute bottleneck for this program. Usign SORT and taking the last two elements is not a good alternative for large inputs also, because it takes a lot of time and demands for storing another temporary array also.
A C-Mex function will be much faster - nearly as fast as a single MAX command: If the current element is larger than the old maximum, store the old maximum as 2nd max value and the current element as new maximum. This can even be multithreaded.
Walter Roberson
Walter Roberson el 25 de Nov. de 2011
There are apparently efficient linear-time routines to find the N largest or N smallest numbers in a list, and supposedly they do not need to do a mini-sort of N elements to find the proper place in the list for each new value being tested. I have not yet been able to understand the logic in the paper that describes the internal comparison scheme.
Rick Rosson
Rick Rosson el 25 de Nov. de 2011
Everyone makes mistakes. Glass houses...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Entering Commands en Centro de ayuda y File Exchange.

Preguntada:

el 24 de Nov. de 2011

Community Treasure Hunt

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

Start Hunting!

Translated by