Find n minimum values in an array
Asked Answered
S

3

6

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?

Saint answered 8/2, 2013 at 14:34 Comment(4)
Is your question about the algorithm to do that? What programming language are you using?Halfmast
I edited, my bad. I am using Matlab 2012aSaint
What is the structure of your data? You mention "array" and "cells" and "X" and "Y". I created an answer assuming you have arrays X and Y - but re-reading your question I am not actually sure what you have... Can you clarify?Guelph
There are more efficient way than sorting. Google something like "find highest k values". This seems useful.Vin
G
14

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.

Guelph answered 8/2, 2013 at 15:3 Comment(3)
Yeah, sorry I wasn't clear enough. I need to find the 5 lowest values in Y, and then make an average of both the X and Y of these 5 points! Your technique was quite interesting though! I'll keep that trick in mind if it comes in handy!Saint
My technique does exactly what you are asking for... I have edited the code to make it even clearer. If it still doesn't work for you, you need to explain your data structure more clearly.Guelph
Okay, this worked. I thought that by sorting them, you would modify the X values. I misunderstood. Thanks for the help! :DSaint
B
1

How about doing a sort of your array from lowest value to the highest and then selecting the 5 first values. Those will be the 5 min values of your array. Then perform a mean of those 5 values.

This might not be the most memory efficient way of doing this but for just 1000 values it will get the job done!

Hope it helps!

Banlieue answered 8/2, 2013 at 15:3 Comment(0)
G
1

use minmaxselection MATLAB MEX package, which has been specially optimized for this problem:

a = [2,3,4,7,56,4,21, 64, -2];
mink(a, 2)

<< ans = 
<<    -2  2    

mink(a,4)

<< ans =
<<    -2     2     3     4
Guardrail answered 11/11, 2014 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.