user1578688
user1578688

Reputation: 427

Double interpolation in Matlab

I want to ask you somehting about interpolation in Matlab. I want to know if it's possible to do two different interpolations in the same line. I mean, for example, at the beginning do a linear interpolation and at the middle, approximately, do another kind of interpolation, like spline.

The main problem is that I've done a linear interpolation and it's perfect at the beginning but after some point, I think it would be better another type. If this is possible, how can I code where I want to change it? I've tried to check the documentation about Matlab and I couldn't find anything about modifying interpolations.

Thanks a lot in advance and greetings,

Upvotes: 3

Views: 1204

Answers (1)

learnvst
learnvst

Reputation: 16193

Allow me to elaborate on the comment I made on your post.

If you want to create an output array from an input array using 2 different functions with a split, you can use array index ranges like in the following code example

x = randn(20,1); %//your input data - 20 random numbers for demonstration
threshold = 5; %//index where you want the change of algorithm
y = zeros(size(x)); %//output array of zeros the same size as input

y(1:threshold)     = fun1(x(1:threshold));
y(1+threshold:end) = fun2(x(1+threshold:end));

You could skip the preallocation of y if you like and just concatenate the additional data on to the end of the output. This is particularly useful if a function returns a different number of output elements relative to the number of input elements. The syntax for this is shown below.

y = fun1(x(1:threshold));
y = [y; fun2(x(1+threshold:end))];

EDIT:

In response to your post below, here is a full example . . .

clc; close all

x = -5:5; %//your x-range
y = [1 1 0 -1 -1 0 1 1 1 1 1]; %//the function to interpolate
t = -5:.01:5; %//sampling interval for output

xIdx = 5; %//the index on the x-axis where you want the split to occur
tIdx = floor(numel(t)/numel(x)*xIdx);%//need to calculate as it is at a different sample rate

out = pchip(x(1:xIdx),y(1:xIdx),t(1:tIdx));
out = [out spline(x((1+xIdx):end),y((1+xIdx):end),t((1+tIdx):end))];

%//PLOTTING
plot(x,y,'o',t,out,'-',[x(xIdx) x(xIdx)], [-1.5 1.5], '-')
legend('data','output','split',4);
ylim ([-1.5 1.5])

Which will give . . .

enter image description here

Upvotes: 3

Related Questions