Uploaded by Vivek Rai

DSP Manual Complete-converted

advertisement
Lab Manual
Digital Filter Design
Instructor: Dr. ANURAG SINGH
Digital Filter Design Lab Experiments
1. REVISIT CONCEPTS FROM SIGNALS AND SYSTEMS
AIM: Write MATALB programs for following problems and revise your basic
understanding of MATLAB language and concepts of signals and systems.
a) Represent the discrete-time (DT) signal:
and plot it using stem function.
�
b) Represent the DT signal: �(�) = ��(8)� for 0≤n≤32 and plot the real, imaginary,
absolute and angle (phase angle in radians) parts. Now convert and plot the phase
angle in degrees and make sure that your plot should have a title, as well as labels
for both axes.
c) Determine (using MATLAB) and plot even and odd parts of the following DT
sequence: �(�) = 0.8�
2. GENERATION OF SUM OF SINUSOIDAL SIGNALS
AIM: Generate sum of sinusoids and verify Fourier theorem. Practically, how many
sinusoids are required to make a square wave? Experiment and observe.
THEORY: A continuous-time signal x(t) is said to be periodic with period T if it satisfy
the condition
x (t+T) = x(t) for all t
-∞<t<+∞ ................. eq1
A signal is periodic if the above condition is satisfied for every value of T.
The smallest value of T that satisfies the above condition is known as fundamental period.
Complex exponential and sinusoidal signals are examples for continuous- time
Periodic signals. Consider a sinusoidal signal
x (t)=A sin (ωt+θ) .................................................................................eq2
Where A is the amplitude, ω is the frequency in radians per second (rad/sec), and θ the
phase in radians. The frequency f0 in hertz is given by f0 = ω /2π
For periodic signal we have
X(t+T)=x(t) ....................................................eq3
For x(t)=Asin(ωt+θ) ...........................eq4
X (t+T) = Asin [ω (t+T)+ θ)]
=Asin[ωt+ωT+θ] ...........................eq5
Equation 5 and 2 are equal if
ωT = 2π
,
Thu
the
T =2π/ ω
sinusoidal
is
periodic
with
period
2π/
ω.
The sum of two periodic signals x1(t) and x2(t) with periods T1 and T2 respectively may
or may not be periodic, then the ratio T1/T2 can be written as the ratio a/b of two integers
a and b. If T1/T2 = a/b, then bT1 = aT2, and since a and b are integers, x1(t) and x2(t) are
periodic with period bT1. If a and b are co prime (i. e. a and b have no common integer
factors other than 1) then T = bT1 is the fundamental period of the sum of two signals.
PROGRAM:
clc; clear all; close all;
t=0:.2:10; % Generating time instants
x1=(4/pi)*sin(t); % Generating a sinusoid of frequency 1
rad/s
subplot(2,2,1); plot(t,x1); % Plotting the sinusoid
title('Single sinusoid');
x2=(4/pi)*1/3*sin(3*t); % Generating another sinusoid of
frequency 3 rad/s
xa=x1+x2;% Adding both sinusoids to get two frequencies
subplot(2,2,2); plot(t,xa);
title(' Sum of two sinusoid');
x3=(4/pi)*1/5*sin(5*t);
xb=x1+x2+x3;
subplot(2,2,3); plot(t,xb);
title(' Sum of three sinusoid');
x4=4/pi*1/7*sin(7*t);
xc=x1+x2+x3+x4;
subplot(2,2,4); plot(t,xc);
title(' Sum of four sinusoid');
OUTPUT WAVEFORMS
RESULT DESCRIPTION:
Visual output in the output waveforms can be seen to visualize a signal with
multiple frequencies. It is also interesting to observe in the output waveforms
that after adding multiple sinusoids of different frequency and amplitudes the
resulting signal tends towards a square wave. It proves converse of a famous
frequency analysis tool/transform. Guess what??
3. FREQUENCY DOMAIN ANALYSIS OF DISCRETE SIGNALS
USING DFT AND IDFT
AIM: To obtain DFT/IDFT of a given sequence/signal and analyse its
frequency spectrum
THEORY:
Discrete Fourier Transform (DFT) is used for performing frequency analysis of
discrete time signals. DFT gives a discrete frequency domain representation whereas
the other transforms are continuous in frequency domain. The N point DFT of discrete
time signal x[n] is given by the below equation. The inverse DFT allows us to recover
the sequence x[n] from the frequency samples.
X (k) is a complex number (remember ���=cos� + jsin �). It has both
magnitude and phase which are plotted versus k. These plots are magnitude and phase
spectrum of x[n]. The “k” gives us the frequency information. Here k=N in the frequency
domain corresponds to sampling frequency (fs). Increasing N, increases the frequency
resolution,
i.e. it improves the spectral characteristics of the sequence. For example, if fs=8kHz and
N=8 point DFT, then in the resulting spectrum, k=1 corresponds to 1kHz frequency. For
the same fs and x[n], if N=80 point DFT is computed, then in the resulting spectrum, k=1
corresponds to 100Hz frequency. Hence, the resolution in frequency is increased. Since N
≥ L, increasing N to 8 from 80 for the same x[n] implies x[n] is still the same sequence
(<8), the rest of x[n] is padded with zeroes. This implies that there is no further
information in time domain, but the resulting spectrum has higher frequency resolution.
This spectrum is known as “high density spectrum” (resulting from zero padding x[n]).
Instead of zero padding, for higher N, if more number of points of x[n] are taken (more
data in time domain), then the resulting spectrum is called a “high resolution spectrum”.
PROGRAM:
A) DFT of a given sequence x(n)
close all;
clc; clear all;
x=input('Enter the input sequence ');
N=length(x); % Calculating length of the signal
for k=0:N-1; % Generating W matrix
for n=0:N-1;
p=exp(-j*2*pi*k*n/N);
W(k+1,n+1)=p;
end
end
X=W*x'; % DFT calculation
Theta=phase(X); % Calculation of Phase associated with
each DFT point
disp('The DFT of the given sequence is') % Display the
inside text as it is
disp(X) % Display the contents of X
subplot(2,1,1);
stem(abs(X)); % Plot X in discrete form
xlabel(' Sample index');
ylabel('Amplitude');
title('Magnitude plot');
subplot(2,1,2);
stem(Theta);
xlabel('Sample index');
ylabel('Amplitude');
title('Phase plot from DFT of the given sequence');
OUTPUT:
Enter the input sequence [2 3 4 5 6 7 2 3 4 9]
X=2
3
4
5
6
7
2
3
4
9
N=10
X1 = 45.0000
-1.7639 - 0.7265i 2.2361 +10.6861i
-6.2361 +
3.0777i -2.2361 + 3.9757i -9.0000 - 0.0000i -2.2361 - 3.9757i -6.2361 3.0777i 2.2361 -10.6861i -1.7639 + 0.7265i
OUTPUT WAVEFORMS:
Observation: No. of samples in original signal and its DFT are same, i.e. N=10.
(WHY ?) No. of phases would also be same.
Exercise:
1. Use direct MATLAB commands for DFT ‘’fft’ and verify the above results
calculated through mathematical equations.
2. Repeat experiment by changing the number of DFT points, i.e. N and observe
the change in values of DFT points. As you change N, number of DFT points
and their values, both get changed. WHY change in values?
3. Generate a multi-frequency sinusoid (more than two frequencies) and analyze
its DFT spectra. Use minimum two frequencies.
4. Locate and observe clearly the frequencies taken for sinusoids in the
DFT/frequency spectrum of the signal (on the x-axis or frequency axis). Refer
‘fft’ command examples in MATLAB HELP window.
5. Add noise (using awgn MATLAB command) to above sinusoid. Calculate
DFT of original and noisy sinusoid. Analyze the difference and similarity
between two DFTs (particularly for amplitude and frequency), i.e., frequency
domain representations.
6. Think about the ways we can remove the noise from the original signal. What
would be the correct domain (Time domain or Frequency domain) to separate
out the noise from the noisy signal? Is frequency domain representation
helpful? If yes, WHY?
B) IDFT of a given DFT sequence X(k)- using direct IDFT formula
close all;
clc; clear all;
X=input('Enter the input DFT sequence ');
N=length(X); % Calculating length of the signal
for n=0:N-1; % Generating W matrix
for k=0:N-1;
p=exp(j*2*pi*k*n/N);
W(n+1,k+1)=p;
end
end
x=W'*X'/N; % IDFT calculation
Theta=phase(x); % Calculation of Phase associated with
each IDFT point
disp('The IDFT of the given sequence is')
disp(x)
subplot(2,1,1);
stem(abs(x)); % Plot x in discrete form
xlabel(' Sample index');
ylabel('Amplitude');
title('Magnitude plot');
subplot(2,1,2);
stem(Theta);
xlabel('Sample index');
ylabel('Amplitude');
title('Phase plot from DFT of the given sequence');
OUTPUT:
Enter the input sequence [10 -2+2i -2 -2-2i]
X =10.0000
-2.0000 + 2.0000i -2.0000
-2.0000 - 2.0000i
N =4
X1 = 1.0000
2.0000 + 0.0000i 3.0000 - 0.0000i 4.0000 - 0.0000i
OUTPUT WAVEFORMS:
Observation:
You can observe same no. of samples again in original time domain signal its DFT
and its IDFT including phase values.
Exercise:
1. Use direct MATLAB commands for IDFT and verify the above results
calculated through mathematical equations.
2. Theoretically you should get a periodically repeated sequence of original time
domain sequence after doing inverse DFT. But, practically are you getting it
or not after applying IDFT, check it ? (NOTE: MATLAB returns back only
one period)
3. Calculate DFT using fft of any arbitrary sequence for two cases: i) Take no.
of DFT points (N) larger than the signal length (L), i.e., N>=L; ii) Take no. of
DFT points (N) smaller than the signal length (L), i.e., N<L.
4. Now recover back the original time-domain sequence using ifft in both of the
above cases, i.e., when N>=L and when N<L. Observe the recovered
sequences. Are both same? If not, WHY? Is time domain aliasing happening,
HOW? (NOTE: MATLAB returns back only one period)
4. LINEAR CONVOLUTION
AIM: To perform a Linear Convolution operation using MATLAB.
Theory: A linear convolution operation is a mathematical operation which is used to find the
response of an LTI system with known impulse response. Indirectly, any LTI system can be
treated as a filter, so practically, a linear convolution operation can be termed as a filtering
operation, which is used to filter input x[n] through system h[n] or h(t).
The convolution of x and h is written x∗ h, denoting the operator with the symbol ∗ . It is
defined as the integral of the product of the two functions after one is reversed and shifted. As
such, it
is a particular kind of integral transform:
�(�) ∗ ℎ(�) = ∫
∞
�(�)ℎ(� − �)��
−∞
In discrete domain-
∞
ℎ[�] ∗ �[�] = ∑ �(�)ℎ(� − �)
�=−∞
MATLAB program for discrete linear convolutionx = input('enter a sequence');
h = input('enter another sequence');
a = length(x);
b = length(h);
n = a+b-1;
% output comes out from 0 to a+b-2
y = zeros(1,n);
l = 1:n;
for i = 0:n
for j = 0:n
if ((i-j+1)>0 && (i-j+1)<=b && (j+1)<=a)
y(i+1) = y(i+1)+ x(j+1).*h(i-j+1);
end
end
end
disp(y)
stem(l,y)
OUTPUT WAVEFORMS:
RESULT:
Enter the 1st sequence x= [1 2 3]
Enter the 2nd sequence h= [1 2 3 4]
The resultant signal is y= [1, 4, 10, 16, 17, 12]
Observation: Check for number of terms in the convolved sequence. It must be equal
to sum of lengths of convolving sequences minus 1.
Exercise:
 Repeat the experiment and perform linear convolution using inbuilt
MATLAB command ‘conv’.
 Verify both results for same output sequence. The command ‘conv’
uses circular convolution technique to calculate discrete linear
convolution. WHY?
 Generate two practical signals, say two rectangular pulses of unity
width and height.
 Use ‘conv’ command to find their convolved sequence as a trapezium
of width 2 (sum of width of two convolving sequences). This verifies
width property of convolution operation.
5. CIRCULAR CONVOLUTION
AIM: Program for Computing Circular Convolution
Theory: Frequency domain analysis of discrete systems is not possible through linear
convolution due to its computational limitation. Linear convolution is equivalent to frequency
domain multiplication of system response to the input signal. However, output of the system
remains a function of continuous variable omega, i.e., frequency which can’t be realized/analyzed
on a digital machine. Hence, an equivalent operation is performed on a digital machine to compute
linear convolution that is called circular convolution. This is the reason, inbuilt linear convolution
MATLAB command ‘conv’ also uses circular convolution backend to perform linear convolution.
There are three methods discussed below to compute circular convolution using MATLAB
software.
(a) MATLAB program to compute circular convolution using theoretical
formula
clc;
clear;
a = input ('enter the sequence x(n) =
'); b = input('enter the sequence h(n) =
'); n1=length(a);
n2=length (b);
N=max
(n1,n2);
x = [a zeros(1,(N-n1))];
for i = 1:N
k = i;
for j = 1:n2
H(i,j)=x(k)* b(j);
k = k-1;
if (k == 0)
k = N;
end
end
end
y=zeros(1,N);
M=H';
for j = 1:N
for i = 1:n2
y(j)=M(i,j)+y(j); end
end
disp('The circular convolved sequence is y(n)= ');
disp(y);
RESULT:
enter the sequence x(n) = [1 2 3]
enter the sequence h(n) = [1 2 3 4]
The output sequence is y(n)= 18 16 10 16
(b) Computing Circular Convolution with using circular shift
clc;
clear all;
close all;
x=input(' enter 1st sequence');
h=input('enter 2nd sequence');
l1=length(x);
l2=length(h);
l3=l1+l2-1;
x=[x,zeros(1,l3-l1)];
h=[h,zeros(1,l3-l2)];
for j=1:l1+l2-1
for i=1:l1+l2-1
a(i,j)=x(i);
end
x=circshift(x,[1,1]);
end
h=h';
o=a*h;
o=o';
display(o);
RESULT:
enter 1st sequence[1 2 3]
enter 2nd sequence[1 2 3 4]
o=
1
4
10 16 17 12
(c) %Program for Circular convolution using DFT-IDFT
close all;
clear all;
clc;
x=input('enter the value of first input sequence');
disp('1st i/p sequence is');
disp(x);
h=input('enter the values of 2nd dft sequence');
disp('2nd i/p sequence is');
disp(h);
lx=length(x);
lh=length(h);
N=max(lx,lh);
xx=[x zeros(N-lx)];
HH=[h zeros(N-lh)];
W=zeros(N,N);
for n=0:N-1
for k=0:N-1
W(n+1,k+1)=exp(-i*2*pi*n*k/N); %Calculating Twiddle Factor
end;
end;
X=W*xx.'; %Calculating DFT of first sequence
H=W*HH.'; %Calculating DFT of second sequence
disp('DFT of 1st sequence is');
disp(X.');
disp('DFT of 2nd sequence is');
disp(H.');
figure
subplot(2,1,1);
stem(x);
title('1st i/p sequence');
subplot(2,1,2);
compass(X); % Circular Plot through arrows of DFT of first sequence
title('dft of 1st sequence');
figure
subplot(2,1,1);
stem(h);
title('2nd i/p sequence');
subplot(2,1,2);
compass(H); % Circular Plot through arrows of DFT of second sequence
title('dft of 2nd sequence');
YY=X.*H; %Multiplication of DFT’s of two input sequences
w=zeros(N,N);
for n=0:N-1
for k=0:N-1
w(n+1,k+1)=exp(i*2*pi*n*k/N); %factor for determining circular
convolved sequence
end;
end;
B=w*YY;
Y=B/N; %circular convolved sequence
disp('Dft of o/p sequence is');
disp(YY.');
disp('IDFT of o/p sequence is');
disp(Y.');
figure
subplot(2,1,1)
compass(YY); % Circular Plot through arrows of Multiplication of DFT’s of two
input sequences
title('o/p DFT sequence of result');
subplot(2,1,2);
compass(Y); %polar plot of circularly convolved sequence
title('circular convoluted o/p');
OUTPUT WAVEFORMS:
2nd ilp sequence
4
3
2
0
1
1.5
2
3
2.5
dft of 2nd sequence
120
90 1D
60
150
30
180
0
330
210
240
270
300
o/p DFT sequence of result
120
60
150
30
0
180
210
330
240
270
300
circular convoluted o/p
120
150
90 20
60
f
1J
30
0
180
330
210
240
270
300
3.5
4
RESULT:
Enter the value of first input sequence [1 2 3]
1st i/p sequence is
1
2
3
enter the values of 2nd dft sequence [ 1 2 3 4]
2nd i/p sequence is
1
2
3
4
DFT of 1st sequence is
6.0000 + 0.0000i -2.0000 - 2.0000i 2.0000 + 0.0000i -2.0000 + 2.0000i
DFT of 2nd sequence is
10.0000 + 0.0000i -2.0000 + 2.0000i -2.0000 - 0.0000i -2.0000 - 2.0000i
DFT of o/p sequence is
60.0000 + 0.0000i 8.0000 + 0.0000i -4.0000 - 0.0000i 8.0000 + 0.0000i
IDFT of o/p sequence is
18.0000 + 0.0000i 16.0000 + 0.0000i 10.0000 - 0.0000i 16.0000 - 0.0000i
B= [72.0000 + 0.0000i
0.0000i]
h=[1 2 3 4]
64.0000 + 0.0000i
40.0000 - 0.0000i
64.0000 -
H= [10.0000 + 0.0000i -2.0000 + 2.0000i -2.0000 - 0.0000i -2.0000 - 2.0000i]
; HH=[1 2 3 4]
k=3; lh=3; n=3; N=4; x=[1 2 3];
X=[ 6.0000 + 0.0000i -2.0000 - 2.0000i 2.0000 + 0.0000i
-2.0000 + 2.0000i ] ; xx=[1 2 3 0]
Y=[ 18.0000 + 0.0000i 16.0000 + 0.0000i 10.0000 - 0.0000i 16.0000 - 0.0000i
]
YY=[ 60.0000 + 0.0000i 8.0000 + 0.0000i -4.0000 - 0.0000i
8.0000 + 0.0000i ]
Exercise:
 Repeat the experiment and perform linear convolution using inbuilt MATLAB
command ‘cconv’. Verify both results for same output sequence.
 Take two arbitrary discrete sequences of different lengths, say L and M. Now
perform linear convolution and get the convolved output sequence
 Now perform circular convolution using cconv for two cases: i) N>L+M-1 ; ii)
N<L+M-1
 Verify that the result of circular convolution when N>L+M-1 is numerically same
to linear convolution.
 Compare also the result of circular convolution when N<L+M-1 to linear
convolution result. Both are not same! WHY? Is the time domain aliasing is the
reason behind not getting same results after linear and circular convolution? If
yes, HOW?
6. FREQUENCY RESPONSE OF A SYSTEM
AIM: To plot the frequency response of the given system
THEORY:
If we know a transfer function model of the system, i.e. H(z), we can calculate the frequency
response from the transfer function, as explained below.
Suppose that system has the transfer function H(s) from input u to output y, that is,
y(s) = H(s)u(s)
By setting s = jω (j is the imaginary unit) into H(s), we get the complex quantity H(jω),
which is the frequency response (function).
The gain function is
A(ω) = |H(jω)| .
The phase shift function is the angle or argument of H(jω):
φ(ω) = arg[H(jω)]
%PROGRAM:
clc; clear all; close all;
b = [1, 4]; %Numerator coefficients of system response H(z)
a = [1, -5]; %Denominator coefficients of system response H(z)
w = -2*pi: pi/256: 2*pi; % Defining frequency points to calculate frequency response
[h] = freqz(b, a, w); %Calculating frequency response H(w) at the defined frequency points
subplot(2, 1, 1);
plot(w, abs(h));
xlabel('Frequency \omega');
ylabel('Magnitude');
grid on;
subplot(2, 1, 2);
plot(w, angle(h));
xlabel('Frequency \omega');
ylabel('Phase - Radians');
grid on;
OUTPUT WAVEFORMS:
RESULT:
If we know H(z), then using the filter coefficiets, b and a, we can find the
frequency response H(w) of the given system. As above, if b = [1, 4]; and a =
1+4�
[1, -5]; i.e., (�) =
, then H(w) will be sinusoidal in nature as shown in
1−5�
above output plot.
7. SPECTRAL ANALYSIS OF NOISY SIGNAL BEFORE AND AFTER
FILTERING
% program
clc;
close all;
clear all;
% simulate noisy multifrequency sinusoid signal
Fs = 1000; % sampling frequency
f = 100;
n = [0:1/Fs:1];
x = sin(2*pi*f*n) + sin(2*pi*f*n/5);
subplot(3,2,1);
plot(n,x);
title('Original Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% Spectral analysis of the ORIGINAL signal
L = length(x);
NFFT = 2^nextpow2(L);
x_fft = abs(fft(x,NFFT))/L;
% creating frequency axis
freq = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum
subplot(3,2,2);
stem(freq,2*x_fft(1:NFFT/2+1));
title('Single-Sided Amplitude Spectrum of Original
Signal x(t)');
xlabel('Frequency (Hz)');
ylabel('|X(f)|');
% add noise to the signal
y = x + 2*rand(size(n));
% plot the noisy signal
subplot(3,2,3); plot(n,y);
title('Noisy Signal');
xlabel('Time (s)');
ylabel('Amplitude');
% Spectral analysis of the NOISY signal
L = length(y);
NFFT = 2^nextpow2(L);
y_fft = abs(fft(y,NFFT))/L;
% creating frequency axis
freq = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum
subplot(3,2,4);
stem(freq,2*y_fft(1:NFFT/2+1));
title('Single-Sided Amplitude Spectrum of Noisy Signal
y(t)');
xlabel('Frequency (Hz)');
ylabel('|Y(f)|');
% Design a Filter and apply on the noisy signal to denoise it
o = 7; % filter order
wn = [19 121]*2/Fs; % Defining cutoff frequencies based on
the frequencies present in the original signal. Denoising
depends on precise selection of cutoff frequencies of the filter
[b,a] = butter(o,wn,'bandpass'); Calculation of filter
coefficients of a butterworth bandpass filter
% Computing frequency response of the filter
[h,w] = freqz(b,a,1024,Fs);
subplot(3,2,5);
plot(w,20*log10(abs(h)));
title('Magnitude Response of the Filter');
xlabel('Frequency (Hz)');
ylabel('Magnitude');grid on;
% Filter the signal
y_filt = filter(b,a,y); % Passing the noisy signal ‘y’ through
the above designed filter for filtering and outputting the filtered
signal y_filt
subplot(3,2,6);
plot(n,y_filt);
title('Filtered Signal');
xlabel('Time (s)');
ylabel('Amplitude');
axis([0 1 -2 2])
OUTPUT WAVEFORMS:
RESULT:
Output waveforms are shown in above figure. Though the denoising is not proper
as a bandpass filter with the defined cutoff frequencies may not be suitable for
the task. But the objective of the above experiment is to introduce filters and
make you understand how to use it for a practical task. Here we have chosen order
and cutoff frequencies using hit and trial and a more precise selection of these
designing parameters would improve the denoising performance.
8. Analysis of a signal in time and frequency domain with Noising and
DeNoising effects
In this experiment we are analysing a practical audio signal, doing spectral
analysis and adding/removing noise out of it
% Program
[y1 fs]=audioread('Ringtone.wav');%taking input of any audio signal
X1=y1+2*rand(length(y1),1); %Addition of noise using randn command
time=(1/fs)*length(y1);
t=linspace(0,time,length(y1)); %for generating time axis
subplot(5,1,1);
plot(t,y1);
title('Time domain plot of original signal'); % this is original signal plot
% plotting for Noise added signal
subplot(5,1,2);
time1=(1/fs)*length(X1);
t1=linspace(0,time1,length(X1)) %for generating time axis
plot(t1,X1);
title('Time domain plot of Noise-added signal i.e X1'); %this plot will be of Noiseadded to the original signal
%plotting of original signal in frequency domain
subplot(5,1,3);
N=length(y1); %determining the length of the signal
Fc=(-N/2:N/2-1)/N; %for frequency normalizing axis
F=fs*Fc; %Generating frequency axis
we=fft(y1);
we=fftshift(we); %for centering zero
plot(F,we);
title('Frequency plot of original signal'); %plotting in frequency domain
subplot(5,1,5);
%noise removal code
i=1;
for j=2:length(X1)-1 %for averaging high frequency signal
y1(j,1)=(y1(j-1,i)+y1(j,i)+y1(j+1,i))/3; %simple average
end
g=gausswin(20);%creating Gaussian Window of 20 unit column vector
wvtool(gausswin(20)); % for Visualizing Gaussian Window
g=g/sum(g); %it will be use for convolution
y=conv(y1(:,1),g,'same');%applying convolution to remove effect of randn pseudono.
added noise
result=sgolayfilt(y,1,17);%Apply signal smoothing using Savitzky-Golay smoothing
filter
audiowrite('result.wav',result,fs); %resultant signal can be written to the new file
Nn=length(result); %Length of new array which we got by manipulating original signal
Fn=(-Nn/2:Nn/2-1)/Nn; %Frequency Plotting for normalizing
Fq=fs*Fn;
qa=fft(result);
qa=fftshift(qa);
plot(Fq,qa);
title('Frequency Plot after removing Noise');
%this is frequency plot for noisy signal i.e X1
subplot(5,1,4);
N1=length(X1);
Fa=(-N1/2:N1/2-1)/N1;
F1=Fa*fs;
Xa=fft(X1);
Xa=fftshift(X1);
plot(F1,Xa);
title('Frequency plot of X1');
OUTPUT WAVEFORMS:
9. FIR FILTER DESIGN USING WINDOW TECHNIQUES
In the design of FIR filters using any window technique, the
order can be calculated using the formula given by
N=
Where δp is the passband ripple, δs is the stopband ripple, fp is the
passband frequency, fs is the stopband frequency, Fs is the sampling
frequency.
(A) Rectangular Window
Algorithm
1.
2.
3.
4.
5.
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Get the sampling frequency
Calculate the order of the filter
Find the window coefficients using Equation
WR (n) = 1, for |n|≤
0, otherwise
6. Draw the magnitude and phase responses.
% Programforthedesignof FIRLowpass, Highpass,
Band pass and Bandstop filters using rectangular
window
clc;
clear all;
close all;
rp=input('enter the passband ripple');
rs=input('enter the stopband ripple');
fp=input('enter the passband freq');
fs=input('enter the stopband freq');
f=input('enter the sampling freq');
wp=2*fp/f;
ws=2*fs/f;
num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f;
n=ceil(num/dem); % Calculation of order of filter
n1=n+1;
if (rem(n,2)~=0)
n1=n;
n=n-1;
end
y=rectwin(n1); % Generation of the rectangular window
% low-pass filter
b=fir1(n,wp,y); % Finding FIR filter coefficients of order ‘n’, cutoff freq ‘wp’ and
rectangular window ‘y’
[h,o]=freqz(b,1,256); % Calculation of frequency resonse of the designed filter
m=20*log10(abs(h)); % Changing in dB
subplot(2,2,1);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
% high-pass filter
b=fir1(n,wp,'high',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,2);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(b) Normalised frequency -->');
% band pass filter
wn=[wp ws];
b=fir1(n,wn,y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,3);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(c) Normalised frequency -->');
% band stop filter
b=fir1(n,wn,'stop',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,4);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(d) Normalised frequency -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.05
enter the stopband ripple 0.04
enter the passband freq 1500
enter the stopband freq 2000
enter the sampling freq 9000
dem= 0.8111; num=13.9897; wp=0.3333; ws=0.4444
(B)
Blackman Window
Algorithm
5.
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Get the sampling frequency
Calculate the order of the filter
Find the window coefficients using Equation
6.
WR (n) = 0.42+ 0.5cos
1.
2.
3.
4.
+0.08cos
, for |n|≤
0, otherwise
7. Draw
the magnitude and phase responses.
% Programforthedesignof FIRLowpass, Highpass,
Band pass and Band stop digital filters using
Blackman window
clc;
clear all;
close all;
rp=input('enter the passband ripple');
rs=input('enter the stopband ripple');
fp=input('enter the passband freq');
fs=input('enter the stopband freq');
f=input('enter the sampling freq');
wp=2*fp/f;
ws=2*fs/f;
num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f;
n=ceil(num/dem);
n1=n+1;
if (rem(n,2)~=0)
n1=n;
n=n-1;
end
y=blackman(n1); % Geration of blackman window
% y=hamming(n1); % Geration of hamming window
% y=hanning(n1); % Geration of hanning window
% y=kaiser(n1,beta); % Geration of kaiser window
% low-pass filter
b=fir1(n,wp,y);
% Finding FIR filter coefficients of order ‘n’, cutoff freq ‘wp’ and
blackman window ‘y’. Particular window selection can be done here
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,1);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
% high-pass filter
b=fir1(n,wp,'high',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,2);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(b) Normalised frequency -->');
% band pass filter
wn=[wp ws];
b=fir1(n,wn,y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,3);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(c) Normalised frequency -->');
% band stop filter
b=fir1(n,wn,'stop',y);
[h,o]=freqz(b,1,256);
m=20*log10(abs(h));
subplot(2,2,4);
plot(o/pi,m);
ylabel('Gain in dB -->');
xlabel('(d) Normalised frequency -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.03
enter the stopband ripple 0.01
enter the passband freq 2000
enter the stopband freq 2500
enter the sampling freq 7000
dem= 1.0429; num=22.2288; wp=0.5714; ws=0.7143
(C) Filter response using HanningWindow
(D) Filter response using Hamming Window
(E)
Filter response using Kaiser Window
10. FIR FILTER DESIGN USING FREQUENCY SAMPLING METHOD
We assume that the frequency points and the corresponding
amplitude values are given as ‘fpts’and ‘mval’. If not
given, we need to find the amplitude values corresponding
to the frequency given
PROGRAM-
fpts = [0 0.28 0.3 0.5 0.52 1];
mval = [0.7 0.7 1.0 1.0 0.7 0.7];
M=31;
b = fir2(M,fpts,mval);
[h,omega] = freqz(b,1,512);
plot(omega/pi,abs(h));grid;
xlabel('\omega/\pi'); ylabel('Magnitude');
11. FIR FILTER DESIGN USING EQUIRIPPLE TECHNIQUE
Remez algorithm has been used to find extremas and
corresponding weighting function required. Using these
parameters FIR filter coefficients have been calculated
using equiripple method
PROGRAM-
format long
fedge = input('Band edges in Hz = ');
mval = input('Desired magnitude values in each band =
');
dev = input('Desired ripple in each band =');
FT = input('Sampling frequency in Hz = ');
[N,fpts,mag,wt] = remezord(fedge,mval,dev,FT);% Finding
extremas, freq poits, and wights ‘wt’ using Remez algorithm
b = firpm(N,fpts,mag,wt); % Finding filter coefficients
using the parameters found above
disp('FIR Filter Coefficients'); disp(b)
[h,w] = freqz(b,1,256);
plot(w/pi,20*log10(abs(h)));grid; o
xlabel('\omega/\pi'); ylabel('Gain, dB');
12. IIR FILTER DESIGN
As its known fact that digital IIR filters are designed by mapping from their
analog counterparts. Analog IIR filters are mapped through different mapping
functions to get the digital IIR filters. So, before going to design digital IIR
filers, we must be aware about the designing procedures of analog IIR filters. In
fact, MATLAB-based desiging of digital and analog IIR filters is quite similar.
So, first we will design analog IIR filters and then will go for digital IIR filter
designing.
(1) BUTTERWORTH ANALOG FILTERS
(A) Low Pass Filter
Algorithm
1. Get the passband and stopband ripples
2. Get the passband and stopband edge frequencies
3. Get the sampling frequency
4. Calculate the order of the filter using following Equation or using
command ‘buttord’
N=
5. Find the filter coefficients using command ‘butter’
6. Find the magnitude and phase responses using ‘freqs’ and ‘angle’.
7. Draw the magnitude and phase responses.
% Program for the design of Butterworth analog low pass filter
clc;
close all;
clear all;
format long
rp=input('enter the passband ripple'); % Ripple values must be in dB
rs=input('enter the stopband ripple');
fp=input('enter the passband freq'); % Passband freq should be in Hz
fs=input('enter the stopband freq'); % Stopband freq should be in Hz
Fs=input('enter the sampling freq'); % Sampling freq should be in Hz
w1= 2*pi* fp/Fs; %Calculation of normalized frequeny
w2= 2*pi* fs/Fs;
[n,wn]=buttord(w1,w2,rp,rs,'s'); % Calculation of filter order. Here,
frequencies are in normalized form between (0,1) and ripple values in dB. The last
parameter ‘s’ indicates that the filter is analog IIR filter and its absence in ‘buttord’
implies digital IIR filter.
[z,p,k]=butter(n,wn, 'low', 's'); % Caculates LP filter coefficients/zeros (z) and
poles (p) of a nth order analog butterworth filter
[b,a]=zp2tf(z,p,k); % In place of ‘zp2tf’, another command ‘tf’ can also be used
to get the transfer function corresponding to poles (p) and zeros (z)
w=0:.01:pi; % You may or may not pre-define frequency points
[h,om]=freqs(b,a,w); %Calculates continuous filter frequency response of the
filter corresponding to the filter coefficiets b, a. The command freqz is used to get
digital filter frequency response
m=20*log10(abs(h));
an=angle(h);
subplot(2,1,1);
plot(om/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
subplot(2,1,2);
plot(om/pi,an);
xlabel('(b) Normalised frequency -->');
ylabel('Phase in radians -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.15
enter the stopband ripple 60
enter the passband freq 1500
enter the stopband freq 3000
enter the sampling freq 7000
(B) High Pass Filter
Algorithm
1. Get the passband and stopband ripples
2. Get the passband and stopband edge frequencies
3. Get the sampling frequency
4. Calculate the order of the filter using Equation
N=
5. Find the filter coefficients
6. Draw the magnitude and phase responses.
% Program for the design of Butterworth analog high—pass filter
clc;
close all;
clear all;
format long
rp=input('enter the passband ripple');
rs=input('enter the stopband ripple');
fp=input('enter the passband freq');
fs=input('enter the stopband freq');
Fs=input('enter the sampling freq');
w1=2*pi*fp/Fs;
w2=2*pi*fs/Fs;
[n,wn]=buttord(w1,w2,rp,rs,'s');
[b,a]=butter(n,wn,'high','s'); % Write ‘bandpass’ and ‘stop’ for designing BP
and BS filters
w=0:.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
an=angle(h);
subplot(2,1,1);
plot(om/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
subplot(2,1,2);
plot(om/pi,an);
xlabel('(b) Normalised frequency -->');
ylabel('Phase in radians -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.2
enter the stopband ripple 40
enter the passband freq 2000
enter the stopband freq 3500
enter the sampling freq 8000
n=11; w1=0.5000; w2=0.8750; wn=0.5757
(2) CHEBYSHEV TYPE-1 ANALOG FILTERS
(A) Low Pass Filter
Algorithm
1.
2.
3.
4.
5.
6.
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Get the sampling frequency
Calculate the order of the filter.
Find the filter coefficients
Draw the magnitude and phase responses.
% Program for the design of Chebyshev Type-1 low-pass filter
clc;
close all;
clear all;
format long
rp=input('enter the passband ripple');
rs=input('enter the stopband ripple');
fp=input('enter the passband freq');
fs=input('enter the stopband freq');
Fs=input('enter the sampling freq');
w1=2*pi*fp/Fs;
w2=2*pi*fs/Fs;
[n,wn]=cheb1ord(w1,w2,rp,rs,'s');
[b,a]=cheby1(n,rp,wn,'s');
w=0:.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
an=angle(h);
subplot(2,1,1);
plot(om/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
subplot(2,1,2);
plot(om/pi,an);
xlabel('(b) Normalised frequency -->');
ylabel('Phase in radians -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.23
enter the stopband ripple 47
enter the passband freq 1300
enter the stopband freq 1550
enter the sampling freq 7800
n=13; w1=0.3333; w2=0.3974; wn=0.3333
(3) CHEBYSHEV TYPE-2 ANALOG FILTERS
(A) High Pass Filter
Algorithm
1. Get the passband and stopband ripples
2. Get the passband and stopband edge frequencies
3. Get the sampling frequency
4. Calculate the order of the filter.
5. Find the filter coefficients
6. Draw the magnitude and phase responses.
% Program for the design of Chebyshev Type-2 High pass analog filter
clc;
close all;
clear all;
format long
rp=input('enter the passband ripple...');
rs=input('enter the stopband ripple...');
fp=input('enter the passband freq...');
fs=input('enter the stopband freq...');
Fs=input('enter the sampling freq...');
w1=2*pi*fp/Fs;
w2=2*pi*fs/Fs;
[n,wn]=cheb2ord(w1,w2,rp,rs,'s');
[b,a]=cheby2(n,rs,wn,'high','s');
w=0:.01:pi;
[h,om]=freqs(b,a,w);
m=20*log10(abs(h));
an=angle(h);
subplot(2,1,1);
plot(om/pi,m);
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
subplot(2,1,2);
plot(om/pi,an);
xlabel('(b) Normalised frequency -->');
ylabel('Phase in radians -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.34
enter the stopband ripple 34
enter the passband freq 1400
enter the stopband freq 1600
enter the sampling freq 10000
n=12; w1=0.2800; w2=0.3200; wn=0.3141
(4) BUTTERWORTH DIGITAL IIR FILTERS
To get digital IIR filters, MATLAB uses ‘bilinear transformation’ (BLT) by
default at the backend for mapping from analog to digital domain. Though this
transformation is not visible, its happening at the algorithmic level. To
understand the mapping concept, we will dsign a digital IIR filter manually
using BLT mapping at the end.
(A) Lowpass Filter
Algorithm
1.
2.
3.
4.
5.
6.
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Get the sampling frequency
Calculate the order of the filter .
Find the filter coefficients
Draw the magnitude and phase responses.
% Program for the design of Butterworth low pass digital filter
Design of Digital IIR Butterworth Filter using default
transformation technique. The command ‘butter’ uses BLT
mapping at the backend
Fs=2000;
Wp=2*pi*200/Fs;
Ws=2*pi*300/Fs;
Rp=1.25;
Rs=15;
% Wp = input('Normalized passband edge = ');
% Ws = input('Normalized stopband edge = ');
% Rp = input('Passband ripple in dB = ');
% Rs = input('Minimum stopband attenuation = ');
[N,Wn] = buttord(Wp, Ws, Rp, Rs);
[b,a] = butter(N,Wn,'low');
[h,omega] = freqz(b,a,256);
gain = 20*log10(abs(h));
plot (omega/pi,gain);grid;
xlabel('\omega/\pi'); ylabel('Gain, dB');
title('IIR Butterworth Filter');
ylabel('Gain in dB -->');
xlabel('(a) Normalised frequency -->');
subplot(2,1,2);
plot(om/pi,an);
xlabel('(b) Normalised frequency -->');
ylabel('Phase in radians -->');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.5
enter the stopband ripple 50
enter the passband freq 1200
enter the stopband freq 2400
enter the sampling freq 10000
n=8; w1=0.2400; w2=0.4800; wn=0.2730
% Design of Digital IIR Butterworth Filter using bilinear transformation
technique (manually)
clc;clear all; close all;
%% Input the filter specifications
Wp=0.3*pi;
Ws=0.8*pi;
Ap=1;
As=40;
T=1; % sampling interval
%% Calculation of filter order and filter coefficients
[N,Wc] = buttord(Wp,Ws,Ap,As,'s');
[b,a]=butter(N,Wc,'low','s');
Hs=tf(b,a) % Find corresponding transfer function
[b_d,a_d]=bilinear(b,a,1/T); % Map the analog filter
coeffiecients (b,a) from analog to digital using BLT
Hz=tf(b_d,a_d,1/T) % Digital IIR filter transfer function
%w=0:.01:pi;
[Hw,omega]=freqz(b_d,a_d,512);% Get the digital filter
grequency response corresponding to digital filter
coefficients (b_d, a_d)
gain = 20*log10(abs(Hw));
plot (omega,gain);grid;
xlabel('\omega/\pi'); ylabel('Gain, dB');
title('IIR Butterworth Filter');
(5) CHEBYSHEV TYPE-1 DIGITAL FILTERS
(A) Lowpass Filter
Algorithm
1.
2.
3.
4.
5.
6.
Get the passband and stopband ripples
Get the passband and stopband edge frequencies
Get the sampling frequency
Calculate the order of the filter.
Find the filter coefficients
Draw the magnitude and phase responses.
% Program for the design of Chebyshev Type-1 lowpass digital filter
% Design of Digital IIR Type 1 Chebyshev Filter
% using default transformation technique
Wp = input('Normalized passband edge = ');
Ws = input('Normalized stopband edge = ');
Rp = input('Passband ripple in dB = ');
Rs = input('Minimum stopband attenuation in dB = ');
[N,Wn] = cheb1ord(Wp,Ws,Rp,Rs);
[b,a] = cheby1(N,Rp,Wn,'low');
[h,omega] = freqz(b,a,256);
plot (omega/pi,20*log10(abs(h)));grid;
xlabel('\omega/\pi'); ylabel('Gain, dB');
title('Type I Chebyshev lowpass Filter');
OUTPUT WAVEFORMS:
RESULT:
enter the passband ripple 0.2
enter the stopband ripple 45
enter the passband freq 1300
enter the stopband freq 1500
enter the sampling freq 10000
n=13; w1=0.2600; w2=0.3000; wn=0.2600
Download