Compute derivative of spline function at a certian value
158 views (last 30 days)
Show older comments
If I have x,y data, and I spline interpolate them:
sp=spline(x,y);
D=@(x) ppval(sp,x);
I want to compute the value of the derivative of the spline function at specific x values, say x1,x2.
Answers (2)
John D'Errico
on 12 Jun 2020
Edited: John D'Errico
on 12 Jun 2020
By far the simplest is to use fnder, IF you have the curve fitting toolbox.
x = linspace(-pi,pi,100);
y = sin(x);
f = spline(x,y);
dfdx = fnder(f);
fnplt(dfdx)
Of course the derivative function should be -cos(x), which is clearly well-approximated here.
You can now evaluate the derivative function at a point easily enough using either ppval or fnval.
ppval(dfdx,pi/4)
ans =
0.70711
fnval(dfdx,pi/4)
ans =
0.70711
If you lack the curve fitting toolbox (get it, if you will be doing any curve fitting at all) you can still do the differentiation easily enough.
D = [3 0 0 0;0 2 0 0;0 0 1 0]';
fp = f;
fp.order = 3;
fp.coefs = fp.coefs*D;
Now to test it...
ppval(fp,pi/4)
ans =
0.70711
So the differentiation was quite easy, even without fnder.
Ameer Hamza
on 12 Jun 2020
Edited: Ameer Hamza
on 12 Jun 2020
Something like this
x = 1:10;
y = x.^2;
sp = spline(x, y);
x1 = 2.5; % point to calculate the derivative
reg = find(x1 < sp.breaks, 1)-1;
deri_val = polyval(polyder(sp.coefs(reg, :)), x1-sp.breaks(reg))
Or create a function handle
x = 1:10;
y = x.^2;
sp = spline(x, y);
reg = @(x1) find(x1 < sp.breaks, 1)-1;
deri_val = @(x1) polyval(polyder(sp.coefs(reg(x1), :)), x1-sp.breaks(reg(x1)));
Result
>> deri_val(2)
ans =
4.0000
>> deri_val(2.5)
ans =
5
>> deri_val(7)
ans =
14.0000
0 Comments
See Also
Categories
Find more on Splines 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!