1
$\begingroup$

I am learning Fourier Series at university so I wanted to do something with Mathematica to calculate frequency spectrum and harmonics of whatever function I create. This is what I have until now after searching here and found this. This is my code:

Print["Generating function..."]
armonica = 10
frec = 200
period = 1/frec
time = 2;
tinc = 0.001;

(*f=Sin[x*(2 Pi frec)]*)
(*f=SquareWave[x];*)
f = Piecewise[{{1, 0 <= x <= period/2}, {-1, 
     period/2 <= x <= period}}];
(*f=SawtoothWave[x]*)

Print["Calculating Fourier..."]
(* Armonica *)
series = FourierSeries[f, x, 
  armonica]; (*FourierParameters->{1,2 Pi}*)
foo = Plot[series, {x, 0, 3*period}, PlotRange -> Full, 
  PlotLabel -> "Harmonic " <> ToString[armonica]]

(* Fundamental *)
bar = Plot[f, {x, 0, 3*period}, PlotLabel -> "Fundamental", 
  ExclusionsStyle -> Dashed, PlotStyle -> {Thickness[0.006], Red}]

(* Combinacion *)
Show[foo, bar, PlotLabel -> "Combination"]

(* Coeficientes para el espectro de frecuencia, siendo el numero en \
el eje x las n veces de la frecuencia fundamental *)
FourierCoefficient[f, x, n];
DiscretePlot[Abs[%], {n, 0, armonica}, PlotStyle -> Thickness[0.008]]

I am generating a 200Hz square wave and calculating Fourier Series up to 10th harmonic. But this are the plots I get:

enter image description here enter image description here

The first picture are the summatory of the harmonics from 0 to 10 or at least that's what I think FourierSeries[] returns. The second one is the square wave at 200Hz. The third picture is the combination on both and is showing really weird. Finally, the last one is the frequency spectrum which is wrong I think.

If I use frec = 1/(2 Pi) I get better result but frequency spectrum is still wrong:

enter image description here

I am testing with square but I want to be able to use other wave forms too but I can't even get one working at different frequencies.


Also tried using Fourier[] which calculates Fourier Series based on a list instead of function but it gives me all complex numbers instead of Fourier in the form of A[n]*Cos[n*x] + B[n]*Sin[n*x]

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.