Compute derivative of spline function at a certian value

43 Ansichten (letzte 30 Tage)
Mohammad Farhat
Mohammad Farhat am 11 Jun. 2020
Kommentiert: Amdad Chowdury am 7 Nov. 2020
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.

Antworten (2)

John D'Errico
John D'Errico am 12 Jun. 2020
Bearbeitet: John D'Errico am 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
Ameer Hamza am 12 Jun. 2020
Bearbeitet: Ameer Hamza am 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

Kategorien

Mehr zu Spline Postprocessing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by