Massimo
unread,Dec 20, 2011, 10:41:07 AM12/20/11You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
Hi,
I would like to know if there is a smart way to use interp1 and obtain spline interpolation and linear extrapolation at the same time.
Suppose, for simplicity, I have :
x=linspace(1,5,4); %my x
Y=[x.^2; x.^3; x.^4]; % my Y
xi=[linspace(0.5,5.5,20);linspace(0.2,6,20)]; %my xi
and I wanted to perform spline interpolation for values of xi inside the interval spanned by x (i.e. 1,5), and linear extrapolation for values of xi outside that interval.
The reason is that I believe that spline extrapolation would produce a bad approximation of the true function.
What I came up with is:
clear all
close all
clc
x=linspace(1,5,4); %my x
Y=[x.^2; x.^3; x.^4]; % my Y
xi=[linspace(0.5,5.5,20);linspace(0.2,6,20)]; %my xi
yi_final=zeros(size(xi,1),size(xi,2),size(Y,1)); %initialize yi
ind1=find(xi>min(x) & xi<max(x)); % index for interpolation
ind2=find(xi<=min(x) | xi>=max(x)); %index for extrapolation
yi_mix1=interp1(x,Y',xi(xi>min(x) & xi<max(x)),'spline','extrap'); %interpolate
yi_mix2=interp1(x,Y',xi(xi<=min(x) | xi>=max(x)),'linear','extrap'); %extrapolate
yi_final_temp=zeros(2,20); %initialize temporary variable
for i=1:size(Y,1) %for each Y
yi_final_temp(ind1)=yi_mix1(:,i); %locate interpolation values
yi_final_temp(ind2)=yi_mix2(:,i); %locate extrapolation values
yi_final(:,:,i)=yi_final_temp; %create yi of the same size as Matlab ND interpolation
end
Clearly this is not efficient because I have to call interp1 twice and because I use a for loop which, in a bigger problem, could slow things down...
Is there a better way to tell interp1 to use different methods for interpolation and extrapolation?
Thanks,
Massimo