1
$\begingroup$

I was testing fft on mathematica using simple functions and ran into problems.

I first tried a simple cos function with the following code:

f1[x_] := Cos[2 \[Pi]*x];
Sample = Table[f1[x], {x, 0, 2, 1/100}];
fft = Abs[Fourier[Sample]];
p1 = ListLinePlot[fft, PlotRange -> Full, DataRange -> {-1, 1}]

which does give me the graph of two delta functions. Here is my first question: Why do I have to manually adjust DataRange in order for the peak to be at the correct position namely -1 and 1?enter image description here

I then tried the addition of two cos functions and this is where it started to give me problems

f2[x_] := Cos[2 \[Pi]*x] + Cos[\[Pi]*x];
Sample1 = Table[f2[x], {x, 0, 2, 1/100}];
fft1 = Abs[Fourier[Sample1]];
p2 = ListLinePlot[fft1, PlotRange -> Full]

Supposedly it should give me four peaks at -2,-1,1,2 but the graph is not showing so. Where might it go wrong in this case? And what datarange shall i use? enter image description here

$\endgroup$
3
  • 1
    $\begingroup$ I have put some notes on Fourier here in answer to another question. You may find them helpful. Let me know if you need more. $\endgroup$
    – Hugh
    Jan 28, 2022 at 13:41
  • $\begingroup$ Hugh I have successfully applied your code to simple functions, however it fails for some more complex function, for example a single impulse. I did read through your points but am unsure if i understand them completely, could you have a look at this question pls?mathematica.stackexchange.com/questions/263082/… $\endgroup$
    – Rescy_
    Feb 4, 2022 at 0:25
  • $\begingroup$ Hugh pls ignore my above question, I just realised I made a stupid mistake. Thanks for your notes, tremendous help! $\endgroup$
    – Rescy_
    Feb 4, 2022 at 0:43

1 Answer 1

3
$\begingroup$

To see it better, you'd need to set the frequency scale yourself. This is how I would do it. Assume some sampling frequency

fs = 1000;  (*1000 hz. Assumed sampling frequency*)
sample = Table[Cos[2*Pi*100*t], {t, 0, 1 - 1/fs, 1/fs}];
fft = Fourier[sample];
fft = fft[[1 ;; Length[sample]/2 + 1]];
df = fs/Length[sample];
frequencyAxis = Range[0, fs/2, df];
data = Transpose[{frequencyAxis , Abs[fft]}];
ListLinePlot[data, PlotRange -> All]

Mathematica graphics

The above shows f at 100 HZ as expected because we used Cos[2*Pi*100*t] as the signal. Now lets add another one at say 200 hz. Just change the line

sample = Table[Cos[2*Pi*100*t] + Cos[2*Pi*200*t], {t, 0, 1 - 1/fs, 1/fs}];

Now you'll get

Mathematica graphics

And so on. The units on the x-axis are in Hz. It goes up to half the sampling frequency (Due to Nyquist limit).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.