p = [1, 2, 3, 4, 5, 6];
x = -5:10;
y = polyval(p, x);
d = 1;
knotInterval = 5;
breaks = -5:knotInterval:10;
pieces = length(breaks)-1;
coefs = nan(pieces*d, length(p));
coefsScaled = nan(pieces*d, length(p));
mu = nan(pieces*d, 2);
yPolyval = nan(pieces, knotInterval+1);
for nPiece = 1:pieces
idxPiece = x >= breaks(nPiece) & x <= breaks(nPiece+1);
coefs(nPiece, :) = polyfit(x(idxPiece), y(idxPiece), length(p)-1);
[coefsScaled(nPiece, :), ~, mu(nPiece, :)] = polyfit(x(idxPiece), y(idxPiece), length(p)-1);
yPolyval(nPiece,:) = polyval(coefs(nPiece, :), x(idxPiece));
end
pp = mkpp(breaks, coefs, d);
ppScaled = mkpp(breaks, coefsScaled, d);
xPolyval = [-5:0; 0:5; 5:10];
plot(x, y, 'x-', x, ppval(pp, x), 'o--', x, ppval(ppScaled, x), '^--', ...
xPolyval(1, :), yPolyval(1, :), 'sq-.', xPolyval(2, :), yPolyval(2, :), 'sq-.', ...
xPolyval(3, :), yPolyval(3, :), 'sq-.')
ylim(1e5*[-1, 3])
legend({'True data', 'pp', 'ppScaled', ...
'Recovered polyval 1', 'Recovered polyval 2', 'Recovered polyval 3'})