方波生成主要是函数square的运用。可直接 help square看到相关的代码
t = linspace(-2*pi,2*pi,150);%150是从-2π到2π取150个点,可取其他数字,不写默认为100
x = square(2*t);%数字2可改变方波的周期。另外可square(2*t,75)改变方波占空比,使得方波正的部分的占空比为75%
plot(t/pi,x)
grid on

t的区间内取点个数越大方波越正,默认为100的时候有点斜。
t = linspace(-2*pi,2*pi,500);
x = square(4*t);%周期相关
subplot(2,3,1)
plot(t/pi,x)
subplot(2,3,2)
plot(abs(fft(x)))
grid on
周期的影响:
改变周期做对比可发现,系数变大,周期变小,谱线间隔变大,频谱变稀疏

脉宽的影响:
脉宽由信号的周期和占空比确定,其计算公式是脉宽W=T×P(T:周期,P:占空比)。固定周期,增加占空比到75如下图所示

可看出脉宽增加的时候频谱的谱线间隔变小,频谱变稠密。此时可以明显的看到频谱的幅度也减小,不知道事实如此还是我代码有问题,没检索到相关内容佐证
------------------------------------------------按照大佬的思路,加入了幅值矫正和调整0频位置
t = linspace(-2*pi,2*pi,500);
x = square(2*t);
N = length(x);
Fs = 50;%设定采样频率50hz
f = (0:N-1)*Fs/N;%将时间横坐标转换为频率横坐标:f = (0:N-1)*Fs/N
f2 = (N/2:N-1)*Fs/N-Fs/2;
subplot(2,2,1)
plot(t/pi,x)
subplot(2,2,2)
y = abs(fftshift(fft(x)));
y2=2*y(N/2:N-1)/N;%幅值修正得到真实幅值
plot(f2,y2)
x = square(2*t,75);
y = abs(fftshift(fft(x)));
y2=2*y(N/2:N-1)/N;
subplot(2,2,3)
plot(t/pi,x)
subplot(2,2,4)
plot(f2,y2)
grid on
% plot((0:7)*0.0001,[0 0.5 1 1 1 1 0.5 0])

参考资料:
square的MATLAB解释
MATLAB绘制频谱图代码
|