# How do I plot a phase spectrum of rectangular pulse with Matlab?

As you can see, I made a code about rectangular pulse like this. And, I plotted complex-exponential-coefficient and Magnitude-Spectrum-of-Complex-Exponential-Form, Phase-Spectrum of-Complex-Exponential-Form, Fourier-Series-Complex-Exponential-Form as follows,

% Define rectangular pulse from t = 0 to t = 4
Ts = 0.001;
T = 4;
t = 0:Ts:T-Ts;
f(t < T/4) = 2;
f((t>=T/4)  & (t<3*T/4)) = 0;
f(t >= 3*T/4) = 2;
plot(t,f)

% Calculate Complex-Valued Coefficients
N=10;
c = zeros(1,2*N+1);
for n=-N:N
c(n + N + 1) = (Ts/T)*sum(f.*exp(-1i*2*pi*n*t/T));
end
stem(-N:N,real(c))
hold on
stem(-N:N,imag(c))
hold off
legend('real(c)','imag(c)')

% Magnitude Spectrum of Complex Exponential Form
stem(-N:N,abs(real(c)))

% Phase Spectrum of Complex Exponential Form
stem(-N:N,angle(c))

% Fourier Series Complex Exponential Form
tsyn=-2*T:Ts:2*T;
fs = zeros(size(tsyn));
for n=-N:N
fs = fs + (c(n+N+1)*exp(1i*2*pi*n*tsyn/T));
end
plot(tsyn,real(fs))


If you run the code directly into Matlab, you can see that everything work well except for Phase Spectrum of Complex Exponential Form.

Actually, my book say Phase Spectrum of Complex Exponential Form must become like this.

But, matlab give me a plot like this....

Could you tell me how to modify the code to draw Phase Spectrum of Complex Exponential Form accurately?

• The problem is likely to be this: the FFT returns some values that are almost zero, but not quite. -0.00000001 and -1000 have the same phase! The solution is to go over the FFT and force small values (let's say, those with absolute value less than 0.001) to be equal to zero.
– MBaz
May 9, 2022 at 18:23
• @MBaz Thank you for answering my question, sir. But, I don't understand. Could you give me more detailed clarifications? Thank you in advance, sir. May 9, 2022 at 23:49
• Theoretically, some of the FFT values should be zero. However, in practice these values are often very small, but not zero. That means that they have a random phase between -pi and pi, instead of zero. The solution is to go over the FFT values, identify those whose magnitude is very small, and replace them with zeros. You can find the magnitude with abs().
– MBaz
May 10, 2022 at 1:57