How do I find values close to a given value?

前端 未结 6 1553
情歌与酒
情歌与酒 2020-12-09 08:56

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 th

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 09:40

    This might be a little bit hacky and inefficient, but I use interp1 to find the single closest value as follows:

    nearestTo = @(x, xq) interp1(x, x, xq, 'nearest');
    nearestTo([2 4 6 8 10], [pi 2*pi 3*pi])  %  4  6  10
    nearestTo(sort([2 7 11 3 5]), abs(-3.5)) %  3
    

提交回复
热议问题