An annoying extrapolation problem
    6 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
    Mohammad Shojaei Arani
 il 4 Dic 2023
  
    
    
    
    
    Modificato: Dyuman Joshi
      
      
 il 4 Dic 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 Commento
  Dyuman Joshi
      
      
 il 4 Dic 2023
				
      Modificato: Dyuman Joshi
      
      
 il 4 Dic 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)
Risposta accettata
  Bruno Luong
      
      
 il 4 Dic 2023
        
      Modificato: Bruno Luong
      
      
 il 4 Dic 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)
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


