Here is the code I use to plot a function in frequency domain in Matlab:

    dt = 1/10000; % sampling rate
    et = 0.1; % end of the interval
    t = 0:dt:et; % sampling range
    y = 2+sin(2.*pi.*50.*t)+18.*sin(2.*pi.*90.*t)+6.*sin(2.*pi.*180.*t); %     sample the signal
    subplot(2,1,1); % first of two plots
    plot(t,y); grid on % plot with grid
    xlabel('Time (s)'); % time expressed in seconds
    ylabel('Amplitude'); % amplitude as function of time
    Y = fft(y); % compute Fourier transform
    n = size(y,2)/2; % 2nd half are complex conjugates
    amp_spec = abs(Y)/n; % absolute value and normalize
    subplot(2,1,2); % second of two plots
    freq = (0:100)/(2*n*dt); % abscissa viewing window
    stem(freq,amp_spec(1:101)); grid on % plot amplitude spectrum
    xlabel('Frequency (Hz)'); % 1 Herz = number of cycles/second
    ylabel('Amplitude'); % amplitude as function of frequency

The problem is, when I zoom in my graph I don't see peaks exactly on 50Hz, 90Hz and 180Hz.

What did I do wrong in my code?


Discrete Fourier transform doesn't actually decompose a signal into sum of sinusoids it was composed from. DFT projects signal onto a specific set of discrete sinusoids known as Fourier basis. Sinusoids used to compose the signal may or may not coincide with the DFT basis. If they are not, they are being decomposed into a number of DFT basis elements.

There's another way of how to look at it. DFT deals with periodic functions. If you plot 3-4 periods of your signal interval, you'll see it doesn't look like a sum of pure sinusoids and has discontinuities - if sinusoids it was composed from don't coincide with a Fourier basis.

  • 1
    $\begingroup$ I think you mean specifically DFT X[k] of x[n]. Because otherwise DTFT $X(e^{j\omega})$ would compute whatever frequency there is in the discrete signal in exactness, due to its continuous frequency variable. $\endgroup$ – Fat32 Apr 8 '15 at 1:01
  • 1
    $\begingroup$ Yes, indeed. Corrected. $\endgroup$ – Yuri Nenakhov Apr 8 '15 at 1:58

Well it does in Octave, (obtained by pasting your code, unmodified into a script file):

enter image description here


Your Answer

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

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