MATLAB: How to make a smooth spline connection at endpoints

curve fittingspline

I can draw a smooth spline across points but when I try to join the end to the beginning I get a sharp corner instead of a smooth connection. How can I smooth out the endpoint connection to make a smoothly shaped blob? Here's my code:
x1 = [0 2 1 4 3 2];
y1 = [1 0 2 1 3 2];
tnum = 1000;
t = linspace(0,1,tnum);
x1 = [x1 x1(1)]; % ADDING THE FIRST POINT TO THE END

y1 = [y1 y1(1)]; % ADDING THE FIRST POINT TO THE END
[xt yt] = ParametricSpline(x1, y1);
xref = ppval(xt, t);
yref = ppval(yt, t);
plot(x1, y1, 'o', xref, yref);
function [xtF, ytF] = ParametricSpline(x,y)
arc_length = 0;
n = length(x);
t = zeros(n, 1);
for i=2:n
arc_length = sqrt((x(i)-x(i-1))^2 + (y(i)-y(i-1))^2);
t(i) = t(i-1) + arc_length;
end
t=t./t(length(t));
xtF = spline(t, x);
ytF = spline(t, y);
end

Best Answer

Try csape:
x1 = [0 2 1 4 3 2];
y1 = [1 0 2 1 3 2];
tnum = 1000;
t = linspace(0,1,tnum);
x1 = [x1 x1(1)]; % ADDING THE FIRST POINT TO THE END

y1 = [y1 y1(1)]; % ADDING THE FIRST POINT TO THE END
[xt yt] = ParametricSpline(x1, y1);
xref = ppval(xt, t);
yref = ppval(yt, t);
plot(x1, y1, 'o', xref, yref);
function [xtF, ytF] = ParametricSpline(x,y)
arc_length = 0;
n = length(x);
t = zeros(n, 1);
for i=2:n
arc_length = sqrt((x(i)-x(i-1))^2 + (y(i)-y(i-1))^2);
t(i) = t(i-1) + arc_length;
end
t=t./t(length(t));
xtF = csape(t, x, 'perodic');
ytF = csape(t, y, 'perodic');
end
Result: