Example (Strang, p.179)
In[47]:=
m={{2,1,0,0,0},{1,4,1,0,0},{0,1,4,1,0},{0,0,1,4,1},{0,0,0,1,2}};
MatrixForm[m]
X={0,1,2,3,4};
u={0,1,4,1,0};
du={1,4,0,-4,-1}
Out[47]=
2 1 0 0 0 1 4 1 0 0 0 1 4 1 0 0 0 1 4 1 0 0 0 1 2
Out[48]=
{1, 4, 0, -4, -1}
In[49]:=
LinearSolve[m,3du]
Out[49]=
{0, 3, 0, -3, 0}
Since leading up to (0, 0) the second derivative is 0, we will have a line, and we are leading up to (0, 0) with s0=0 (from above), we have a horizontal line at 0 up to (0, 0).
In[50]:=
spline0[x_]:=0
On the interval from x=0 to x=1 we have hermite[x] with a=u0=0, b=s0=0, c=u1=1, d=s1=3.
In[51]:=
Clear[x]
spline1[x_]:=hermite[x,0,0,1,3];
spline1[x]
Simplify[%]
Out[51]=
2 2
(3 - 2 x) x + 3 (-1 + x) x
Out[52]=
3 x
On the interval from x=1 to x=2 we have hermite[x-1] with a=u1=1, b=s1=3, c=u2=4, d=s2=0.
In[53]:=
spline2[x_]:=hermite[x-1,1,3,4,0];
spline2[x]
Simplify[%]
Out[53]=
2 2
(1 + 2 (-1 + x)) (-2 + x) + 3 (-2 + x) (-1 + x) +
2
4 (3 - 2 (-1 + x)) (-1 + x)
Out[54]=
2 3
4 - 12 x + 12 x - 3 x
On the interval from x=2 to x=3 we have hermite[x-2] with a=u2=4, b=s2=0, c=u3=1, d=s3=-3.
In[55]:=
spline3[x_]:=hermite[x-2,4,0,1,-3];
spline3[x]
Simplify[%]
Out[55]=
2
4 (1 + 2 (-2 + x)) (-3 + x) +
2 2
(3 - 2 (-2 + x)) (-2 + x) - 3 (-3 + x) (-2 + x)
Out[56]=
2 3
-44 + 60 x - 24 x + 3 x
On the interval from x=3 to x=4 we have hermite[x-3] with a=u3=1, b=s3=-3, c=u4=0, d=s4=0.
In[57]:=
spline4[x_]:=hermite[x-3,1,-3,0,0];
spline4[x]
Simplify[%]
Out[57]=
2 2
(1 + 2 (-3 + x)) (-4 + x) - 3 (-4 + x) (-3 + x)
Out[58]=
3
(4 - x)
On the interval after x=4 we have a line with slope s4=0 so a horizontal line at u4=0.
In[59]:=
spline5[x_]:=0
In[60]:=
spline[x_]:=If[x<=0,spline0[x],
If[x<=1,spline1[x],
If[x<=2,spline2[x],
If[x<=3,spline3[x],
If[x<=4,spline4[x],spline5[x]]
]
]
]
]
In[61]:=
plot1=ListPlot[Table[{X[[i]],u[[i]]},{i,1,5}],PlotStyle->{RGBColor[1,0,0],PointSize[.02]}];
plot2=Plot[spline[x],{x,-1,5}];
Show[plot1,plot2];
