How to change my spline code to natural spline?

5 views (last 30 days)
I have written the following code to recieve a function from the user and a set of points to be interpolated by natural cubic spline.
funstr = input('Please enter your function: ', 's');
f = str2func( ['@(x) ' funstr ] );
x = input('Please enter the points separated with space in row vector form: ');
y = f(x);
m = min(x);
M = max(x);
xx = linspace(m-10,M+10,100);
values = csapi(x,y,xx);
plot(x,y,'b');
hold on
plot(xx, values - xx,'r')
How can I modify it so that it uses Natural cubic spline rather than spline? Also is there a way to access the coefficients of each spline polynomial s(x) for each previously given node point in some [a,b] interval?
P.S: I have already searched every spline related quetsion on the site and they were not helpful.
  11 Comments
Mali Yaser
Mali Yaser on 28 Jan 2022
The error is in the following. If I remove that line which is intended to plot the error function, it would work without a problem.
plot(xx, values - xx,'r')
Walter Roberson
Walter Roberson on 29 Jan 2022
There a couple of possibilities for how "Matrix dimensions must agree" could occur in that statement.
The simplest possibility is that xx and values are vectors but they do not have the same orientation, and that you are using R2015a or earlier. (If you are using R2015b or later then that situation would not lead to that message, but you would get a plot you did not expect.)
Another possibility is that xx is a vector but values is not a vector, and the non-singular sizes do not match. For example, a (1 x 3) minus a (3 x 2) would not be permitted, but a (3 x 1) minus a (3 x 2) would be permitted because the mis-match in sizes, 1 vs 2, only involves singular dimensions. (3 x 1) minus (3 x 2) would be equivalent to repmat(the_3x1, [1 2]) - the_3x2
Beyond that... both could be matrices with mismatched sizes.
If values and xx are both vectors, make sure they have the same orientation -- either both row vectors or both column vectors.

Sign in to comment.

Answers (1)

Torsten
Torsten on 28 Jan 2022
Edited: Walter Roberson on 28 Jan 2022
One google search and so many hits, e.g.
The page
also answers the question about the spline coefficients.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!