AnnaSchumann
AnnaSchumann

Reputation: 1271

Find nearest set of values to a given value within an array

A = 
0.75
0.6
0.62
0.51
0.53
0.48

Within such an array, how can one calculate the indices of x number of values closest to a given number? For example:

x = 0.5 %Given number 
y = 3; %Number of values closest to (x) to extract

Here we wish to extract the three closest values to 0.5 - 0.51, 0.53 and 0.48.

[~,I] = min(abs(data-b));
c = data(I);

Is what I have thus far but this only extracts a single value - the absolute closest.

Upvotes: 1

Views: 224

Answers (2)

rayryeng
rayryeng

Reputation: 104565

Sorting the absolute differences and choosing the three values that minimize this difference is the most canonical way to do it.... in fact, that's what I recommend.

However for the sake of completeness, if you can use toolboxes consider using knnsearch from the Statistics Toolbox and return the k=3 closest points. The output of knnsearch gives you the indices of the closest points. To find the actual points, index into A after:

A = [0.75
0.6
0.62
0.51
0.53
0.48];

x = 0.5;
y = 3;

IDX = knnsearch(A, x, 'K', y);
out = A(IDX);

We get:

>> out = A(IDX)

out =

    0.5100
    0.4800
    0.5300

Upvotes: 4

Adriaan
Adriaan

Reputation: 18197

A = [0.75
0.6
0.62
0.51
0.53
0.48];

x = 0.5 %Given number 
y = 3; %Number of values closest to (x) to extract

[~,c] = sort(abs(A-x));
yclosest=A(c(1:y));

This uses the second output of sort to index the original array A. First you subtract the number x from the array A and take the absolute value, as you had, then you sort that and take the lowest y numbers and use those to index A.

Upvotes: 5

Related Questions