% Digital lowpass butterworth
%
%  
% Analog specs
wpa=750; wsa=1500; Gp=-1; Gs=-20;
T = 1/900;
% Step 1: prewarp stop and pass frequencies
wp=(2/T)*tan(wpa*T*0.5);
ws=(2/T)*tan(wsa*T*0.5);
%
% Step 2: determine n
P1=-Gs/10; P2=-Gp/10; Wsp=ws/wp;
nc=log((10^P1 - 1)/(10^P2 - 1))/(2*log(Wsp));
nc
n= ceil(nc);
fprintf('Filter order is %i\n', n)
%
% Step 3 determine two wc's, one that exactly satisfies passband,
%  and the other satisfies stopband
Wcp = wp/(10^P2-1)^(1/(2*n));
Wcs = ws/(10^P1-1)^(1/(2*n));
%
% Step 4 Determine two transfer functions and discrete versions. also
[num1, den1] = butter(n, Wcp, 's');
[num2, den2] = butter(n, Wcs, 's');
[numd1, dend1] = bilinear(num1, den1, 1/T);
[numd2, dend2] = bilinear(num2, den2, 1/T);
%
%  Display final filter transfer functions (analog and digital)
%  Cutoff freq is the one that meets stopband spec.
disp('The final transfer function is')
format short e
disp('This satisfies passband');
num1, den1
numd1, dend1
disp('This satisfies stopband');
num2, den2
numd2, dend2
%
%
% Check magnitude at pass and stop freq
% must transform frequencies to discrete
disp('Checking magnitude at pass and stop frequencies:')
% transform discrete frequency to radians around unit circle for freqz()
zs=wsa*T; zp=wpa*T;
mag1=abs(freqz(numd1, dend1, [zp zs]));
mag1
mag2=abs(freqz(numd2, dend2, [zp zs]));
mag2
%
%
%  Do comparison between two digital filters
%
figure(1);
%
% z is the radian frequency to be passed to freqz(), and is the
% product of wd, the discrete frequency and T, the sample period.
% wd, the discrete frequency, is z/T
%
%
z=0:pi/200:pi/2;
wd=z/T;
H=freqz(numd1, dend1, z);
H1mag=abs(H);
H1phs=180/pi*unwrap(angle(H));
H=freqz(numd2, dend2, z);
H2mag=abs(H);
H2phs=180/pi*unwrap(angle(H));
subplot(211);
plot(wd, H1mag,  'c');
title('Butterworth design, red meets stop spec');
ylabel('Mag');
xlabel('Discrete freq (rad/sec)');
hold on;
plot(wd, H2mag, 'r');
grid;
hold off;
zoom on;
subplot(212);
plot(wd, H1phs,  'c');
ylabel('Phase (deg)');
hold on;
plot(wd, H2phs, 'r');
grid;
hold off;
%
%  Now repeat using buttord and butter for discrete
%  To use these functions, remember that the radian sampling
%  frequency is 2. Must normalize all pass and stop freqs by
%  multiplying by T/pi
Wpa=wpa*(T/pi); Wsa=wsa*(T/pi);
[n, Wn] = buttord( Wpa, Wsa, -Gp, -Gs);
[b,a]=butter(n,Wn);
%
% Display this result
disp('The transfer function using buttord and butter is')
b,a