Return Indices for x Smallest/Largest Values in Array

2 visualizaciones (últimos 30 días)
Nicholas Sbalbi
Nicholas Sbalbi el 4 de Jun. de 2020
Comentada: David Hill el 4 de Jun. de 2020
Is there a clean and elegant way for extracting the indices of the x smallest or largest values in an array? For example say I have an array [1,6,4,9,0] and I want the indices of the 3 smallest values, [1,3,5]. The functions min/max only return the index for the single minimum/maximum.

Respuesta aceptada

Steven Lord
Steven Lord el 4 de Jun. de 2020
Use the second output of the mink or maxk functions.

Más respuestas (2)

David Hill
David Hill el 4 de Jun. de 2020
[~,idx]=sort(x);
minIdx=idx(1:3);%for minimum 3
maxIdx=idx(end:-1:end-2);%for maximum 3

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 4 de Jun. de 2020
Editada: Sulaymon Eshkabilov el 4 de Jun. de 2020
here is one of the possible ways:
A = [...; ...; ...];
[Row1,Col1]=find(max(A(:))==A) % Shows row# and col# of largest element
[Row2,Col2]=find(min(A(:))==A) % Shows row# and col# of smallest element

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by