An annoying extrapolation problem

5 次查看(过去 30 天)
Hello,
I have a simple problem but it seems difficult to solve. MATLAB command interp1 has a nice extrapolation option but, unfortunately
it only considers just one extrapolation value outside of our domain. Assuming that my interval is [L R], I would like to extrapolate my function
f to be f(L) when x<L and also I want to extrapolate f with f(R) when x>R. This works but I cannot vectorise this. And, this is quite annoying. To make it clear what is my point the best is to go for a simple example. Consider the following
x1=linspace(0,pi/2,1000);y1=sin(x1);
f1=@(x)interp1(x1,y1,x,'spline');
f=@(x)interp1(x1,y1,x,'spline',0).*(x>=0 && x<=pi/2)+f1(0).*(x<0)+f1(pi/2).*(x>pi/2);
If I type f(3) or f(4) then I get 1. But, when I type f([3 4]) it, unfortunately, throws an error message. I know why it gives error message but
I cannot fix this.
Note: I COULD WRITE f1=@(x)interp1(x1,y1,x,'spline','extrap'); BUT I DO NOT LIKE TO USE THIS SINCE THIS IS NOT
APPROPRIATE FOR THE NATURE OF MY ACTUAL PROBLEM (NOT SHOWN). THE EXAMPLE ABOVE IS ONLY TO SHOW YOU MY PROBLEM.
Thanks for your help in advance!
Babak
  1 个评论
Dyuman Joshi
Dyuman Joshi 2023-12-4
编辑:Dyuman Joshi 2023-12-4
I am aware that Bruno has provided an efficient solution to the problem, but I'll make a different point nonetheless -
"I know why it gives error message but I cannot fix this."
Look into the difference between &&, || and &, | (double vs single)

请先登录,再进行评论。

采纳的回答

Bruno Luong
Bruno Luong 2023-12-4
编辑:Bruno Luong 2023-12-4
Because you insist on using anonymous function and ugly combined expression using scalar logical expression. The trick is no longer smart.
Just give up any of those then you are OK.
Also different way
x1 = linspace(0,pi/2,1000);y1=sin(x1);
lo = min(x1); % 0
up = max(x1); % pi/2
f = @(x) interp1(x1, y1, min(max(x,lo),up), 'spline')
f = function_handle with value:
@(x)interp1(x1,y1,min(max(x,lo),up),'spline')
f(-1:4)
ans = 1×6
0 0 0.8415 1.0000 1.0000 1.0000

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by