0

I am trying to find a value or the most similar value to an item in an array. As example if the Item is 3 and the array is [1,2,5,6,9] so the most similar value is 2 as it has the least difference. I already did it but I feel that there is a more efficient way to do it as sometimes it gives the values wrong .. any ideas?

My code:

value = 3;
array = [1 2 5 6 9];
cur = array - value;
theneededvalue = min(cur); %error as it gets the -ve value and I need the smallest positive value
SMH
  • 1,276
  • 3
  • 20
  • 40

2 Answers2

2

You're close. To avoid the problem with the negative values, you can use abs to take the absolute value. You can then get the closest value using the second output of min:

value=3;
array=[1,2,5,6,9];
cur = abs(array-value);

% df is the minimum distance, ind is the index of the minimum distance
[df,ind] = min(cur); 
theneededvalue = array(ind);
MrAzzaman
  • 4,734
  • 12
  • 25
1

MrAzzamans answer is perfectly fine. Just to offer an alternative: what you are doing is interpolating to the nearest value, hence you can use the appropriate function for this interp1() with specifying the interpolation method 'nearest'.

This will probably not be faster than the other solution, but it could be more readable for some people as the word 'nearest' is used, hence we know that something is mapped to a nearest value.

This method requires that your array is sorted.

value = 3;
array = [1 2 5 6 9];
array = sort(array); %// only needed if array is not sorted already

idx = interp1(array, 1:length(array), value, 'nearest'); %// interpolate to nearest index
array(idx)
Nras
  • 4,251
  • 3
  • 25
  • 37