Open In App

MATLAB Find Closest Value in Array

Last Updated : 22 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




% MATLAB code 
% using the interp1 function to get closest value
% array
arr=[1 2 3 4 5 6 7];
target = 2.3;    %target value
  
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




% MATLAB code When target value is greater 
% or less than the maximum and minimum value of array
arr=[1 2 3 4 5 6 7];
  
% Target lesser than minimum of array
target1 = -31;    
  
% Target greater than maximum of array
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




% MATLAB code for 'extrap' parameter
arr=[1 2 3 4 5 6 7];
target = 31;
closest = interp1(arr,arr,target,'nearest','extrap');


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads