# MATLAB: Natural spline, unmkpp gives ‘wrong’ answer

spline natural unmkpp

@Uwe Brauer: this time I formatted your code for you. In future you can do it yourself by selecting the code text and clicking the {} Code button.

Well, it gives the right answer, to a different problem than the one that you think you posed. :)
So first of all, if you read the help for spline:
"However, if Y contains two more values than X has entries, then the first and last value in Y are used as the endslopes for the cubic spline."
That is NOT the definition of a NATURAL spline, although I can see how one might mistake that easily enough. A natural cubic spline has SECOND derivatives zero at the ends.
Next, the coefficients that you see here:
``pspl.coefsans =       2.0595      -4.0595            0            2     -0.37963        2.119      -1.9405            0      0.30026      -1.2976      0.52381            3     -0.53869       1.4048      0.84524            1``
are listed with the constant term LAST, so in decreasing order. The first element in each row is the coefficient of the cubic term (as you show it, with the knot in that interval subtracted off).
So, if we differentiate the spline ONCE, then evaluate it at the end points, we see:
``fnval(fnder(pspl,1),[-3 6])ans =            0  -6.6613e-16``
The first derivatives are indeed zero at the ends, although not the second derivatives.
``fnval(fnder(pspl,2),[-3 6])ans =       -8.119      -3.6548``
If your goal is to generate a natural cubic spline, I'll need to think for a second. :) A smoothing spline will suffice, if we crank down on tol.
``pspl = spaps(x,y,0)pspl =   struct with fields:        form: 'B-'       knots: [-3 -3 -3 -3 -2 1 4 6 6 6 6]       coefs: [2 1.1652 -2.174 6.1053 -0.99415 2.5731 4]      number: 7       order: 4         dim: 1``
It produces a result in B-spline form, but s we see, it is indeed a natural cubic spline.
``fnval(fnder(pspl,2),[-3 6])ans =  -2.6645e-15  -4.4409e-16``
I'm pretty sure there is a direct way to generate a natural cubic spline in pp form, but my mind is drawing a blank at the moment. Drat, I almost forgot about csape.
``pp = csape(x,y,'var')pp =   struct with fields:        form: 'pp'      breaks: [-3 -2 1 4 6]       coefs: [4×4 double]      pieces: 4       order: 4         dim: 1fnval(fnder(pp,2),[-3 6])ans =     0     0fnval(fnder(pp,1),[-3 6])ans =      -2.5044       2.1404pp.coefsans =      0.50439            0      -2.5044            2     -0.28314       1.5132     -0.99123            0      0.22173      -1.0351      0.44298            3     -0.16009      0.96053       0.2193            1``
So a cubic spline in pp form, with natural end conditions. Of course, if you were to use my SLM toolbox, a spline with natural end conditions is one of the many options.