MATLAB Answers

Plotting magnitude spectra of square wave using FFT

141 views (last 30 days)
Yu-Wen Chang
Yu-Wen Chang on 29 Apr 2020
Answered: Samatha Aleti on 4 May 2020
I tried to plot two magnitude spectra for the two square waves (x1 and x2), however the plots are incorrect (I had completed the Fourier series analysis and also synthesized the FFT output to double check) and I'm not sure why because the sinusoid's magnitude spectrum was fine. Thanks in advance!
clc;
clear all;
close all;
% given
fs = 44100; % Sampling rate (44100 is CD quality)
Ts = 1/fs; % Step-size (resolution) of simulation
t = 0:Ts:12-Ts; % t = 2s
N = length(t); % length of time array
F = fs/N; % step-size (f)
f = (-fs/2):F:(fs/2)-F; % yay!
% task
x0 = cos(1000*pi*t); % a single-frequency tone
x1 = square((1000*pi*t)+(pi/2)); % square-wave 1
x2 = square((1000*pi*t)+(pi/4), 25); % square-wave 2
% FFT
x_0 = fftshift(fft(x0))/N;
x_1 = fftshift(fft(x1))/N;
x_2 = fftshift(fft(x2))/N;
figure();
% sinusoid
subplot(3, 2, 1)
plot(t, x0);
xlim([0 0.007])
title('Sinusoid - Time Domain');
xlabel('time (s)');
ylabel('x0(t)');
subplot(3, 2, 2)
plot(f, abs(x_0));
xlim([-550 550])
title('Sinusoid - Magnitude Spectra');
xlabel('f (Hz)');
ylabel('|X0(f)|');
% square-wave 1
subplot(3, 2, 3)
plot(t, x1);
xlim([0 0.007])
title('Square Wave 1 - Time Domain');
xlabel('time (s)');
ylabel('x1(t)');
subplot(3, 2, 4)
plot(f, abs(x_1))
xlim([-10000 10000])
title('Square Wave 1 - Magnitude Spectra');
xlabel('f (Hz)');
ylabel('|X1(f)|');
% square-wave 2
subplot(3, 2, 5)
plot(t, x2)
xlim([0 0.007])
title('Square Wave 2 - Time Domain');
xlabel('time (s)');
ylabel('x2(t)');
subplot(3, 2, 6)
plot(f, abs(x_2));
xlim([-10000 10000])
title('Square Wave 2 - Magnitude Spectra');
xlabel('f (Hz)');
ylabel('|X2(f)|');

  0 Comments

Sign in to comment.

Answers (1)

Samatha Aleti
Samatha Aleti on 4 May 2020
Hi,
As per my understanding, you have 2 square waves out of which one is actual square wave and the other is a Pulse wave (duty cycle not equal to 50). Generally, Fourier transform of square wave contains odd harmonics only and Fourier transform of pulse train contains even and odd harmonics. Accordingly, spectrum of your first square wave has odd harmonics only unlike that of your second wave which is a Pulse wave. For better visualization and understanding of the spectra try limiting the x-axis as follows:
plot(f, abs(x_1))
xlim([-1600 1600]) % Limit x-axis
title('Square Wave 1 - Magnitude Spectra');
xlabel('f (Hz)');
ylabel('|X1(f)|');

  0 Comments

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!