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
% 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
You can use interp1
with the 'nearest'
option:
V = [0, 54, 10, 11, 152, 7];
x = 6;
result = interp1(V,V,x,'nearest');