22

I have data = [1 1.2 1.3 1.5 1.8]

I want to find closest values before and after from data for this point, b = 1.23

How do I do this?

ObscureRobot
  • 7,306
  • 2
  • 27
  • 36
nsy
  • 251
  • 2
  • 3
  • 4

6 Answers6

23

Here is another method. The vector data need not be sorted and b can be positive or negative.

[~,I] = min(abs(data-b));
c = data(I);
Doubt
  • 1,163
  • 2
  • 15
  • 26
11

if the data is sorted you can use find:

i_lower  = find(data <= b,1,'last');
i_higher = find(data >= b,1,'first');

lower_than_b  = data(i_lower)
higher_than_b = data(i_higher)
bdecaf
  • 4,652
  • 23
  • 44
5

How about min(abs(data - b))?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

This method generalizes Doubt's answer to the case where there are multiple elements in b that you are searching for:

ind=knnsearch(data',b) c=data(ind)

which returns the index (or array of indices), ind, of the closest element (or elements) in data to the elements listed in b.

Note that data is transposed because the set to be searched in needs to be a column vector. If be had multiple elements then it should also be a column vector.

Also, this method can be generalized to give 2nd, 3rd, 4th ... closest neighbors (see documentation).

It also generalizes to the case when the data is higher dimensional (If d dimensions then test and b would have d columns).

cantorhead
  • 121
  • 4
1

This might be a little bit hacky and inefficient, but I use interp1 to find the single closest value as follows:

nearestTo = @(x, xq) interp1(x, x, xq, 'nearest');
nearestTo([2 4 6 8 10], [pi 2*pi 3*pi])  %  4  6  10
nearestTo(sort([2 7 11 3 5]), abs(-3.5)) %  3
Alex Hirzel
  • 1,719
  • 2
  • 12
  • 18
0
data = [1 1.2 1.3 1.5 1.8]

b = 1.23

find(abs(data-b)==min(abs(data-b)))
nkjt
  • 7,825
  • 9
  • 22
  • 28
Aliton Oliveira
  • 1,224
  • 1
  • 15
  • 26