Compute linear interpolant in pp form and find derivative
6 views (last 30 days)
Show older comments
Alessandro Maria Marco
on 30 Dec 2023
Commented: Alessandro Maria Marco
on 30 Dec 2023
I would like to compute a linear interpolant in pp-form and then use the function fnder to compute its derivative. [The reason to do this is that I am solving a functional equation using collocation and I approximate the policy function using splines, but this is not so relevant here].
I used to do the following with interp1 and 'pp' (this is a minimum working example), but Matlab says that it will be removed in a later release. So my question is how to update this code.
Note: if I use cubic spline or other splines like pchip or makima I know how to do it, e.g.
pp = spline(x_grid,f_grid);
der_pp = fnder(pp,1);
y = ppval(der_pp,x)
but I want to do it for linear splines
Any help is greatly appreciated!
clear;clc;close all
n = 10;
x_grid = linspace(-5,5,n)';
x_grid_fine = linspace(-5,5,10*n)';
f_grid = x_grid.^2;
% Linear interpolant
pp = interp1(x_grid,f_grid,'linear','pp'); % MATLAB does not like it :(
% Derivative of linear interpolant
der_pp = fnder(pp,1);
fun_f_x = @(x) ppval(pp,x);
fun_df_dx = @(x) ppval(der_pp,x);
figure
plot(x_grid,fun_f_x(x_grid),'-o')
hold on
plot(x_grid_fine,fun_f_x(x_grid_fine))
legend('Raw data','Fitted')
figure
plot(x_grid,2*x_grid,'-o')
hold on
plot(x_grid_fine,fun_df_dx(x_grid_fine))
legend('Raw data','Fitted')
0 Comments
Accepted Answer
John D'Errico
on 30 Dec 2023
Edited: John D'Errico
on 30 Dec 2023
n = 10;
x_grid = linspace(-5,5,n)';
f_grid = x_grid.^2; % A simple quadratic polynomial
fn = spapi(2,x_grid,f_grid)
Convert to a pp-form. I might be able to do this directly in the call to spapi, but why bother?
pp = fn2fm(fn,'pp')
fnplt(pp)
So clearly a piecewise linear spline. Now differentiate using fnder.
dfdx = fnder(pp)
fnplt(dfdx)
So easy enough, especially if the interp1 usage is going to turn into a pumpkin one day.
More Answers (0)
See Also
Categories
Find more on Spline Postprocessing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!