# How to plot multiple functions in Fourier Series?

I have the following periodic problem. We have calculated the coefficients and created the graphs separately

f[x_] := Which[-2 < x < 0, x + 2, 0 < x < 2, 2 - 2 x]
Plot[f[x], {x, -2, 2}]
L = 4;(*period*)
a[n_] := (2/L)*Integrate[f[x]*Cos[2 n*Pi*x/L], {x, -L/2, L/2}]
a[0] := (1/L)*Integrate[f[x], {x, -L/2, L/2}]
b[n_] := (2/L)*Integrate[f[x]*Sin[2 n*Pi*x/L], {x, -L/2, L/2}]
F[x_, Nmax_] :=
a[0] + Sum[
a[n]*Cos[2 n*Pi*x/L] + b[n]*Sin[2 n*Pi*x/L], {n, 1, Nmax}]
p[Nmax_, a_] :=
Plot[Evaluate[F[x, Nmax]], {x, -a, a}, PlotRange -> All,
PlotPoints -> 200]
f[x_] := If[x > 0, 2 - 2 x, x + 2];
a[n]
a[0]
b[n]
Simplify[%, n \[Element] Integers]
curve1 =  p[5, 2]
curve2 = p[10, 2]
curve3 = p[15, 2]
curve4 = p[20, 2]


Now we are trying to create a plot with the initial functions and the curves (curve1,curve2,curve3,curve4) and then to create the same with the command manipulate. I have used the following code

Plot[{f[x], curve1, curve2, curve3, curve4}, {x, -2, 2}]
Manipulate[Plot[{f[x], F[x, Nmax]}, {x, -2, 2}], {Nmax, 0, 30}]


But the first command returns the following plot, and the manipulate does not work.

Any help would be greatly appreciated. Thank you!

• Use Piecewise instead of Which and If. Also it's kind of weird you're redefining f. You can do everything in your problem much more simply with L = 4; f[x_] := Piecewise[{{x + 2, -2 < x < 0}, {2 - 2 x, 0 < x < 2}}]; fs = Table[ExpToTrig[FourierSeries[f[t], t, i, FourierParameters -> {1, 2 \[Pi]/L}]], {i, 10}]; ListAnimate[Plot[{f[t], Re[#]}, {t, -2, 2}] & /@ fs] Commented Jan 24, 2023 at 23:13
• Very helpful thanks! Commented Jan 24, 2023 at 23:32

ClearAll["Global*"]
f[x_] := Piecewise[{{x + 2, -2 <= x <= 0}, {2 - 2 x, 0 < x <= 2}}]
L = 4;(*period*)
a[(n_Integer)?Positive, x_Symbol] = (2/L)*Integrate[f[x]*Cos[2 n*Pi*x/L], {x, -L/2, L/2}];
a[0, x_Symbol] = (1/L)*Integrate[f[x], {x, -L/2, L/2}];
b[n_Integer, x_Symbol] = (2/L)*Integrate[f[x]*Sin[2 n*Pi*x/L], {x, -L/2, L/2}];

F[x_Symbol, Nmax_Integer] := a[0, x] + Sum[a[n, x]*Cos[2 n*Pi*x/L] + b[n, x]*Sin[2 n*Pi*x/L], {n, 1, Nmax}]

p[Nmax_Integer, a_?NumericQ, x_Symbol] :=
Plot[Evaluate[F[x, Nmax]], {x, -a, a}, PlotRange -> All, PlotPoints -> 200];

Manipulate[
Module[{x},
Plot[Evaluate[{f[x], F[x, Nmax]}], {x, -2, 2},
PlotRange -> {Automatic, {-2, 2}}]
],
{{Nmax, 0, "number terms"}, 0, 30, 1, Appearance -> "Labeled"},
TrackedSymbols :> Nmax]
`
• Thank you very much again! Commented Jan 27, 2023 at 0:41