I have data = [1 1.2 1.3 1.5 1.8]
I want to find closest values before and after from data for this point, b = 1.23
How do I do this?
So what you have to do is you take the average and you subtract the 5 numbers from the average. Now the result may come in negative as some numbers can be greater than average. For example if 12 is average and you have 11 and 15, you can see 12-11=1 and 12-15=-3 .
So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
Here is another method. The vector data
need not be sorted and b
can be positive or negative.
[~,I] = min(abs(data-b)); c = data(I);
if the data is sorted you can use find:
i_lower = find(data <= b,1,'last'); i_higher = find(data >= b,1,'first'); lower_than_b = data(i_lower) higher_than_b = data(i_higher)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With