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
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
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(-1:4)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!