## Plotting FFT Spectrum using Square Wave

Oscar Rodrigues

### Oscar Rodrigues (view profile)

さんによって質問されました 2019 年 7 月 7 日

### Star Strider (view profile)

さんによって コメントされました 2019 年 7 月 7 日
Star Strider

### Star Strider (view profile)

さんの 回答が採用されました
I am trying to plot an FFT spectrum but the graph stops at half of the window I'm looking to acquire.
This is the code that I have used:
% clc;
% clear all;
t = 0:(1/1e6):(10/1e5);
x = 2.5*square(t*2*pi*1e5,50);
N = length(x);
fs = 10e5;
figure(1)
plot(t,x)
X = abs(fft(x));
bins = (0:(N-1));
f = (bins*fs)/N;
intN = ceil(N/2);
figure(2)
plot(f(1:intN),X(1:intN))
xlabel('Frequency (Hz)')
ylabel('Amplitude');
title('FFT Spectrum of Square Wave with 100kHz Frequency and 50% Duty Cycle');
xlim([0 1e6])
set(gca,'YTickLabel',[]);

#### 0 件のコメント

サインイン to comment.

## 1 件の回答

### Star Strider (view profile)

2019 年 7 月 7 日
採用された回答

Two problems:
First: ‘fs’ is the inverse of the sampling interval, or 1E+6.
Second, your code is correct although your plot is not. You can only plot to the Nyquist frequency (½ the sampling frequency), so your xlim call should be:
xlim([0 1e6/2])
Also, you need to normalise the fft result by dividing it by the length of your data vector:
X = abs(fft(x))/N;
and then multiply it by 2 to get the approximately correct amplitude in the plot.
Those changes result in a correct fft plot.

Oscar Rodrigues

### Oscar Rodrigues (view profile)

2019 年 7 月 7 日
You are the greatest human to ever exist. Thank you so much for your help. I wish you a wonderful life filled with blessings.
Star Strider

### Star Strider (view profile)

2019 年 7 月 7 日
As always, my pleasure!
I very much appreciate your sentiments!

サインイン to comment.

Translated by