0
c1[n_] := 1/2/Pi Integrate[Sign[x] Exp[-I n x], {x, -Pi, Pi}]; 
c2[n_] = Simplify[c1[n], Assumptions -> Element[n, Integers]]; 
c[n_] := If[n == 0, c1[0] = 0];
f5[x_] = Sum[c[k] Exp[I k x], {k, -10, 10}]; 
Plot[{f5[x], Sign[x]}, {x, -Pi, Pi}]

I am trying to plot the $Sign[x]$ function and the series: $\displaystyle\sum_{n=-\infty}^\infty \dfrac{i(-1)^n - i}{n\pi}e^{inx} $ (which should be the answer to the integral in the code) on the same graph, but I cannot seem to get it to work. It displays no error, just an empty graph.

Tom
  • 73
  • 4
  • The expression If[n == 0, c1[0] = 0]; does not make sense to me and it is the reason that f5[x] contains unwanted Null signs. – halirutan Jan 06 '14 at 00:54
  • I remove it and get the division by 0 error. I try and use a different method to avoid the division by 0 error and displays an empty graph or just the Sign[x] graph. – Tom Jan 06 '14 at 01:01

2 Answers2

3

You only have to make sure that the coefficient c[n] in the Fourier series is defined for all n. This means that the If statement defining c[n] must return a value not only for n==0 as it does in your attempt, but also for other values of n. So all you have to do is change your code to

c1[n_] := 1/2/Pi Integrate[Sign[x] Exp[-I n x], {x, -Pi, Pi}];
c2[n_] = Simplify[c1[n], Assumptions -> Element[n, Integers]];
c[n_] := If[n == 0, c1[0] = 0, c2[n]];
f5[x_] = Sum[c[k] Exp[I k x], {k, -10, 10}];
Plot[{f5[x], Sign[x]}, {x, -Pi, Pi}]

and the plot comes out as expected:

sign Fourier

The way you use the If statement suggests that there may be another misunderstanding. What you need is for If to return two alternative results, not to execute the assignment c1[0] = 0 as you do it. That's simply unnecessary. So you may as well simplify it to

c[n_] := If[n == 0, 0, c2[n]];

Also, you could use

c2[n_] = FourierCoefficient[Sign[x], x, n]

instead of the explicit integration.

Jens
  • 97,245
  • 7
  • 213
  • 499
2

All the even terms vanish and using definition c2:

fun[x_, r_?OddQ] := 
  Sum[c2[k] Exp[I k x], {k, Join[Range[-r, -1, 2], Range[1, r, 2]]}];
fun[x_, r_] := fun[x, r - 1]

Animating using:

Table[Plot[{fun[x, j], Sign[x]}, {x, -Pi, Pi}, 
  PlotStyle -> {Blue, {Thick, Red}}], {j, 1, 21, 2}]

enter image description here

ubpdqn
  • 60,617
  • 3
  • 59
  • 148