Find n minimum values in an array

Vissenbot picture Vissenbot · Feb 8, 2013 · Viewed 14k times · Source

I am using Matlab 2012a.

I have an array of k cells (say 1000). I need to find the 5 lowest values of this array and need to do an average of those values in X and Y.

Anyone has an idea how to do that?

Answer

Floris picture Floris · Feb 8, 2013

Assuming you have arrays X and Y, and you want to find the five lowest Y values:

[m mi] = sort(Y);
lowest5index = mi(1:5);
lowest5Y = Y(lowest5index);
lowest5X = X(lowest5index);

meanYlowest5 = mean(lowest5Y);
meanXlowest5 = mean(lowest5X);

Explanation:

The sort command with two output parameters returns both the sorted array (in m) and the indices in the original array (mi). The first five indices mi(1:5) correspond to the five lowest values. Taking the mean of these values for both X and Y will do what we want. If I didn't understand your problem statement, please clarify your question and I will take another shot at it.