MATLAB m-files listings – by Chapter (Digital Signal Processing – A Practical Approach, E C Ifeachor and B W Jervis, Pearson/Prentice Hall, 2002; ISBN 817808 609 3) Chapter 1 Introduction N/A Chapter 2 Analog I/O interface for real-time DSP systems N/A Chapter 3 Discrete transform function DFTD clear all; % Program to compute DFT coefficients directly % (Program 3c.1, p170; program name: dftd.m) % direction = -1; %1 - forward DFT, -1 - inverse DFT in = fopen('datain.dat','r'); x = fscanf(in,'%g %g',[2,inf]); fclose(in); x = x(1,:)+x(2,:)*i; % form complex numbers if direction==1 y = x*dftmtx(length(x)) ; %compute DFT else y = x*conj(dftmtx(length(x)))/length(x); end %compute IDFT % Save/Print the results out=fopen('dataout.dat','w'); fprintf(out,'%g %g\n',[real(y); imag(y)]); fclose(out); subplot(2,1,1),plot(1:length(x),x); title('Input Signal'); subplot(2,1,2),plot(1:length(y),y); title('Output Signal'); ============================================================ function DFTF % Program to compute DFT coefficients using DIT FFT % (Program 3c.2, p171; program name: dftf.m) % clear all; direction = -1; %1 - forward DFT, -1 - inverse DFT in = fopen('dataout.dat','r'); x = fscanf(in,'%g %g',[2,inf]); fclose(in); x = x(1,:)+x(2,:)*i; % form complex numbers if direction==1 1 y=fft(x,length(x)) else y=ifft(x,length(x)) end % compute FFT % compute IFFT % Save/Print the results out=fopen('dataout.dat','w'); fprintf(out,'%g %g\n',[real(y); imag(y)]); fclose(out); subplot(2,1,1),plot(1:length(x),x); title('Input Signal'); subplot(2,1,2),plot(1:length(y),y); title('Output Signal'); ======================================================= % % 4-point DFT (sdft1.m) % A simple m-file script illustrating direct 4-point DFT computation. % input data: x(0)=1, x(1)=5, x(2)=4, x(3)=2. % N=4;j=sqrt(-1); x0=1; x1=5; x2=4; x3=2; X0=x0+x1+x2+x3; X11=x1*exp(-j*2*pi/N); X12=x2*exp(-j*2*pi*2/N); X13=x3*exp(-j*2*pi*3/N); X1a=x0+X11+X12+X13; X1=x0+x1*exp(-j*2*pi/N)+x2*exp(-j*2*pi*2/N)+x3*exp(-j*2*pi*3/N); X2=x0+x1*exp(-j*2*pi*2/N)+x2*exp(-j*2*pi*2*2/N)+x3*exp(-j*2*pi*2*3/N); X3=x0+x1*exp(-j*2*pi*3/N)+x2*exp(-j*2*pi*3*2/N)+x3*exp(-j*2*pi*3*3/N); X11 X12 X13 X1a X0 X1 X2 X3 ======================================================== % % 4-point DFT (sdft2.m) % A simple m-file script illustrating direct 4-point DFT computation. % input data: x(0)=1, x(1)=0.5, x(2)=0, x(3)=0. % N=4;j=sqrt(-1); x0=1; x1=0.5; x2=0; x3=0; X0=x0+x1+x2+x3; X11=x1*exp(-j*2*pi/N); X12=x2*exp(-j*2*pi*2/N); X13=x3*exp(-j*2*pi*3/N); X1a=x0+X11+X12+X13; X1=x0+x1*exp(-j*2*pi/N)+x2*exp(-j*2*pi*2/N)+x3*exp(-j*2*pi*3/N); X2=x0+x1*exp(-j*2*pi*2/N)+x2*exp(-j*2*pi*2*2/N)+x3*exp(-j*2*pi*2*3/N); X3=x0+x1*exp(-j*2*pi*3/N)+x2*exp(-j*2*pi*3*2/N)+x3*exp(-j*2*pi*3*3/N); X11 X12 X13 2 X1a X0 X1 X2 X3 ================================================================ % % 4-point FFT (sfft2.m) % A simple m-file script illustrating direct 4-point FFT decimation-intime % computation. % Input data: x(0)=1, x(1)=0.5, x(2)=0, x(3)=0. % N=4;j=sqrt(-1); x0=1; x1=0.5; x2=0; x3=0; W0=1; W1=-j; a11=x0+W0*x2;b11=x0-W0*x2; a12=x1+W0*x3; b12=x1-W0*x3; X0=a11+W0*a12; X2=a11-W0*a12; X1=b11+W1*b12; X3=b11-W1*b12; a11 b11 a12 b12 X0 X1 X2 X3 ======================================================== % % % 8-point DFT (sfft8.m) % A simple m-file script illustrating direct 8-point DFT computation. % Input data: x(0)=4, x(1)=2, x(2)=1, x(3)=4, x(4)=6, x(5)=3, x(6)=5, x(7)=2. % j=sqrt(-1); x0=4; x1=2; x2=1; x3=4; x4=6; x5=3; x6=5; x7=2; W0=1; W1=sqrt(2)/2 - j*sqrt(2)/2; W2=-j; W3=-sqrt(2)/2 - j*sqrt(2)/2; % stage 1 A11=x0+W0*x4;B11=x0-W0*x4; A12=x2+W0*x6;B12=x2-W0*x6; A13=x1+W0*x5;B13=x1-W0*x5; A14=x3+W0*x7;B14=x3-W0*x7; % stage 2 A21=A11+W0*A12;B21=A11-W0*A12; A22=B11+W2*B12;B22=B11-W2*B12; A23=A13+W0*A14;B23=A13-W0*A14; A24=B13+W2*B14;B24=B13-W2*B14; % stage 3 X0=A21+W0*A23;X4=A21-W0*A23; X1=A22+W1*A24;X5=A22-W1*A24; X2=B21+W2*B23;X6=B21-W2*B23; 3 X3=B22+W3*B24;X7=B22-W3*B24; A11 B11 A12 B12 A13 B13 A14 B14 A21 A22 B21 B22 A23 A24 B23 B24 X0 X1 X2 X3 X4 X5 X6 X7 ================================================================= % % 4-point inverse FFT (sifft4.m) % A simple m-file script illustrating direct 4-point inverse DFT computation. % Input data: x(0)=1.5 +0j, x(1)=1-0.5j, x(2)=0.5+0j, x(3)=1+0.5j % N=4;j=sqrt(-1); x0=1.5 + 0j; x1=1 - 0.5j; x2=0.5 + 0j; x3=1+0.5j; W0=1; W1=j; a11=x0+W0*x2;b11=x0-W0*x2; a12=x1+W0*x3; b12=x1-W0*x3; X0=(a11+W0*a12)/N; X2=(a11-W0*a12)/N; X1=(b11+W1*b12)/N; X3=(b11-W1*b12)/N; a11 b11 a12 b12 X0 X1 X2 X3 x0 x1 x2 x3 ====================================================== 4 Chapter 4 z-transform and its applications in signal processing. % % m-file to compute the first 5 values of the % inverse z-transform using the power series method % (Program 4D.1, p235; program name: prog4d1.m) % n = 5; % number of power series points N1 = [1 -1.122346 1]; D1 = [1 -1.433509 0.85811]; N2 = [1 1.474597 1]; D2 = [1 -1.293601 0.556929]; N3 = [1 1 0]; D3 = [1 -0.612159 0]; B = [N1; N2; N3]; A = [D1; D2; D3]; [b,a] = sos2tf([B A]); b = [b zeros(1,n-1)]; [h,r] = deconv(b,a); %perform long division disp(h); ============================================================ % % m-file for finding the partial fraction expansion of a z-transform % (Program 4D.2, p237; program name: prog4d2.m) % N1=[1 -1.122346 1]; N2=[1 -0.437833 1]; N3=[1 1 0]; D1=[1 -1.433509 0.85811]; D2=[1 -1.293601 0.556929]; D3=[1 -0.612159 0]; sos=[N1 D1; N2 D2; N3 D3]; [b, a] = sos2tf(sos); [r, p, k]=residue(b, a) ================================================ % % A script illustrating cascade to parallel realization % (Program 4B.3, p237; program name: prog4d3.m) % nstage=2; N1 = [1 0.481199 1]; N2 = [1 1.474597 1]; D1 = [1 0.052921 0.83173]; D2 = [1 -0.304609 0.238865]; sos = [N1 D1; N2 N2]; [b, a] = sos2tf(sos); [c, p, k] = residue(b, a); m = length(b); b0 = b(m)/a(m); j=1; for i=1:nstage bk(j)=c(j)+c(j+1); bk(j+1)=-(c(j)*p(j+1)+c(j+1)*p(j)); ak(j)=-(p(j)+p(j+1)); ak(j+1)=p(j)*p(j+1); j=j+2; end b0 5 ak bk c p k =============================================================== % % A simple script illustrating basics of cascade to parallel % conversion for a 4th order filter (cprealization.m) % b=[1, -2, 1, 0, 0]; a=[1, -0.41421, 0.08579, 0.292895, 0.5]; [c, p, k] = residuez(b, a); c p k b0 = b(3)/a(5) b01=c(1)+c(2) b11=-(c(1)*p(2)+c(2)*p(1)) a11=-(p(1)+p(2)) a12=p(1)*p(2) b02=c(3)+c(4) b12=-(c(3)*p(4)+c(4)*p(3)) a12=-(p(3)+p(4)) a22=p(3)*p(4) ================================================================= % % A simple script illustrating inverse z transform by power series codes % File-name: pseries.m b1 = [1 0.481199 1]; b2 = [1 1.474597 1]; a1 = [1 0.052921 0.83173]; a2 = [1 -0.304609 0.238865]; sos = [b1 a1; b2 a2]; [b, a] = sos2tf(sos); m = length(b); r = b; for n=1:m [h(n), r] = deconv(r, a); h r r = [r(2:m) 0]; end ================================================= function IZT %program IZT (izt.m) is for: %(1) computing the inverse z-transform via the power series or partial % fraction expansion method %(2) converting a transfer function, H(z), in cascade form to an equivalent % transfer function in parallel, via partial fraction expansion. The % basic building block is the second order biquad 6 IZT_Mode = 1; %1 - use power series to perform the IZT %2 - use partial fraction/residue to perform the IZT %3 - cascade to parallel conversion n = 5; % number of power series points b1 = [1 0.481199 1]; a1 = [1 0.052921 0.83173]; b2 = [1 1.474597 1]; a2 = [1 -0.304609 0.238865]; B = [b1; b2]; A = [a1; a2]; [b,a] = sos2tf([B A]); if IZT_Mode==1 %compute the IZT by power series b = [b zeros(1,n-1)]; [h,r] = deconv(b,a); %perform long division disp('The result of the inverse Z-transform by power series is:'); disp(h); else [res,poles,rem] = residuez(b,a); disp('The poles of the transform function are:'); disp(poles'); disp('The partial fraction coefficients are:'); disp(res'); if IZT_Mode==3 i = 1 ; for j=1:size(B,1) [b,a] = residuez(res(i:i+1),poles(i:i+1), 0); fprintf('Numerator and Denominator for stage%d:\n',j);disp(b);disp(a); i = i + 2; end end end ========================================================= % % m-file to illustrate the computation of frequency response % of an IIR filter using FFT (freqrespex1.m). % Fs=500; % sampling frequency b1=[1 -1.6180 1]; b2=[]; % numerator/denominator filter coefficients a1=[1 -1.5161 0.878]; a2=[]; B=[b1; b2]; A=[a1; a2]; [b,a]=sos2tf([B A]); n=256; % number of frequency points dx=0; if dx freqz(b,a,n,Fs); % Frequency response evaluation by FFT else f=(0:n-1)*(Fs/2)/n; freqz(b,a,f,Fs); % frequency response by direct evaluation. end ========================================================= 7 Chapter 5 Correlation and Convolution function Correlation %Program to compute normalised/unnormalised auto- or crosscorrelation crosscorrelation = 1 ; normalized = 0 ; if crosscorrelation == 0 x = [1 3 2 -1 -2]; %for autocorrelation if normalized==0 R11 = xcorr(x,'biased') % unnormalized autocorrelation else R11 = xcorr(x,'coeff') % normalized autocorrelation end else x1 = [4 2 -1 3 -2 -6 -5 4 5]; %for crosscorrelation x2 = [-4 1 3 7 4 -2 -8 -2 1]; %for crosscorrelation if normalized==0 R12 = xcorr(x1,x2,'biased') % unnormalized crosscorrelation else R12 = xcorr(x1,x2,'coeff') % normalized crosscorrelation end end if crosscorrelation subplot(3,1,1), plot(1:length(x1),x1), ylabel('x1(n)'); subplot(3,1,2), plot(1:length(x2),x2), ylabel('x2(n)'); subplot(3,1,3), plot(1:length(R12),R12), ylabel('R12'); else subplot(2,1,1), plot(1:length(x),x), ylabel('x(n)'); subplot(2,1,2), plot(1:length(R11),R11), ylabel('R11'); end Chapter 6 A framework for digital filter design N/A 8 Chapter 7 Finite impulse response (FIR) filter design % % prog7b1.m, p442 % fc=0.53; N= 10; hd=fir1(N-1,fc,boxcar(N)); coeffs wn=hamming(N); hn=fir1(N-1,fc,wn); Program name % cutoff frequency (normalized to Fs/2) % Filter length (number of taps) % Calculate truncated ideal impulse response % Calculate Hamming window coefficients % Obtain windowed coefficients =============================== % % prog7b2.m, p444 % FS=1000; % FN=FS/2; % N=73; % beta=5.65; % fc1=125/FN; % fc2=275/FN; FC=[fc1 fc2]; % hn=fir1(N-1, FC, kaiser(N, beta)); [H,f]=freqz(hn, 1, 512, FS); % mag=20*log10(abs(H)); plot(f, mag), grid on xlabel('Frequency (Hz)') ylabel('Magnitude Response (dB)') File name Sampling frequency Nyquist frequency Filter length Kaiser ripple parameter Normalized cut off frequencies Band edge frequencies %Obtain windowed filter coefficients Compute frequency response =============================== % % Program name - prog7b3.m, p446 % m-file for calculating optimal FIR filter coefficients and % plotting frequency response % Fs=10000; % Sampling frequency N=41; % Filter length WT=[10 3 10]; % Weights of the deviations in the bands Hd=[0 0 1 1 0 0]; % Desired magnitude response in the bands F=[0 0.1 0.2 0.3 0.4 1]; % Band edge frequencies b = remez(N-1, F, Hd, WT); % Compute the filter coefficients [H, f] = freqz(b, 1, 512, Fs);% Compute the frequency response mag = 20*log10(abs(H)); % of filter and plot it plot(f, mag), grid on xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') ================================= 9 % % Program name - prog7b4a.m, p449. % m-file for calculating the optimal FIR filter coefficients % and plotting frequency response for Example 7B.4 % Fs=50000; % Sampling frequency % Filter length Ap=1; % Pass band ripple in dB As=45; % Stop band attenuation in dB M=[0 1 0]; % Desired magnitude response F=[10000, 12000, 16000, 18000] ; % Band edge frequencies dp=(10^(Ap/20)-1)/(10^(Ap/20)+1); % Pass and stop band ripples ds=10^(-As/20); dev=[ds dp ds]; [N1, F0, M0, W] = remezord(F, M, dev, Fs);% Determine filter order [b delta] = remez(N1, F0, M0, W);% Compute the filter coefficients [H, f] = freqz(b, 1, 1024, Fs); % Compute the frequency response mag = 20*log10(abs(H)); % of filter and plot it plot(f, mag), grid on xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') =========================================== % % Program name - prog7b4b.m, p450. % An alternative m-file for calculating the optimal FIR filter % coefficients and plotting frequency response for Example 7B.4 % N=44; Fs=50000; % Sampling frequency % Filter length Ap=1; % Pass band ripple in dB As=45; % Stop band attenuation in dB M=[0 0 1 1 0 0]; % Desired magnitude response F=[0, 0.4, 0.48, 0.64, 0.72 1] ; % Band edge frequencies dp=(10^(Ap/20)-1)/(10^(Ap/20)+1); ds=10^(-As/20); W=[dp/ds, 1, dp/ds]; dev=[ds ds dp dp ds ds ]; [b delta] = remez(N-1, F, M, W);% Compute the filter coefficients [H, f] = freqz(b, 1, 1024, Fs); % Compute the frequency response mag = 20*log10(abs(H)); % of filter and plot it plot(f, mag), grid on xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') ============================================== 10 % % Program name - prog7b5.m, p451. % m-file for computing the coefficients of an FIR frequency sampling % filter % Fs=2000; % Sampling frequency N=15; % Filter length fd=[0 1/7 2/7 3/7 4/7 5/7 6/7 1]; % Frequency sampling points Hd=[1 1 1 1 0.5571 0.0841 0 0]; % Frequency samples hn=fir2(N-1, fd, Hd); % Compute the impulse response coeffs. [H, f] = freqz(hn, 1, 512, Fs); % Plot the magnitude frequency response plot(f, abs(H)), grid on xlabel('Frequency (Hz)') ylabel('Magnitude ') ================================================== % % Program name - prog7b6.m, p453. % m-file for calculating the coefficients of an FIR filter % with arbitrary magnitude response % Fs=2000; N=110; fd=[0 0.15 0.25 0.45 0.5 0.75 0.85 1]; % Frequency sampling points Hd=[1 1 0.3 0.3 0.1 0.1 0 0]; % Frequency samples hn=fir2(N-1, fd, Hd); % Compute the impulse response [H, f] = freqz(hn, 1, 512, Fs); % Plot the magnitude response plot(f, abs(H)), grid on xlabel('Frequency (Hz)') ylabel('Magnitude ') ================================================= function Filt_win %This program uses the window method to design FIR filters. %The following windows are supported: Rectangular, Hamming, Hanning, Blackman, %and Kaiser. % ftype: [] for lowpass filter % 'high' for highpass filter % [] for bandpass filter % 'stop' for bandstop filter % wtype: 1 for Rectangular window % 2 for Hamming window % 3 for Hanning window % 4 for Blackman window % 5 for Kaiser window clear all; wtype = 2 ; Fs = 8000; %sampling frequency 11 n = 52; %the order of the filter Wn = 0.4375; %normalised cutoff frequency (2*Fstop/Fs) beta = 0; %Kaiser window beta parameter ftype=[]; window=[]; %Hamming window will be used if variable window is empty if wtype==1 window=ones(1,n+1); %Rectangular window elseif wtype==3 window=hanning(n+1); %Hanning window elseif wtype==4 window=blackman(n+1); %Blackman window elseif wtype==5 window=kaiser(n+1,beta);%Kaiser window end b = fir1(n,Wn,ftype,window) % Plot the frequency response freqz(b,1,1024,Fs); ========================================= function Firfilt %FIR filtering program - program performs FIR filtering using coefficients %and data in user specified files. clear all; data_file = fopen('filterin.dat','r'); %read the data to be filtered from file x = fscanf(data_file,'%f'); coef_file = fopen('filtcoef.dat','r'); %read the filter coefficients from file [b,n]=fscanf(coef_file,'%f',inf); fclose('all'); y=filter(b,1,x); %filtering %Plot the results bx=fft(x,512); by=fft(y,512); [h, w]=freqz(b,1,1024); subplot(3,1,1),plot(1000*(0:255)/512,abs(bx(1:256))), ylabel('X(f)'); subplot(3,1,2),plot(w/pi,abs(h)), ylabel('H(f)'); subplot(3,1,3),plot(1000*(0:255)/512,abs(by(1:256))), ylabel('Y(f)'); =================================================================== function Fresamp %Design arbitrary FIR filter by frequency sampling method n=15; m = [1 1 1 1 0.5571 0.0841 0 0]; f = [0 1/7 2/7 3/7 4/7 5/7 6/7 1]; window = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]; % n+1 elements long b = fir2(n,f,m,window); % get filter coefficients 12 %Output the results disp('The coefficients are:'); disp(b); [h,w] = freqz(b,1,128); plot(f,m,w/pi,abs(h)); title('Desired and Actual Frequency Responses'); ================================================== % % Program name - REMEZ1.m % Fs=15000; N=41; WT=[10 3 10]; bands Hd=[0 0 1 1 0 0]; the bands F=[0 0.06 0.12 0.14667 0.206667 1]; [b, delta] = remez(N-1, F, Hd, WT); [H, f] = freqz(b, 1, 512, Fs); mag = 20*log10(abs(H)); plot(f, mag) xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') % % % sampling frequency Filter length Weights of the deviations in the % Desired magnitude response in % Band edge frequencies % Compute the filter coefficients % Compute the frequency response % of filter and plot it ================================================ % % Program name – REMEZex2.m % N=44 Fs=50000; % Ap=1; As=45; M=[0 0 1 1 0 0]; F=[0, 0.4, 0.48, 0.64, 0.72 1] ; dp=(10^(Ap/20)-1)/(10^(Ap/20)+1); ds=10^(-As/20); W=[dp/ds, 1, dp/ds]; dev=[ds ds dp dp ds ds ]; [b delta] = remez(N-1, F, M, W);% [H, f] = freqz(b, 1, 1024, Fs); mag = 20*log10(abs(H)); plot(f, mag), grid on xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') % Sampling frequency Filter length % Pass band ripple in dB % Stop band attenuation in dB % Desired magnitude response % Band edge frequencies Compute the filter coefficients % Compute the frequency response % of filter and plot it ================================================ 13 Chapter 8 Design of infinite impulse response (IIR) digital filters. % % Program 8.1, p511. m-file for the analog filter design % (Example 8.19) % program name: prog81.m % FN=1000/2; fc=300; % cut offf frequency N=5; % filter order [z, p, k]=buttap(N); % create an analog filter w=linspace(0, FN/fc, 1000); % plot the response of filter h=freqs(k*poly(z), poly(p), w); f=fc*w; plot(f, 20*log10(abs(h))), grid ylabel('Magnitude (dB)') xlabel('Frequency (Hz)') ============================================= % % Program 8.2, p511. m-file for the % impulse invariant filter (Example % program name: prog82.m % Fs=1000; fc=300; WC=2*pi*fc; N=5; [b,a]=butter(N,WC,'s'); [z, p, k]=butter(N, WC, 's'); [bz, az]=impinvar(b,a,Fs); [h, f]=freqz(bz, az, 512,Fs); plot(f, 20*log10(abs(h))), grid xlabel('Frequency (Hz)') ylabel('Magnitude (dB)') design of the 8.19) % % % % % sampling frequency cutoff frequency cutoff frequency in radian filter order create an analog filter % determine coeffs of IIR filter ============================================== % % Program 8.3, p512. m-file for the design of the BZT filter % (Example 8.19) % program name: prog83.m % Fs=1000; % sampling frequency FN=Fs/2; fc=300; % cutoff frequency N=5; [z, p, k]=butter(N, fc/FN); [h, f]=freqz(k*poly(z), poly(p), 512, Fs); plot(f, 20*log10(abs(h))), grid ylabel('Magnitude (dB)') xlabel('Frequency (Hz)') 14 ===================================================== % % m-file for Example 8B.1 (Program 8B.1, p564). % Program name: prog8b1.m % N=2; % Filter order Fs=1280; % Sampling frequency fc=150; % Cutoff frequency WC=2*pi*fc; % Cutoff frequency in radian % % Create an analogue filter % [b,a]=butter(N,WC,'s'); [z,p,k]=butter(N, WC, 's'); % % Convert analogue filter into Discrete IIR filter % [bz, az]=impinvar(b, a, Fs); %Determine coeffs of IIR filter subplot(2,1,1) % Plot magnitude freq. response [H, f]=freqz(bz, az, 512, Fs); plot(f, 20*log10(abs(H))) xlabel('Frequency (Hz)') ylabel('Magnitude Response (dB)') subplot(2,1,2) % Plot pole-zero diagram zplane(bz, az) zz=roots(bz); % Determine poles and zeros pz=roots(az); ============================================================ % % m-file for Example 8B.2 (Program % Program name: prog8b2.m % N=2; Fs=1280; FN=Fs/2; fc=150; Fc=fc/FN; [b,a]=butter(N,Fc); filter. [z,p,k]=butter(N, Fc); subplot(2,1,1) [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) zplane(b, a) b a 8B.2, p566). % Filter order % Sampling frequency % Cutoff frequency % Normalized Cutoff frequency % Create and digitize analogue % Plot magnitude freq. response % Plot pole-zero diagram 15 ========================================================== % % m-file for Example 8B.3 (Program % Program name: prog8b3.m % Fs=2000; FN=Fs/2; fc1=200/FN; fc2=300/FN; [b,a]=butter(4,[fc1, fc2]); filter. [z,p,k]=butter(4, [fc1, fc2]); subplot(2,1,1) [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) zplane(b, a) 8B.3, p567) % Sampling frequency % Create and digitize analogue % Plot magnitude freq. response % Plot pole-zero diagram ========================================================= % % m-file for Example 8B.4 (Program 8B.4, p569) % Program name: prog8b4.m % Fs=8000; % Sampling frequency Ap=3; As=20; wp=500/4000; ws=2000/4000; [N, wc]=buttord(wp, ws, Ap, As); % Determine filter order [zz, pz, kz]=butter(N,500/4000); % Digitise filter [b, a]=butter(N, 500/4000); subplot(2,1,1) % Plot magnitude freq. response [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) % Plot pole-zero diagram zplane(b, a) ======================================================= 16 % % m-file for Example 8B.5 (Program 8B.5, % Program name: prog8b5.m % Fs=8000; Ap=3; As=20; wp=2000/4000; ws=500/4000; [N, wc]=buttord(wp, ws, Ap, As); [zz, pz, kz]=butter(N,2000/4000, 'high'); [b, a]=butter(N, 2000/4000, 'high'); subplot(2,1,1) response [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) zplane(b, a) p571) % Sampling frequency % Determine filter order % Digitise filter % Plot magnitude freq. % Plot pole-zero diagram ==================================================== % % m-file for Example 8B.6 (Program 8B.6, p572) % Program name: prog8b6.m % Band pass filter % Fs=1000; % Sampling frequency Ap=3; As=20; Wp=[200/500, 300/500]; % Band edge frequencies Ws=[50/500, 450/500]; [N, Wc]=buttord(Wp, Ws, Ap, As); % Determine filter order [zz, pz, kz]=butter(N,Wp); % Digitise filter [b, a]=butter(N, Wp); subplot(2,1,1) % Plot magnitude freq. response [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) % Plot pole-zero diagram zplane(b, a) ======================================================= 17 % % % % m-file for Example 8B.7 (Program 8B.7, p574) Program name: prog8b7.m Band stop filter % Fs=1000; Ap=3; As=20; Wp=[50/500, 450/500]; Ws=[200/500, 300/500]; [N, Wc]=buttord(Wp, Ws, Ap, As); [zz, pz, kz]=butter(N,Ws, 'stop'); [b, a]=butter(N, Ws, 'stop'); subplot(2,1,1) [H, f]=freqz(b, a, 512, Fs); plot(f, abs(H)) xlabel('Frequency (Hz)') ylabel('Magnitude Response ') subplot(2,1,2) zplane(b, a) % Sampling frequency % Band edge frequencies % Determine filter order % Digitise filter % Plot magnitude freq. response % Plot pole-zero diagram ============================================================ % % m-file for the design Example 8B.8 (Program 8B.8, p576) % Program Name: prog8b8.m % Ap=0.25; As=45; Fs=100000; Wp=[20500/50000, 23500/50000]; % Band edge frequencies Ws=[19000/50000, 25000/50000]; [N,Wc]=ellipord(Wp, Ws, Ap, As); [b, a]=ellip(N, Ap, As, Wc); [z, p, k]=ellip(N, Ap, As,Wc); zeros sos=zp2sos(z, p,k); sections subplot(2,1,1) response [H, f]=freqz(b, a, 512, Fs); plot(f, 20*log10(abs(H))) xlabel('Frequency (Hz)') ylabel('Magnitude Response (dB)') subplot(2,1,2) zplane(b, a) % % % Determine filter order Determine filter coeffs Determine poles and % Convert to second order % Plot magnitude freq. % Plot pole-zero diagram ============================================================ 18 function IIRBZT %Design program for IIR filters with Butterworth, Chebyshev, Inverse %Chebyshev or Elliptic Characteristic using bilinear transformation %output arguments: %n - estimated minimun filter order. %Wn - cutoff frequencies. %b,a - coefficients of digital filter %ftype - 'low' for lowpass filter % 'high' for highpass filter % 'bandpass' for bandpass filter % 'stop' for bandstop filter %ctype - 1 for Butterworth filter % 2 for Chebyshev filter % 3 for Inverse Chebyshev filter % 4 for Elliptic filter %steps of designing a digital filter implied in the called functions: % step 1: estimate the minimum order of the filter from specifications % step 2: get analog, pre-warped frequencies % step 3: convert to low-pass prototype estimate % step 4: Get n-th order analog lowpass prototype with desired filter characters % step 5: Transform to lowpass, bandpass, highpass, or bandstop of desired Wn % step 6: Use Bilinear transformation to find discrete equivalent: clear all; format; Fs = 100000; %sampling frequency(Hz). Wp = [20500 23500]/(Fs/2); %passband edge frequency normalised by Fs/2. Ws = [19000 25000]/(Fs/2); %stopband edge frewquency normalised by Fs/2. Rp = 0.25; %passband attenuation in dB. Rs = 45; %stopband attenuation in dB ctype = 4; %character of filter ftype = 'bandpass'; %type of filter if ctype==1 [n,Wn]=buttord(Wp,Ws,Rp,Rs); [b,a]=butter(n,Wn,ftype); elseif ctype==2 [n,Wn]=cheb1ord(Wp,Ws,Rp,Rs); [b,a]=cheby1(n,Rp,Wn,ftype); elseif ctype==3 [n,Wn]=cheb2ord(Wp,Ws,Rp,Rs); [b,a]=cheby2(n,Rs,Wn,ftype); elseif ctype==4 [n,Wn]=ellipord(Wp,Ws,Rp,Rs); [b,a]=ellip(n,Rp,Rs,Wn,ftype); end %Output the result disp('Numerator coefficients (in descending powers of z):'); disp(b); disp('Denominator coefficients (in descending powers of z):'); disp(a); 19 freqz(b,a,1024,Fs); ======================================================= function Impinv %Impulse invariance method of anolog-to-digital filter conversion %a,b -- s-plane coefficients %az,bz -- digital filter coefficients clear all; b = 1; a = [1.84496 1.920675 1]; [bz,az]=impinvar(b,a) freqz(bz,az,1024); %get z-plane coefficients using impulse Inv. ======================================================= % % Program name - prob825.m (problem 8.25(1), p553) % Comparison of magnitude and phase responses of an analogue % and equivalent BZT and impulse invariant discrete-time filters % and pole-zero diagrams (elliptic low pass filter) % Fs=10000; FN=Fs/2; fp=1000; fs=3000; wp=fp*2*pi; ws=fs*2*pi; Ap=1; As=60; % % Calculate filter coefficients and frequency responses [N, wc]=ellipord(wp, ws, Ap, As,'s'); % analog filter [B, A]=ellip(N, Ap, As, wc, 's'); [bBZT, aBZT]=bilinear(B,A,Fs); % BZT filter [bIIT,aIIT]=impinvar(B,A,Fs); % Impulse invariance filter % % Compute frequency response [Ha, wa]=freqs(B,A); [HBZT, fBZT]=freqz(bBZT, aBZT, 512, Fs); [HIIT, fIIT]=freqz(bIIT, aIIT, 512, Fs); % % Plot magnitude frequency responses % figure(1); % Plot analogue magnitude response plot(wa/(2*pi), 20*log10(abs(Ha))) hold on figure (1); plot(fBZT, 20*log10(abs(HBZT)), 'r:') % Plot BZT magnitude response hold on figure (1); plot(fIIT, 20*log10(abs(HIIT)), 'g:') % Plot Impinv magnitude response legend('Analog', 'BZT', 'Imp Invar'); axis([0 10000 -120 0]) ylabel('Magnitude (dB)') xlabel('Frequency (Hz)') 20 title('Filter magnitude responses') hold off; % % Plot phase responses % figure(2); plot(wa/(2*pi), angle(Ha)*180/pi) % Plot analogue phase response hold on figure (2); plot(fBZT, angle(HBZT)*180/pi, 'r:') % Plot BZT phase response hold on figure(2); plot(fIIT, angle(HIIT)*180/pi, 'g.') %ImpInvar phase response legend('Analog', 'BZT','Imp Invar'); axis([0 10000 -360 360]) ylabel('Phase (Degrees)') xlabel('Frequency (Hz)') title('Filter Phase Responses') hold off % % Plot pole-zero diagrams % figure (3); zplane(bBZT, aBZT) title('Pole-zero diagram - BZT filter') figure (4); zplane(bIIT, aIIT) xmin=-1; xmax=1; ymin=-1; ymax=1; % Scale the z-plane for the Impulse Inva. axis([xmin xmax ymin ymax]) title('Pole-zero diagram - impulse invariance filter') ===================================================== % % Program name - prob8261a.m (modified problem 8.26(1), p553) % Comparison of characteristic features of discrete-time Butterworth, % Chebyshev 1,Chebyshev 2 and elliptic lowpass filters. % Fs=8000; fp=500/4000; fs=2000/5000; Ap=0.1; As=60; % % Calculate filter coefficients [N1, wc1]=buttord(fp, fs, Ap, As); % filter order [N2, wc2]=cheb1ord(fp, fs, Ap, As); [N3, wc3]=cheb2ord(fp, fs, Ap, As); [N4, wc4]=ellipord(fp, fs, Ap, As); [b1, a1]=butter(4, fp); % Butterworth filter [b2, a2]=cheby1(4, Ap, fp); [b3, a3]=cheby2(4, As, fs); [b4, a4]=ellip(4, Ap, As, fp); % % Calculate frequency responses % [H1, f1]=freqz(b1, a1, 512, Fs); [H2, f2]=freqz(b2, a2, 512, Fs); 21 [H3, f3]=freqz(b3, a3, 512, Fs); [H4, f4]=freqz(b4, a4, 512, Fs); % % Plot magnitude frequency responses % figure (1); plot(f1, 20*log10(abs(H1)), 'r:') % Plot Butterworth magnitude response hold on figure (1); plot(f2, 20*log10(abs(H2)), 'b--') % Plot Cheby1 magnitude response hold on figure (1); plot(f3, 20*log10(abs(H3)), 'g-.') % Plot Cheby2 magnitude response hold on figure (1); plot(f4, 20*log10(abs(H4)), 'k-') % Plot elliptic magnitude response hold on legend('Butworth', 'Cheby1', 'Cheby2', 'Ellip'); axis([0 4000 -100 10]) ylabel('Magnitude (dB)') xlabel('Frequency (Hz)') title('Filter magnitude responses') hold off; % % Plot phase responses % figure (2); plot(f1, angle(H1)*180/pi, 'r:') % Plot BZT phase response hold on figure (2); plot(f2, angle(H2)*180/pi, 'b--') % Plot Cheby 1 phase response hold on figure (2); plot(f3, angle(H3)*180/pi, 'g-.') % Plot Cheby 2 phase response hold on figure (2); plot(f4, angle(H4)*180/pi, 'k-') % Plot elliptic phase response hold on figure(2); legend('Butter', 'Cheby1','Cheby2', 'Ellip'); axis([0 4000 -360 360]) ylabel('Phase (Degrees)') xlabel('Frequency (Hz)') title('Filter Phase Responses') hold off % % Plot pole-zero diagrams % figure (3); zplane(b1, a1) title('Pole-zero diagram - Butterworth filter') figure (4); zplane(b2, a2) title('Pole-zero diagram - Chebyshev 1 filter') figure (5); zplane(b3, a3) 22 title('Pole-zero diagram - Chebyshev 2 filter') figure (6); zplane(b4, a4) title('Pole-zero diagram - Elliptic filter') N1 N2 N3 N4 ========================================================== Chapter 9 Multirate digital signal processing % % m-file to illustrate simple interpolation and % decimation operations (Program 9B.1, p641) % File name: prog9b1.m % An Illustration of interpolation by a factor of 4 % Fs=1000; % sampling frequency A=1.5; % relative amplitudes B=1; f1=50; % signal frequencies f2=100; t=0:1/Fs:1; % time vector x=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signal y=interp(x,4); % interpolate signal by 4 stem(x(1:25)) % plot original signal xlabel('Discrete time, nT ') ylabel('Input signal level') figure stem(y(1:100)) % plot interpolated signal. xlabel('Discrete time, 4 x nT') ylabel('Output signal level') ========================================== % % m-file to illustrate simple interpolation and % decimation operations (Program 9B.2, p644). % File name: prog9b2.m % An Illustration of sampling rate changes using upfirdn by a factor of 4 % Fs=1000; % sampling frequency A=1.5; % relative amplitudes B=1; f1=50; % signal frequencies f2=100; t=0:1/Fs:1; % time vector x=A*cos(2*pi*f1*t)+B*cos(2*pi*f2*t); % generate signal y=resample(x,4,1); % interpolate signal by 4 23 stem(x(1:25)) % plot original signal xlabel('Discrete time, nT ') ylabel('Input signal level') figure stem(y(1:100)) % plot interpolated signal. xlabel('Discrete time, 4 x nT') ylabel('Interpolated output signal level') y1=resample(y,1,4); figure stem(y1(1:25)) % plot decimated signal. xlabel('Discrete time, nT') ylabel('Decimated output signal level') ============================================ function moptimum %Program moptimum is for designing I-stage optimum decimator %or interpolator (I=1,2,3 or 4). The program computes the decimation %factors, filter characteristics, and decimator efficiencies %The following parameters must be provided by the user: % Fs input sampling frequency % M overall decimation factor % fp passband edge frequency % dp overall passband deviation in +ve dB % ds overall stopband deviation in +ve dB clear all; Fs = 96000; fp = 450; dp = 0.0864; ds = 60; M = 96; % sampling frequency in Hz % passband edge frequency in Hz % overall passband deviation in +ve dB % overall stopband deviation in +ve dB % overall decimation factor EvalNStageDecimator(Fs,fp,dp,ds,M); % evaluate single stage decimator for i=2:4 % evaluate all possible 2-, 3- and 4-stage decimators R = GetFactors(M,i); for j=1:size(R,1); EvalNStageDecimator(Fs,fp,dp,ds,R(j,:)); end end =============================================== 24 % % m-file for working out the computational % complexities of a 2-stage decimator % Program name: mrate-ex1.m % dp=0.01; ds=0.01; dp1=dp/2; ds1=ds; fp=5000; Fi=1536000; F0=12000; M=Fi/F0; M1=16; M2=8; F1=Fi/M1; F2=F1/M2; fs1=F1-(Fi/(2*M)); fs2=F2-(Fi/(2*M)); df1=(fs1-fp)/Fi; df2=(fs2-fp)/F1; NUM= -10*log10(dp1*ds1)-13; N1=(NUM/(14.6*df1)); N2=(NUM/(14.6*df2)); MPS=(N1*F1 + N2*F2); TSR = N1+N2; M1 M2 fs1 fs2 df1 df2 N1 N2 MPS ====================================== function DecimationFactors = GetFactors(M,n) % The function GetFactors finds all possible decimation factors for % 2-, 3-, and 4-stage decimation. M is the % overall decimation factor and n is the number of stages p = floor(M/(2^(n-1))); m = 1; for i=2:p for j=2:p if n==2&i*j==M R(m,1) = i; % get the 2-stage decimator factors R(m,2) = j; m = m + 1; elseif n>2 for k=2:p if n==3&i*j*k==M R(m,1) = i; % get the 3-stage R(m,2) = j; % decimator factors R(m,3) = k; m = m + 1; elseif n>3 for l=2:p if i*j*k*l==M R(m,1) = i; % get the 4-stage R(m,2) = j; % decimator factors R(m,3) = k; R(m,4) = l; m = m + 1; 25 end end end end end end end R = z = k = for fliplr(sort(R')'); % sort the decimation factor vectors zeros(1,size(R,2)); 1; i=1:size(R,1) % reject the redundancies for j=i+1:size(R,1) if R(i,:)==R(j,:) R(j,:) = z; end end if R(i,:)~=z DecimationFactors(k,:) = R(i,:); k = k + 1; end end ========================================================== function decimation %program performs multi-stages of decimation on data in a userspecified data file %enough data must be guaranteed when using a large overall decimation fator clear all; r = [2 2 3 2]; % decimation factor array for different stages FIR = 0; % 1 - use FIR filter, 0 - use IIR filter n = 0; % order of IIR filter or FIR filter length % n=0 for 30 points FIR filter or 8th order Chebyshev type I LPF filter in = fopen('decimation.dat','r') ; [x,count] = fscanf(in,'%g',inf); % data to be decimated y = x; fclose(in); for i=1:length(r) if n==0 %decimating data use default filter if FIR y = decimate(y,r(i),'fir'); else y = decimate(y,r(i)); end else if FIR y = decimate(y,r(i),n,'fir'); else y = decimate(y,r(i),n); end end 26 end plot(1:count,x,1:prod(r):count,y(1:length(y)),'o'); =========================================================== function EvalNStageDecimator(Fs,fp,dp,ds,R) format long; a1 = 0.005309; a2 = 0.07114; a3 = -0.4761; a4 = -0.00266; a5 = -0.5941; a6 = -0.4278; a7 = 11.01217; a8 = 0.51244; dp = 10^(dp/20.0)-1; ds = 10^(-ds/20.0); Ftemp = Fs; dp = dp/length(R); MPS = 0; TSR = 0; fprintf('stage\tfactor\tFi\tfp\tfs\tdp\tds\tN\n'); for i=1:length(R) % n=size(R,1) possible k-stages decimators F = Ftemp/R(i); fs = F - Fs/2/prod(R); df = (fs - fp)/Ftemp; Ftemp = F; N = round((log10(ds)*(a1*log10(dp)^2+a2*log10(dp)+a3)+... a4*log10(dp)^2+a5*log10(dp)+a6)/df-df*(a7+a8*(log10(dp)log10(ds)))+1); fprintf('%d\t%d\t%d\t%d\t%d\t%-7.4f\t%7.4f\t%d\n',i,R(i),F,fp,fs,dp,ds,N); MPS = MPS + N*F; TSR = TSR + N; end fprintf('MPS = %d, TSR = %d\n\n',MPS,TSR); format; ======================== function interpolation %program performs multi-stages interpolation on data in a userspecified data file clear all; r = [2 1 1]; % decimation factor array for different stages l = 4; % filter length alpha = 0.5; % cut-off frequency in = fopen('decimation.dat','r') ; [x,count] = fscanf(in,'%g',inf); % data to be decimated y = x; fclose(in); for i=1:length(r) y = interp(y,r(i),l,alpha); end subplot(1,2,1);stem(x);subplot(1,2,2);stem(y); 27 Chapter 10 Adaptive filters function LMSADF %Program to illustrate adaptive filtering using the LMS algorithms % % % % X Y W E delayed input data vector measured signal coefficient vector enhanced signal N=30; % filter length M=0; % delay w0=1; % initial value for adaptive filter coefficients SF=2048; % factor for reducing the data samples - 11 bit ADC assumed mu=0.04; X = zeros(N,1); delay = zeros(1,M+1); W = w0*ones(N,1); in = fopen('ADF.dat','r'); %read input data from specified data file Y = fscanf(in,'%g',inf)/SF; fclose(in); if w0==0 sf = SF; % scaling factor for display else sf = SF/N/w0; end for i=1:length(Y) if M>0 delay(2:M+1) = delay(1:M); % shift data for delay end delay(1) = Y(i); X(2:N) = X(1:N-1); % update buffer X(1) = delay(M+1); E(i) = Y(i)-W'*X; % the enhanced signal W = W + 2*mu*E(i)*X; % update the weights end subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal'); subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal'); ==================================================== function UDUADF % program to illustrate adaptive filtering using % the RLS algorithm via the UDU factorization % % % % X Y W E delayed input data vector measured signal coefficient vector enhanced signal clear all; N = 30; % filter length 28 M = 1; % delay npt = N*(N+1)/2; SF = 2048; % 12-bit ADC scaling p0 = 0.05; w0 = 1; gamma = 0.98; RemoveMean = 0; % 1 - remove the mean from the data, 0 - otherwise delay = zeros(1,M); U=zeros(1,npt); U(1)=p0; W = w0*ones(N,1); X = zeros(N,1); for i=1:N-1 ik=(i*(i+1)-2)/2+1; U(ik)=p0; end if w0==0 sf = SF; % scaling factor for display else sf = SF/N/w0; end in = fopen('ADF.dat','r'); Y = fscanf(in,'%g',inf)/SF; fclose(in); %read input data from specified data file if RemoveMean required Y = Y - sum(Y)/length(Y); end % remove the mean from the data if for i=1:length(Y) if M>0 delay(2:M+1) = delay(1:M); registers end delay(1) = Y(i); X(2:N) = X(1:N-1); X(1) = delay(M+1); % shift input data in delay % update buffer E(i) = Y(i) - X'*W; % the enhanced signal W = uduflt(W,X,U,E(i),gamma ,N); end subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal'); subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal'); ========================================== 29 function w=uduflt(w,x,u,ek,gamma,N) % udu algorithm - a numerically stable form of % the recursive least squares algorithm % % inputs: % x() input vector % dn latest input data value % w() coefficient vector % u() vector containing elements of U and D % % outputs: % en error signal % yn digital filter output % w() updated coefficient vector % u() updated elements of U and D % sf = 1/gamma; m=1; % update the UD elements v=zeros(1,N); v(1)=x(1); for j=2:N v(j)=x(j); for k=1:j-1 m=m+1; v(j)=v(j)+u(m)*x(k); end m=m+1; b(j)=u(m)*v(j); end b(1)=u(1)*x(1); alpha=gamma+b(1)*v(1); delta=1/alpha; u(1)=u(1)*delta; m=1; for j=2:N beta1=alpha; alpha=alpha+b(j)*v(j); p=-v(j)*delta; delta=1/alpha; for k=1:j-1 m=m+1; beta=u(m); u(m)=beta+b(k)*p; b(k)=b(k)+b(j)*beta; end m=m+1; u(m)=u(m)*beta1*delta*sf; end perr=ek/alpha; for j=1:N % update the weights w(j)=w(j)+b(j)*perr; end 30 ============================================ function SQRTADF % program to illustrate adaptive filtering using % the square root RLS algorithm % % % % X Y W E delayed input data vector measured signal coefficient vector enhanced signal N = 30; % filter length M = 1; % delay npt = N*(N+1)/2; SF = 2048; % 12-bit ADC scaling p0 = 0.05; w0 = 1; gamma = 0.98; RemoveMean = 0; % 1 - remove the mean from the data, 0 - otherwise delay = zeros(1,M); W = w0*ones(N,1); X = zeros(N,1); S = zeros(1,npt); S(1)=p0; for i=1:N-1 ik=(i*(i+1)-2)/2+1; S(ik)=p0; end if w0==0 sf = SF; % scaling factor for display else sf = SF/N/w0; end in = fopen('ADF.dat','r'); Y = fscanf(in,'%g',inf)/SF; fclose(in); %read input data from specified data file if RemoveMean required Y = Y - sum(Y)/length(Y); end % remove the mean from the data if for i=1:length(Y) if M>0 delay(2:M+1) = delay(1:M); registers end delay(1) = Y(i); X(2:N) = X(1:N-1); X(1) = delay(M+1); E(i) = Y(i) - X'*W; % shift input data in delay % update buffer % the enhanced signal 31 W = sqrtflt(W,X,E(i),S,gamma,N); end subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal'); subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal'); ================================================== function w=sqrtflt(w,x,perr,s,gamma,N) % % % % A simple square root RLS adaptive filter For details, see: Digital Signal Processing: A Practical Approach E C Ifeachor and B W Jervis, Pearson, 2002 forgt=sqrt(gamma); sig=forgt; sigsq=forgt*forgt; ij=1; ji=1; for j=2:N fj=0.0; for i=1:j-1 ji=ji+1; fj=fj+s(ji)*x(i); end a=sig/forgt; b=fj/sigsq; sigsq=sigsq+fj*fj; sig=sqrt(sigsq); a=a/sig; g(j)=s(ji)*fj; s(ji)=a*s(ji); for i=1:j-1 ij=ij+1; sqp=s(ij); s(ij)=a*(sqp-b*g(i)); g(i)=g(i)+sqp*fj; end ij=ij+1; end w = w + g'*perr/sigsq; ============================= function RLSadf % program to illustrate adaptive filtering using % the RLS algorithm % % % % X Y W E delayed input signal measured signal coefficient vector enhanced signal N = 30; M = 1; SF = 2048; p0 = 0.05; % filter length % stages of delay % 12-bit ADC scaling 32 w0 = 100; gamma = 0.98; RemoveMean = 0; % 1 to remove the mean, 0 otherwise W = w0*ones(N,1); % adaptive filter weights X = zeros(N,1); delay = zeros(1,M+1); P = p0*diag(ones(1,N),0); if w0==0 sf = SF; % scaling factor for display else sf = SF/N/w0; end in = fopen('ADF.dat','r'); Y = fscanf(in,'%g',inf)/SF; fclose(in); %read input data from specified data file if RemoveMean % remove the mean from the data if required Y = Y - sum(Y)/length(Y); end for i=1:length(Y) if M>0 delay(2:M+1) = delay(1:M); % shift input data in delay registers end delay(1) = Y(i); X(2:N) = X(1:N-1); % update buffer X(1) = delay(M+1); E(i) = Y(i) - X'*W; G = P*X/(gamma + X'*P*X); P = (P - G*X'*P)/gamma; W = W + G*E(i); % the enhanced signal % update the weights end subplot(2,1,1),plot(1:length(Y),Y*SF); title('Input Signal'); subplot(2,1,2),plot(1:length(E),E*sf); title('Enhanced Signal'); ======================================== Chapter 11 Spectrum estimation and analysis N/A 33 Chapter 12 General and special-purpose digital signal processors. function cgdft % function cgdft compute DFT coefficients using DIT FFT algorithm % function cgfft.m is used to implement the constant geometry FFT clear all; direction = 1; %1 - forward DFT, -1 - inverse DFT in=fopen('datain.dat','r'); [x,count]=fscanf(in,'%g %g',[2 inf]); fclose(in); x = x(1,:)+x(2,:)*i; % form complex numbers npt = 2^(nextpow2(count/2)); % find the next power of two x(1:npt) = [x; zeros(npt-count/2,1)]; % x is padded with trailing zeros to npt y=cgfft(x,npt,direction); % calculate the constant geometry FFT % Save/Print the results out=fopen('dataout.dat','w'); fprintf(out,'%g %g\n',[real(y); imag(y)]); fclose(out); subplot(2,1,1),plot(1:npt,x); title('Input Signal'); subplot(2,1,2),plot(1:npt,y); title('Output Signal'); =============================================== function x=cgfft(x,npt,direction) % Function computes the DFT of a sequence using radix2 FFT % with constant geometry % in-place bit reverse shuffling of data j=2; for n=2:npt if n<j t = x(j-1); x(j-1) = x(n-1); x(n-1) = t; end k = npt/2; while k<j-1 j = j-k; k = k/2; end j = j+k; end m = log2(npt); % calculate the number of stages: m=log2(npt) 34 w = exp(direction*2*pi*(0:npt/2-1)/npt*i); % pre-compute the twiddle factors % perform the FFT computation for each stage for d=1:m n = 1; dk = 2^(d-1); dr = npt/(2^d); for k=0:dk-1 p = (k*npt)/(2^d)+1; for r=1:dr if rem(d,2)~=0 t = x(2*n)*conj(w(p)); x1(n) = x(2*n-1)+t; x1(npt/2+n) = x(2*n-1)-t; else t = x1(2*n)*conj(w(p)); x(n) = x1(2*n-1)+t; x(npt/2+n) = x1(2*n-1)-t; end n = n+1; end end end if rem(m,2)~=0 x = x1; end %If inverse fft is desired divide each coefficient by npt if direction==-1 x = x /npt; end Chapter 13 Analysis of finite wordlength effects in fixed-point DSP systems. N/A Chapter 14 Applications and design studies N/A 35