The Plucked string

We'll use Mathematica's calculus package to solve this problem.  We begin by defining a "Hat" function that will correspond to the initial conditions on the string.  This is tricky though because as we will learn later, the function has to be periodic.  We can make a hat-like function out of sines or cosines depending on whether we want the periodic extension of the function to look like a sawtooth or a blocky sine wave.  We will go for the blocky sine wave.  In the interval of interest [0,1] it will look like a hat.

<< Calculus`FourierTransform`

h[x_]  =  If[x  <  .5,  x,  (1 - x)]g[x_]  =  If[x  >  -.5,  x,  -(x + 1)]f[x_]  =  If[x  <=  0,  g[x], h[x]]

Plot[f[x], {x, -1, 1}]

We can directly compute the Fourier Series of the function.  You can safely ignore the error messages about accuracty.  The result is accurate enough for our purposes.

\(\(fs[x_]\  = NFourierTrigSeries[f[x], {x, \(-1\), 1}, 10]
\)\)

The Mathematica chop function is designed to get rid of extremely small but not precisely zero numbers.

\(\(
Chop[fs[x]]\)\)

Plot[fs[x], {x, 0, 1}]

But for our purposes we just need the Fourier coefficients.  We'll stuff these into an array for later use.

\(numcoef\  = \ 6; 
coeftab\  = \ Table[0, {i, numcoef}]; 

    Do[
		\(coeftab[\([i]\)] = 
        NFourierSinSeriesCoefficient[f[x], {x, \(-1\), 1}, i]; \)
	, {i, 6}]
      \)

\(\(
ListPlot[coeftab, PlotJoined -> True, PlotRange -> All]\)\)

Here is the core code.The Do loop is over small time steps so we can build up the solution as a function of time for purposes of animation.  The Sum is over the nonzero coefficients in our Fourier series solution of the wave equation.  This Sum is exactly the sum in point 7 of our discussion of separation of variables in 1D.  After the snapshots are computed you can animate the results.

\(\(\ nsteps\  = \ 50; 
\ dt = \ 1\ /\((nsteps - 1)\); 
		
    Do[
		t\  = \ dt\ \((i - 1)\); 
		
      \(Plot[
			
        Sum[coeftab[\([j]\)] Sin[j\ Pi\ x] Cos[j\ Pi\ t], {j, numcoef}], {x, 
          0, 1}, 
			PlotRange -> 
				{{0, 1}, {\(-.5\), .5}}]; \)

      	, {i, nsteps}]\)\)