An annoying extrapolation problem

조회 수: 5 (최근 30일)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2023년 12월 4일
편집: Dyuman Joshi 2023년 12월 4일
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