How to find second largest value and its index in an array?

93 visualizaciones (últimos 30 días)
charu shree
charu shree el 7 de Oct. de 2021
Editada: Matt J el 7 de Oct. de 2021
Hello everyone, I am trying to find the second largest value and its index in an array given by
A = [11,15,16,99,87]
Any help in this regard will be highly appreciated.

Respuestas (2)

Matt J
Matt J el 7 de Oct. de 2021
Editada: Matt J el 7 de Oct. de 2021
A = [11,15,16,99,87];
[mx,ind]=maxk(A,2)
mx = 1×2
99 87
ind = 1×2
4 5
secondMax=mx(2)
secondMax = 87
index=ind(2)
index = 5
  1 comentario
Matt J
Matt J el 7 de Oct. de 2021
Or, if ties are not allowed
A = [11,15,16,99,99];
[u,i]=unique(A);
secondMax=u(end-1)
secondMax = 16
index=i(end-1)
index = 3

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 7 de Oct. de 2021
charu, did you try sorting and using find()? We also need to know your definition of "second largest".
% What is the second largest in this vector: 99 or 87?
A = [11,15,16,99,87, 99, 87]
% Assume it's 87, then to find all locations where 87 occurs:
sortedA = sort(unique(A), 'descend')
indexes = find(A == sortedA(2))
You get
A =
11 15 16 99 87 99 87
sortedA =
99 87 16 15 11
indexes =
5 7

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by