An annoying extrapolation problem
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mohammad Shojaei Arani
le 4 Déc 2023
Modifié(e) : Dyuman Joshi
le 4 Déc 2023
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 commentaire
Dyuman Joshi
le 4 Déc 2023
Modifié(e) : Dyuman Joshi
le 4 Déc 2023
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)
Réponse acceptée
Bruno Luong
le 4 Déc 2023
Modifié(e) : Bruno Luong
le 4 Déc 2023
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)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!