How to specify breaks for spline fitting?
6 views (last 30 days)
Show older comments
Hello,
I want to fit piecewise, but continous functions to a given data and get the corresponding polynomial coefficients.
This can be done by pp = spline(x,y) , however, the spline function returns a fixed number of polynomials on uniformly distributed break points. How can I fit my data to a user defined number of pieces and specify the breaks for each polynomial?
1 Comment
Bruno Luong
on 28 Jul 2022
Edited: Bruno Luong
on 28 Jul 2022
"This can be done by pp = spline(x,y) , however, the spline function returns a fixed number of polynomials on uniformly distributed break points."
This statement is plain wrong, it returns the piecewise 3rd order polynomial on the x data you specify.
x=cumsum(rand(1,5))
y=rand(size(x))
pp=spline(x,y)
You see that the "breaks" or knots are exactly the x vector and it is not uniform.
And spline functions return the interpolation function, not the fit.
As you use wrong mathematical vocabulary and claim statement, it is hard to know what is your aim.
Answers (2)
Bruno Luong
on 28 Jul 2022
It seems I iedit again a wrong post that is not mine ! Sorry that happens for people who is distracted like me, probably age is not helping.
I put here my comment followed Matt's answer, and I would like to point out that a simple linear algebra is enough because spline function is linear with repect to fit y-value:
% Generate test data
xdata = rand(1,200);
ydata = sin(10*xdata); % whatever the model
ydata = ydata + 0.1*randn(size(ydata));
xknots = linspace(0,1,10); % The vector of knots that you want it to be
% Find out y vector at xknots such that the spline will fit the data
nknots = length(xknots);
ndata = length(xdata);
M = zeros(ndata,nknots);
for k=1:nknots
byk = accumarray(k,1,[nknots,1]);
M(:,k) = spline(xknots,byk,xdata);
end
y = M\ydata(:);
% Check the spline model
xq = linspace(0,1,100);
yq = spline(xknots,y,xq);
plot(xdata, ydata, '.', xq, yq, 'r')
3 Comments
Bruno Luong
on 28 Jul 2022
Edited: Bruno Luong
on 28 Jul 2022
"Is this also true if there are end-slopes specified in y?"
Once x, y values are specified, the cubic spline function still has 2 DOFs. Most of the time if one select a homogenuous boundary condition such as
- f'''(left) = f''(right) = 0, (natural spline)
- f'(left) = f'(right) = 0
- not-a-knot bc (MATLAB spline)
- f(left) = f(right) and f'(left) = f'(right) (periodic spline)
then yes it is linear.
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!