# MATLAB frequency magnitude spectrum

I am using the following code to generate four sine waves using a sampling rate of 8000.

   Fs = 8000;                       % samples per second
Ts = 1/Fs;                       % seconds per sample
t = 0: Ts: 3;                    % Start signals at 0sec and stop after 3sec

% Sine wave x1[n]:
Fc = 320;
x1 = sin(2*pi*Fc*t);

% Sine wave x2[n]:
Fc = 760;
x2 = sin(2*pi*Fc*t);

% Sine wave x3[n]:
Fc = 1280;
x3 = sin(2*pi*Fc*t);

% Sine wave x4[n]:
Fc = 2000;
x4 = sin(2*pi*Fc*t);

x_comp = x1 + x2 + x3 + x4;


Now I need to plot the frequency magnitude spectrum of the composite signal (x_comp) in dB. How can I achieve this please?

I used the code below but the plot is not making sense.

   x_comp = x1 + x2 + x3 + x4;

x_comp_mag = abs(fft(x_comp));

• What do you get? What are you expecting? What doesn't make sense? – ThP May 14 '15 at 18:34

You might be seeing the FFT coefficients shifted towards the extremes with your code. Try using fftshift() as shown below,

N=2^(nextpow2(length(x_comp)));

x_comp_mag = abs(fftshift(fft(x_comp,N)));

f = linspace(-Fs/2,Fs/2,N); % for double sided spectrum

plot(f,x_comp_mag);


try changing the number of samples from t = 0: Ts: 3; to t = 0: Ts: 3-Ts;

you then have a frequency resolution of 1/3 (8000/24000), which is divisible by all the chosen frequencies in your sinusoidal signal. Also does it need to be in dB ? (is abs(fft(x)) enough). some values after fft will be very small (virtually zero), but will ruin your plot if plotting log. you can round to remove the very small values, then log plot.

L=length(x_comp_mag); 