优化这段代码:function [Rp,As] = freqzn(num,den,wp,ws,Rp,As,ftype) switch ftype case 1 % 低通 [H, w] = freqz(num, den); H = abs(H); wp_index = find(w >= wp, 1); ws_index = find(w >= ws, 1); Rp = -20*log10(H(wp_index)); As = -20*log10(max(H(ws_index:end))); case 2 % 高通 [H, w] = freqz(num, den); H = abs(H); wp_index = find(w >= wp, 1); ws_index = find(w >= ws, 1); Rp = -20*log10(H(ws_index)); As = -20*log10(max(H(1:wp_index))); case 3 % 带通 [H, w] = freqz(num, den); H = abs(H); wp_index1 = find(w >= wp(1), 1); wp_index2 = find(w >= wp(2), 1); ws_index1 = find(w >= ws(1), 1); ws_index2 = find(w >= ws(2), 1); Rp = -20*log10(min(H(wp_index1:wp_index2))); As = -20*log10(max([max(H(1:ws_index1)), max(H(ws_index2:end))])); case 4 % 带阻 [H, w] = freqz(num, den); H = abs(H); wp_index1 = find(w >= wp(1), 1); wp_index2 = find(w >= wp(2), 1); ws_index1 = find(w >= ws(1), 1); ws_index2 = find(w >= ws(2), 1); Rp = -20*log10(max(H(wp_index1:wp_index2))); As = -20*log10(max([max(H(1:ws_index1)), max(H(ws_index2:end))])); otherwise error('Unsupported filter type!'); end %绘制滤波器的幅频特性 [H, w] = freqz(num, den); H = abs(H); figure; plot(w/pi, H, 'b', 'linewidth', 1.5); hold on; plot([0, wp]/pi, [1, 1], 'r--', 'linewidth', 1.5); plot([ws, 1]/pi, [0, 0], 'r--', 'linewidth', 1.5); if ftype == 3 || ftype == 4 plot([wp(1), wp(1)]/pi, [0, 1], 'r--', 'linewidth', 1.5); plot([wp(2), wp(2)]/pi, [0, 1], 'r--', 'linewidth', 1.5); end hold off; grid on; xlabel('归一化频率/\pi'); ylabel('幅值'); title('数字滤波器幅频特性'); end
时间: 2024-01-17 13:04:42 浏览: 60
asp 获取参数值与sql安全过滤参数函数代码
function [Rp,As] = freqzn(num,den,wp,ws,Rp,As,ftype)
[H, w] = freqz(num, den); % 计算频率响应
H = abs(H); % 取频率响应的幅值
wp_index = find(w >= wp, 1); % 找到截止频率对应的下标
ws_index = find(w >= ws, 1);
switch ftype
case 1 % 低通
Rp = -20*log10(H(wp_index)); % 计算通带衰减
As = -20*log10(max(H(ws_index:end))); % 计算阻带衰减
case 2 % 高通
Rp = -20*log10(H(ws_index));
As = -20*log10(max(H(1:wp_index)));
case 3 % 带通
wp_index2 = find(w >= wp(2), 1); % 找到第二个截止频率对应的下标
Rp = -20*log10(min(H(wp_index:wp_index2)));
As = -20*log10(max([max(H(1:ws_index)), max(H(wp_index2:end))])); % 注意阻带衰减的计算
case 4 % 带阻
wp_index2 = find(w >= wp(2), 1);
Rp = -20*log10(max(H(wp_index:wp_index2)));
As = -20*log10(max([max(H(1:ws_index)), max(H(wp_index2:end))]));
otherwise
error('Unsupported filter type!');
end
%绘制滤波器的幅频特性
figure;
plot(w/pi, H, 'b', 'linewidth', 1.5);
hold on;
plot([0, wp]/pi, [1, 1], 'r--', 'linewidth', 1.5);
plot([ws, 1]/pi, [0, 0], 'r--', 'linewidth', 1.5);
if ftype == 3 || ftype == 4
plot([wp(1), wp(1)]/pi, [0, 1], 'r--', 'linewidth', 1.5);
plot([wp(2), wp(2)]/pi, [0, 1], 'r--', 'linewidth', 1.5);
end
hold off;
grid on;
xlabel('归一化频率/\pi');
ylabel('幅值');
title('数字滤波器幅频特性');
end
阅读全文