0

How can I search and find, for a given target value, the closest value in an array? For example here is my array:

0, 54, 10, 11, 152, 7

For example, when I search with the target value 6, the code shall return 7

Ph MO
  • 19
  • 1
  • 6

2 Answers2

5
% Array to search in, modified to have more than one closest value.
x = [0, 5, 10, 11, 152, 7];

% Target value.
target = 6;

Calculate absolute "distances" between each array element and the target value.

% Temporary "distances" array.
temp = abs(target - x);

Find the minimum "distance" value by min. Compare the temporary "distances" array to that minimum value (resulting in some binary array), and then use find to get the corresponding indices, which finally can be used to get the values from the original input array x.

% Find "closest" values array wrt. target value.
closest = x(find(temp == min(abs(target - x))))

The output looks like this:

closest =
   5   7
HansHirse
  • 18,010
  • 10
  • 38
  • 67
  • Thank you for your input. For my program i just need one closest value 5 or 7.. How can i avoid to get 2 values? – Ph MO Apr 30 '19 at 08:36
  • @PhMO For example, use `closest = x(find(temp == min(abs(target - x)), 1, 'first'))`, where the `find` method is set to just find `1` (one) entry, starting at the `first` index. Alternatively, you could also use `last`. – HansHirse Apr 30 '19 at 08:41
1

You can use interp1 with the 'nearest' option:

V = [0, 54, 10, 11, 152, 7];
x = 6;
result = interp1(V,V,x,'nearest');
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147