用matlab作图演示方波信号的傅里叶级数
时间: 2023-09-10 22:11:23 浏览: 196
要演示方波信号的傅里叶级数,可以按照以下步骤进行:
1. 定义方波函数:
```
function y = square_wave(t, T)
y = sign(sin(2*pi*t/T));
end
```
其中,`t` 是时间变量,`T` 是方波周期。
2. 计算傅里叶级数:
```
function [a, b] = fourier_coefficients(T, N)
syms t;
f = square_wave(t, T);
a0 = 2/T * int(f, t, -T/2, T/2);
a = zeros(1, N);
b = zeros(1, N);
for n = 1:N
a(n) = 2/T * int(f*cos(2*pi*n*t/T), t, -T/2, T/2);
b(n) = 2/T * int(f*sin(2*pi*n*t/T), t, -T/2, T/2);
end
end
```
其中,`T` 是方波周期,`N` 是傅里叶级数的项数。使用符号计算工具箱中的 `int` 函数计算积分。
3. 绘制傅里叶级数的幅度谱:
```
T = 2*pi;
N = 10;
[a, b] = fourier_coefficients(T, N);
f = [a(1)/2, zeros(1, N)];
for n = 1:N
f = f + [a(n+1)*cos(n*t) + b(n)*sin(n*t), zeros(1, N-n)];
end
f = f * 2/T;
f = fftshift(f);
f_mag = abs(f);
f_mag = f_mag(1:N+1);
f_mag(2:end-1) = 2*f_mag(2:end-1);
stem(0:N, f_mag);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
```
其中,`fftshift` 函数将频率分量移到中心位置,`abs` 函数计算幅度,`stem` 函数绘制幅度谱。
4. 绘制傅里叶级数的波形:
```
t = linspace(-T/2, T/2, 1000);
f = [a(1)/2, zeros(1, N)];
for n = 1:N
f = f + [a(n+1)*cos(n*t) + b(n)*sin(n*t), zeros(1, N-n)];
end
plot(t, f);
xlabel('Time (s)');
ylabel('Amplitude');
```
其中,`linspace` 函数生成时间变量,`plot` 函数绘制波形。
完整代码如下:
```
function y = square_wave(t, T)
y = sign(sin(2*pi*t/T));
end
function [a, b] = fourier_coefficients(T, N)
syms t;
f = square_wave(t, T);
a0 = 2/T * int(f, t, -T/2, T/2);
a = zeros(1, N);
b = zeros(1, N);
for n = 1:N
a(n) = 2/T * int(f*cos(2*pi*n*t/T), t, -T/2, T/2);
b(n) = 2/T * int(f*sin(2*pi*n*t/T), t, -T/2, T/2);
end
end
T = 2*pi;
N = 10;
[a, b] = fourier_coefficients(T, N);
t = linspace(-T/2, T/2, 1000);
f = [a(1)/2, zeros(1, N)];
for n = 1:N
f = f + [a(n+1)*cos(n*t) + b(n)*sin(n*t), zeros(1, N-n)];
end
plot(t, f);
xlabel('Time (s)');
ylabel('Amplitude');
f = [a(1)/2, zeros(1, N)];
for n = 1:N
f = f + [a(n+1)*cos(n*t) + b(n)*sin(n*t), zeros(1, N-n)];
end
f = f * 2/T;
f = fftshift(f);
f_mag = abs(f);
f_mag = f_mag(1:N+1);
f_mag(2:end-1) = 2*f_mag(2:end-1);
stem(0:N, f_mag);
xlabel('Frequency (Hz)');
ylabel('Magnitude');
```
阅读全文