MATLAB Find Closest Value in Array
Last Updated :
22 Nov, 2022
MATLAB arrays store numbers and allow users to perform various operations on them. In this article, we shall see how to find the closest value to a given target value in a MATLAB array. The same task can be performed by using the nearest neighbor interpolation, which we shall explore in the following sections with examples.
Method 1: Using the Nearest Neighborhood Interpolation
Using the nearest neighborhood interpolation method in MATLAB, we can find the value of the closest value to a given value in an array. This is done by using the interp1() function and selecting the interpolation as ‘nearest’.
interp1(array, array, <target value>, ‘nearest’)
Example 1:
Matlab
arr=[1 2 3 4 5 6 7];
target = 2.3;
closest = interp1(arr,arr,target, 'nearest' )
|
Output:
This should return 2 as it is the closest value to 2.3
Method 2: Target Value is Greater or Less than Maximum and Minimum Value of Array
In this case, the standard interpolation method used above will return NaN as the queried values do not lie between the elements of the array.
Example 2:
Matlab
arr=[1 2 3 4 5 6 7];
target1 = -31;
target2 = 23;
closest_1 = interp1(arr,arr,target1, 'nearest' );
closest_2 = interp1(arr,arr,target2, 'nearest' );
|
Output:
Both the interpolation results will return NaN.
To fix this problem we only need to extrapolate on the given array which can be done by adding the ‘extrap’ parameter for extrapolation. See the following example for seeing the implementation of the same.
Example 3:
Matlab
arr=[1 2 3 4 5 6 7];
target = 31;
closest = interp1(arr,arr,target, 'nearest' , 'extrap' );
|
Output:
Share your thoughts in the comments
Please Login to comment...