Wednesday, April 24, 2013

How to find the closest value in 1D array in Matlab

My function GetClosestValue  finds the closest value in the gives array with respect to the entered target value.


EXAMPLE:

>>v=[1.0000   25.0000   26.0000   10.0000   25.0000   21.0000    8.0000    1.0500    2.0000];
>>[aa, bb]=GetClosestValue(v, 1.03)

aa =

    1.0500


bb =

     8



%%%%%%%%%%%%% CODE %%%%%%%%%%%%%%%%


function [x_ii, ii]=GetClosestValue(x, x_T)
% [x_ii, ii]=GetClosestValue(x, x_T)
% x= 1D array
% x_T= target value
% x_ii  = final value
% ii   = index corresponding to the final value
% Find the closest value (x_ii) and index (ii) in the given array with respect to the entered target value (x_T)


[mm, nn]=size(x);

if nn>mm
    x=x';
end

matrix=[abs(x-x_T) , x];

% sorting with respect to the first column, i.e. to the absolute differences among x and x_T

matrix=sortrows(matrix);

x_ii=matrix(1,2);
ii=find(x==x_ii);



Did you like this post?
Let me know!