interp1 returns NaN for last value in x range

跟風遠走 提交于 2019-12-24 06:37:49

问题


I have a question about the interp1 function in MATLAB. Let x be in the range [1, 1024]. However, the following:

yi = interp1(x, y, 1024);

returns NaN.

I've checked my program several times and nothing seems wrong but the result is still weird to me. I'd be thankful if anyone could help.


回答1:


I'm pretty sure that you're not getting to 1024 but rather some value just less like 1023.999999999945435

Try out this very contrived example:

x = 1:10;
y = 1:10;
interp1(x, y, 10) %This works, returns 10

Now try

x = 1:0.99999999768768765:10 %note x(end) will give you 10.0000, very deceptive because sum(x == 10 ) gives 0
interp(x, y, 10) %Returns NaN

So although my example is very contrived, sometimes it could happen that due to precision errors even though the series you specified should get exactly to 1024 it doesn't because of the truncation of representing nice looking decimal number in binary where they no longer look nice.

If this is your issue then either round off x to the appropriate precision or else you could specify extrapolation in the interp1 options but I would think rounding is better because it will stop other unexpected precision issue down the line.




回答2:


You must verify that the value 1024 exists in your input x.

For example

>> x = 1: 2 : 1024;

seems like it contains 1024, but it does NOT!

>> x

   1 3 5 ... 1019 1021 1023

No 1024!

If you want to ensure that 1024 is indeed in x, you can use linspace:

>> x = linspace( 1, 1024, 512 ); % same number of elements as before, but now 1024 is included!



回答3:


To look whether x contains 1024 (or larger), you could use: any(x>=1024)



来源:https://stackoverflow.com/questions/17341927/interp1-returns-nan-for-last-value-in-x-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!