How to use inerpolation option with end values? If I use interp1 command it's giving NaN as the output if input is out of the range. I want to use end values if input is out of the range?

89 views (last 30 days)
1 120
2 5000
3 12000
My input is something like this. If i give 4 as my input currently it's giving NaN as the output but I want output to be 12000(i.e end value)

Accepted Answer

Stephen23
Stephen23 on 7 Aug 2018
Edited: Stephen23 on 7 Aug 2018
>> X = [1,2,3];
>> Y = [12,5000,12000];
>> interp1(X,Y,4,'nearest','extrap')
ans = 12000
>> interp1(X,Y,4,'linear','extrap')
ans = 19000
But note that you cannot pick a method like linear, spline, etc, and also limit the extrapolation to the end values:
>> interp1(X,Y,[0,1.5,4],'linear','extrap') % linear -> not end values
ans =
-4976 2506 19000
>> interp1(X,Y,[0,1.5,4],'nearest','extrap') % nearest -> not linear interpolated
ans =
12 5000 12000
But you can easily select the interpolation method and limit to the end values, by simply using max and min:
>> max(Y(1),min(Y(end),interp1(X,Y,[0,1.5,4],'linear','extrap')))
ans =
12 2506 12000
If you only need to extrapolate in one direction then you could set the extrapolation value:
>> interp1(X,Y,[1.5,4],'linear',Y(end))
ans =
2506 12000
  2 Comments
Parthiban C
Parthiban C on 10 Aug 2018
Thank you for your response. This one worked for my problem. max(Y(1),min(Y(end),interp1(X,Y,[0,1.5,4],'linear','extrap'))) ans = 12 2506 12000
Christian
Christian on 19 Apr 2021
This min/max stuff does not work that way, if Y is not monotonously increasing, let's say
>> Y = [12,5000,4000];
Then I get this:
>> max(Y(1),min(Y(end),interp1(X,Y,[0,1.5,4],'linear','extrap')))
ans =
12 2506 3000
And I guess for X=4 we want to see 4000 instead of 3000.
In general monotony assumptions should only be made towards X, not towards Y.

Sign in to comment.

More Answers (0)

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!