Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find values close to a given value?

Tags:

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?

like image 843
nsy Avatar asked Nov 11 '11 02:11

nsy


People also ask

What do we do to find the close value of another number?

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 .

How do you find the nearest number in a range?

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.


2 Answers

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); 
like image 188
Doubt Avatar answered Sep 30 '22 01:09

Doubt


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) 
like image 40
bdecaf Avatar answered Sep 30 '22 02:09

bdecaf