Find and plot the critical points of the spline constructed from the data
x = 1:7; y = [1 3 2 4 4 1 5];
Answer.
Since the number of critical points is not known in advance, we can gather them by appending each new critical point to the vector
critpts. To qualify for inclusion, a root of derivative of the cubic polynomial used on \([x_k, x_{k+1}]\) must be real and must lie within this interval.
s = spline(x, y);
critpts = [];
for k=1:numel(x)-1
r = roots([3 2 1].*s.coefs(k, 1:3));
for j = 1:numel(r)
if isreal(r(j)) && r(j) >= 0 && r(j) <= x(k+1)-x(k)
critpts = [critpts, x(k)+r(j)];
end
end
end
t = linspace(min(x), max(x), 1000);
plot(t, ppval(s, t), x, y, 'r+', critpts, ppval(s, critpts), 'k*')
The script uses
ppval since the spline s is already constructed; calling spline(x, y, ...) repeatedly with the same x, y seems wasteful.
