matlab lab manual
TRANSCRIPT
MATLAB EXPERIMENTS 36
1 FAMILIARIZATION OF MATLAB 37
2 LINEAR CONVOLUTION 50
3 CIRCULAR CONVOLUTION 53
4 DISCRETE FOURIER TRANSFORM AND INVERSE DFT 56
5 FIR LOW PASS FILTER DESING USING HAMMING WINDOW
58
6 IIR LOW PASS BUTTERWORTH FILTER 62
7 IIR HIGH PASS CHEBYSHEV TYPE 1 FILTER 65
MATLAB EXPERIMENTS
36
EXPERIMENT NO: 1
FAMILIARIZATION OF MATLAB
AIM
To familiarize the MATLAB environment and the basic commands and functions
THEORY
MATLAB (MATrix LABoratory) is matrix-based software package for
computation in engineering, Science and applied mathematics. It offers a powerful
programming language, excellent graphics, and a wide range of expert knowledge. A
numerical analyst called Cleve Moler wrote the first version of MATLAB in the 1970s.
MATLAB is published by and a trademark of The Math Works Inc. The focus in
MATLAB is on computation, not mathematics.
MATLAB is a high-performance language for technical computing. It integrates
computation, visualization, and programming in an easy-to-use environment where
problems and solutions are expressed in familiar mathematical notation. Typical uses
include
•Math and computation
•Algorithm development
•Data acquisition
•Modeling, simulation, and prototyping
•Data analysis, exploration, and visualization
•Scientific and engineering graphics
•Application development, including graphical user interface building.
MATLAB is an interactive system whose basic data element is an array
that does not require dimensioning. This allows you to solve many technical computing
problems, especially those with matrix and vector formulations, in a fraction of the time it
would take to write a program in a scalar no interactive language such as C or
FORTRAN. It provides s an interactive environment with hundreds of built in functions
for technical computation and graphics.
1. TOOLBOXES
MATLAB features a family of add-on application-specific solutions called
toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and
apply specialized technology. Toolboxes are comprehensive collections of MATLAB
37
functions (M-files) that extend the MATLAB environment to solve particular classes of
problems. Areas in which toolboxes are available include signal processing, control
systems, neural networks, fuzzy logic, wavelets, simulation, and many others.
2. MATLAB SYSTEM
The MATLAB system consists of five main parts:
2.1 Development Environment. This is the set of tools and facilities that help you use
MATLAB functions and files. Many of these tools are graphical user interfaces. It
includes the MATLAB desktop and Command Window, a command history, an editor
and debugger, and browsers for viewing help, the workspace, files, and the search path.
2.2 The MATLAB Mathematical Function Library. This is a vast collection of
computational algorithms ranging from elementary functions, like sum, sine, cosine, and
complex arithmetic, to more sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier transforms.
2.3 The MATLAB Language. This is a high-level matrix/array language with control
flow statements, functions, data structures, input/output, and object-oriented
programming features. It allows both “programming in the small” to rapidly create quick
and dirty throw-away programs, and “programming in the large” to create large and
complex application programs.
2.4 Graphics. MATLAB has extensive facilities for displaying vectors and matrices as
graphs, as well as annotating and printing these graphs. It includes high-level functions
for two-dimensional and three-dimensional data visualization, image processing,
animation, and presentation graphics. It also includes low-level functions that allow you
to fully customize the appearance of graphics as well as to build complete graphical user
interfaces on your MATLAB applications.
2.5 The MATLAB Application Program Interface (API). This is a library that allows
you to write C and FORTRAN programs that interact with MATLAB. It includes
facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.
38
3. STARTING UP MATLAB
Start MATLAB by double clicking on the MATLAB icon that should be on the
desktop of your computer. This brings up the window called the Command Window.
This window allows a user to enter simple commands. To perform a simple computations
type a command and next press the Enter or Return key. The Matlab prompt is >>.
3.1 M-files
MATLAB can execute a sequence of statements in a file. Such files are called “M-files”
There are two types of M-files: script files and function files.
Steps to create M-Files
1. In the command window click ‘file’ menu, click ‘New’, click ‘.m files’. Now the
edit menu will be displayed
2. Type the program and save it with a file name. e.g. myprogram.m
Running the program depends on the type of M-file, i.e. whether it is a script file or
function file.
3.2 Script files
A script file consists of a sequence of normal MATLAB statements.
To run the program, click ‘debug’ menu and click ‘run’ or return to command
window and enter the file name at the command prompt and press enter key.
3.3 Function files
User can create new functions specific to the problem, which will then have the same
status as other MATLAB functions. Variables in a function files are by default local,
otherwise need to be declared as “global”. The function file will start with function
[y1, y2, ..] = Function Name (x1, x2, …)
To run the function files, enter ‘[y1, y2, ..] = Function Name (x1, x2, …)’ and
give all input parameters, i.e. x1,x2.
39
4. BASIC COMMANDS IN MATLAB
4.1 On-Line Help Commands
help Lists on which help is available
helpwin opens the interactive help window
help topic provide help on topic
lookfor string lists help topic containing string
demo runs the demo program
4.2 Workspace Information
who Lists the variable currently in the workspace
whos lists the variable currently in the workspace with their size
clear clear the workspace, all variables are removed
clear x y z clears only variables x, y and z
close all close all the graphic windows, which are open
clc clears command window
home same as clc
clf clear figure window
4.3 Directory information
pwd shows the current working directory
cd changes the current working directory
dir lists the contents of current directory
is same as dir
path gets or sets MATLAB search path
editpath modify MATLAB search path
copyfile copies a file
mkdir creates a directory
4.4 General information
computer tells you the computer type you are using
clock gives you wall clock time and date as vector
date tells you date as a string
more controls the paged output according to the screen size
40
4.5 Termination
^C (Control+C) local abort kills the current command execution
quit quits MATLAB
exit same as quit
Notes:
When writing a long MATLAB statement that exceeds a single row use “...” to
continue statement to next row.
When using the command line, a ";" at the end means MATLAB will not display
the result. If ";" is omitted then MATLAB will display result.
Use the up-arrow to recall commands without retyping them (and down arrow to
go forward in commands).
The symbol "%" is used in front of a comment.
5. MATLAB PROGRAMMING
Functions and Operators in MATLAB
5.1 Operators
+ addition- subtraction* matrix multiplication^ power‘ transpose\ left division/ right division
Operators used for arrays.* term by term multiplication./ term by term left division.^ term by term exponentiation.\ term by term right division
Relational Operators
The relational operators in MATLAB are< less than> greater than<= less than or equal>= greater than or equal= = equal~= not equal.
Note that “=" is used in an assignment statement while “= =" is used in a relation.Logical Operators
& and
| or
41
~ notxor exclusive or
5.2 Functions
Basic functions
Elementary math functions
abs absolute value or complex magnitude
angle phase angle
sqrt square root
real real part
imag imaginary part
conj complex conjugate
gcd greatest common divisor
lcm least common multiple
round round to nearest integer
fix round toward zero
floor round the nearest integers less than or equal to the input
ceil round toward 1
sign signum function
rem remainder
exp exponential base e
log natural logarithm
log10 log base 10
Commonly used programming functions
input prompt for user inputkeyboard invoke keyboard as if it were a script _lemenu generate menu of choices for user inputpause waits for user responsefunction define functioneval execute string with MATLAB expressionfeval evaluate function speci_ed by stringglobal define global variablessave saving a variable valueload loading a variable from the specified location.
Commonly used Signal Processing Functions
abs complex magnitude
42
angle phase angle
conv convolution and polynomial multiplication
deconv deconvolution and polynomial division
corrcoef correlation coefficients
cov covariance matrix
filter one-dimensional digital filter
filter2 two-dimensional digital filter
unwrap remove phase angle jumps across 360_ boundaries
nextpow2 next higher power of 2
fft radix-2 fast Fourier transform
fft2 two-dimensional FFT
ifft inverse fast Fourier transform
ifft2 inverse 2-D FFT
fftshift zero-th lags to center of spectrum
circshift circularly shifting the vector by points specified by user
fir1 one dimensional FIR filtering
buttord order of butterworth filter
buttord coefficients of butterworth filter response
chebyord order of chebyshev type 1 filter
chebyord1 coefficients of chebyshev filter response
freqz convert to frequency domain from time doamain
Functions for building matrices
eye identity matrixzeros matrix of zerosones matrix of onesdiag diagonal matrixtriu upper triangular part of a matrixtril lower triangular part of a matrixrand randomly generated matrix
Matrix functions
svd singular value decompositioninv inversedet determinantsize sizenorm 1-norm, 2-norm, F-norm
43
cond condition number in the 2-normrank rankmax maximum value in each columnmin minimum value in each column
Few other functions are: sort, sum, prod, mean, std, any, all.
Basic Matrix operations Creating Matrix
A=[1 2 5; 3 9 0]
Transpose of Matrix=A’
Appending row :
If B =[4 7 9]
[A;B]=
Appending Column
If B=
[A B]=
Deleting a row or column
A(2,:)=[] deletes the second row of matrix
A(:,3:2)=[] deletes the third row and second column
Create an empty matrix
A=[ ];
44
6.CONDITIONAL STATEMENTS
In their basic forms, these MATLAB flow control statements operate like those in
most computer languages.
6.1 For.
The general form of a for loop is
for variable_name=initial_valu e: increment/decrement term : final_value
statements
end
For example:
(1) for a given n, the statement
x = []; for i = 1:n, x=[x,i^2], end
or
x = [];
for i = 1:n
x = [x,i^2]
end
will produce a certain n-vector.
(2) The statements
for i = 1:m
for j = 1:n
H(i, j) = 1/(i+j-1);
end
end
H
will produce and print to the screen the m-by-n hilbert matrix. The semicolon on the inner
statement is essential to suppress printing of unwanted intermediate results while the last
H displays the final result.
Note: The for statement permits any matrix to be used instead of 1:n. The variable just
consecutively assumes the value of each column of the matrix.
45
6.2 While
The general form of a while loop is
while relation
statements
end
The statements will be repeatedly executed as long as the relation remains true. For
example, for a given number a, the following will compute and display the smallest
nonnegative integer n such that 2n >=a:
n = 0;
while 2^ n < a
n = n + 1;
end
n
6.3 If
The general form of a simple if statement is
if relation
statements
end
The statements will be executed only if the relation is true. Multiple branching is also
possible, as is illustrated by
if n < 0
parity = 0;
elseif rem(n,2) == 0
parity = 2;
else
parity = 1;
end
In two-way branching the elseif portion would, of course, be omitted.
46
7. GRAPHICS.
MATLAB can produce planar plots of curves, 3-D plots of curves, 3-D mesh surface
plots, and 3-D faceted surface plots. The primary commands for these facilities are plot,
plot3, mesh, and surf, respectively. An introduction to each of these is given below.
Planar plots.
The plot command creates linear x-y plots; if x and y are vectors of the same length, the
command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x
versus the elements of y.
For Example:
To draw the graph of the sine function
over the interval -4 to 4 with the following commands:
x = -4:.01:4; y = sin(x); plot(x,y)
The graphs can be given titles, axes labeled, and text placed within the graph with the
following commands which take a string as an argument.
title graph title
xlabel x-axis label
ylabel y-axis label
gtext place text on the graph using the mouse
text position text at specified coordinates
grid place grid lines on the current graph.
By default, the axes are auto-scaled. This can be overridden by the command axis. Some
features of axis are:
axis([xmin,xmax,ymin,ymax]) set axis scaling to prescribed limits
axis(axis) freezes scaling for subsequent graphs
axis auto returns to auto-scaling
v= axis returns vector v showing current scaling
axis square same scale on both axes
axis equal same scale and tic marks on both axes
axis off turns off axis scaling and tic marks
axis on turns on axis scaling and tic marks
47
The axis command should be given after the plot command.
Two ways to make multiple plots on a single graph are illustrated by
x=0:.01:2*pi;y1=sin(x);y2=sin(2*x);y3=sin(4*x);plot(x,y1,x,y2,x,y3)
and by forming a matrix Y containing the functional values as columns
x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)
Another way is with hold. The command hold on freezes the current graphics screen so
that subsequent plots are superimposed on it. The axes may, however, become rescaled.
Entering hold off releases the “hold."
One can override the default linetypes, pointtypes and colors. For example,
x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);
plot(x,y1,'--',x,y2,':',x,y3,'+')
renders a dashed line and dotted line for the first two graphs while for the third the
symbol + is placed at each node.
The line- and mark-types are
Linetypes: solid (-), dashed (--). dotted (:), dashdot (-.)
Marktypes: point (.), plus (+), star (*), circle (o), x-mark (x)
Colors can be specified for the line- and mark-types.
Colors: yellow (y), magenta (m), cyan (c), red (r), green (g), blue (b), white (w),
black (k)
For example, plot(x,y,'r--') plots a red dashed line.
The command subplot can be used to partition the screen so that several small plots can
be placed in one figure. Other specialized 2-D plotting functions are:
polar, bar, hist, quiver, compass, feather, rose, stairs, fill
Another plot functions are
stem plot the discrete signals
mesh three dimensional wire mesh surface plots
RESULT
Familiarized the basic functions and commands in MATLAB.
48
MATLAB PROGRAMS
49
EXPERIMENT NO:2
LINEAR CONVOLUTION
AIM:
To find out the linear convolution output of two sequences and plot the input and
out put sequences in single figure.
THEORY
In signal processing, the output of LTI system is found out using the convolution
operation. Here the discrete time signals are under consideration. Consider two sequences
x1(n) and x2(n) and let m = length(x1) and l = length(x2). Then z(n) is the vector of
length m+l-1
And whose rth element is
The sum is over all the values of j which lead to legal subscripts for x1(j) and
x2(k+1-j), specifically j = max(1,k+1-n): min(k,m). When m = n, this gives
z(1) = x1(1)*x2(1)
z(2) = x1(1)*x2(2)+x1(2)*x2(1)
z(3) =x1(1)*x2(3)+x1(2)*x2(2)+x1(3)*x2(1)
...
z(n) = x1(1)*x2(n)+x1(2)*x2(n-1)+ ... +x1(n)*x2(1)
...
z(2*n-1) = x1(n)*x2(n)
The following function can be used to compute the convolution of two sequences.
w = conv(x1,x2) convolves vectors x1 and x2. Algebraically, convolution is the same
operation as multiplying the polynomials whose coefficients are the elements of x1 and
x2.
50
ALGORITHM
1. Get the two sequences
2. Get the starting time of two sequences
3. Find out the length of input sequences
4. Calculate the starting time of output sequences
5. Calculate the length of output sequence
6. Find out the convolution using the inbuilt function.
7. Plot all the sequences using stem function and make it in a single figure using
subplot function.
PROCEDURE
1. Program is written in the edit window
2. The program file is saved as an M-file and executed.
3. For the case of errors they are rectified
4. The sequence plotes are obtained and output verified.
PROGRAM
%program to find the linear convolution of two sequences%%*********************************************************% clc;close all; clear all;x1=input('enter the first sequence');%input the first sequencet1=input('enter the starting time of first seqence');%input the starting time of first sequencex2=input('enter the second sequence');%input the second sequencet2=input('enter the starting time of second sequence');%input the starting time of second sequencel1=length(x1);%calculate the number of elements in 1st sequencel2=length(x2);%calculate the number of elements in 2nd sequence %plot the first sequence using stem functionsubplot(3,1,1);a=t1+l1-1;x=t1:1:a;stem(x,x1),grid on;ylabel('amplitude----->');xlabel('time----->');title('The first sequence'); %plot the second sequence using stem functionsubplot(3,1,2);b=t2+l2-1;y=t2:1:b;stem(y,x2),grid on;ylabel('amplitude----->');
51
xlabel('time----->');title('The second sequence'); l=l1+l2-1;%length of output sequencet=t1+t2;%starting time of output sequencen=t:1:l+t-1;%time instances of output sequencez=conv(x1,x2);%convovolution of the two input sequences %plot the output sequence using stem functionsubplot(3,1,3);stem(n,z),grid on;ylabel('amplitude----->');xlabel('time----->');title('convolved output'); %sample input% enter the first sequence[ 1 3 5 7 8 1 ]% enter the starting time of first seqence-2% enter the second sequence[3 5 7 1 7]% enter the starting time of second sequence-2
RESULT
The convolution between two sequences was computed and result plotted.
WAVEFORMS
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5 30
5
10
ampl
itude
----->
time----->
The first sequence
-2 -1.5 -1 -0.5 0 0.5 1 1.5 20
5
10
ampl
itude
----->
time----->
The second sequence
-4 -3 -2 -1 0 1 2 3 4 50
50
100
150
ampl
itude
----->
time----->
convolved output
52
EXPERIMENT NO:3
CIRCULAR CONVOLUTION
AIM:
To find out the circular convolution output of two sequences and plot the input
and out put sequences in single figure.
THEORY
In circular convolution or periodic convolution one of the sequences should be
periodic. Circular convolution operation that contains circular shift operation is called
circular convolution. Circular convolution of two sequences X1(n) and X2(n) each
having a length of N is given by
0≤m≤N-1
The circular convolution output is also an N-point sequence. If the length of
sequences is not equal sufficient number of zeros must be added to it.
Here Matrix multiplication method is used to perform circular convolution.The
circular shifting is done using the function circshift().
ALGORITHM
1. Get the input sequences and their length.
2. If the length are not equal make the shorter sequence length equal to
longer sequence by appending zeros.
3. Perform the circular convolution us ing matrix multiplication method.
4. Plot the input and output sequences
PROCEDURE
1. Write the program and save it with a name and extension .m
2. After running the program, enter the sequences.
3. Observe the result and verify.
53
PROGRAM
%program to find the circular convolution of two sequences%%%************************************************************% clc; close all; clear all;x1=input('enter the first sequence');% input the first sequencel1=length(x1);%find out the no:of elementsx2=input('enter the second sequence');%input the second sequencel2=length(x2);%find out the no:of elements %making the length of both sequence equal by appending zeros to shorter sequence. l=max(l1,l2);X1=[x1,zeros(l-l1)];% appending l-l1 zeros by creating all zero row matrix X2=[x2,zeros(1,l-l2)]; %appending l-l2 zeros by creating all zero row %circular convolution is done by matrix multiplication methodX1=X1';%taking the transpose to make the row vector to column vectorsh=X1;for i=1:1:l-1 X1=[X1 circshift(sh,i)];%circular shifting and the column vector and %append to the existing matrix to create an l*l matrix end X2=X2';%take the transpose of 2nd sequence.y=(X1*X2)';% multily X2' with the matrix whose columns are the circular %shifted versions of X1 %plot the input and output sequences using stem functiont1=0:1:l1-1;subplot(3,1,1);stem(t1,x1),grid on;ylabel('amplitude----->');xlabel('time----->');title('The first sequence'); t2=0:1:l2-1;subplot(3,1,2);stem(t2,x2),grid on;ylabel('amplitude----->');xlabel('time----->');title('The second sequence'); n=0:1:l-1subplot(3,1,3);stem(n,y),grid on;ylabel('amplitude----->');xlabel('time----->');title('convolved output'); %sample input% enter the first sequence[1 3 5 7]% enter the second sequence[3 8]
54
RESULT
Circular convolution between the two sequences was performed and the sequences plotted.
WAVEFORMS
0 0.5 1 1.5 2 2.5 30
5
10
ampl
itude
----->
time----->
The first sequence
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 10
5
10
ampl
itude
----->
time----->
The second sequence
0 0.5 1 1.5 2 2.5 30
50
100
ampl
itude
----->
time----->
convolved output
55
EXPERIMENT NO:4
DISRETE FOURIER TRANSFORM AND INVERSE DFT
AIM
1. To compute N- point DFT for a given sequence and plot the magnitude and phase spectrum.
2. To compute the IDFT of the computed DFT sequence, to reconstruct the original signal.
THEORY
DFT stands for Discrete Fourier Transform. It is used to find amplitude and phase spectrum of discrete time signal. The function fft(x) and ifft(x) are used for finding DFT and IDFT of a sequence (x). DFT is complex quantity. Magnitude and phase spectrum of the sequence can be obtained using abs and angle functions.
ALGORITHM
1. Input the sequence.2. Find the DFT3. Find the magnitude and phase part of DFT4. Find the IDFT of the DFT sequence to reconstruct the original input5. Plot the amplitude spectrum, phase spectrum and IDFT.
PROCEDURE
1. Write the program and save the file with a name and extension .m2. After executing the program, enter the sequence.3. Observe the result and verify.
PROGRAM
%program to find the N-point DFT and IDFT of sequences%%***********************************************%close all;clear all;clc; x=input('enter the first sequence');%input the first sequenceN=input('Input the length of DFT sequence');% the value of N in N-point DFT %plotting the input siganlsubplot(2,2,1),stem(x),grid on;title('Input signal')xlabel('time----->')ylabel('amp----->') a=fft(x,N); %find out the DFT of the sequenecemag=abs(a); % computing magnitude part of each DFT valuephase=(angle(a))*180/pi;% computing phase part of each DFT value %magnitude plot
56
subplot(2,2,2),stem(mag),grid on;title('Magnitude part of DFT'); xlabel('time----->');ylabel('amp----->')
%phase plotsubplot(2,2,3),stem(phase),grid on;title('phase part of DFT'); xlabel('time----->'); ylabel('amp----->');
b=ifft(a,N); % performing the IDFT of the computed DFT to reconstruct the original signal%Plot the reconstructed sequence subplot(2,2,4),stem(b),grid on;title('IDFT-the reconstructed input sequence'); xlabel('time----->')ylabel('amp----->') %sample input % enter the first sequence[2 3 4 1 2 3 4]% Input the length of DFT sequence8
RESULT1. DFT of the given sequence was performed and the magnitude and phase.
Spectrum computed and plotted. 2. IDFT of the computed DFT sequence was performed to reconstruct the original signal and IDFT was plotted.
WAVEFORMS
1 2 3 4 5 6 70
1
2
3
4Input signal
time----->
amp-
----
>
1 2 3 4 5 6 7 80
5
10
15
20Magnitude part of DFT
time----->
amp-
----
>
1 2 3 4 5 6 7 8-200
-100
0
100
200phase part of DFT
time----->
amp-
----
>
1 2 3 4 5 6 7 80
1
2
3
4IDFT-the reconstructed input sequence
time----->
amp-
----
>
57
EXPERIMENT NO:5
FIR LOW PASS FILTER DESIGN USING HAMMING WINDOW
AIM
To design a lowpass FIR filter Using hanning window and plot the magnitude and
phase responses.
THEORY
fir1 and fir2 are the two functions used for the window based filter design. The
function ‘fir1’ is used to design one dimensional conventional LPF, HPF, BPF and band
stop filter.
The operation of an FIR filter is governed by a linear constant coefficient difference
equation of non recursive nature.
They have the following properties
(1) They have finite memory and the transient start up is of finite duration
(2) They are always BIBO stable
(3) They can realize a desired magnitude response with exactly linear phase response.
The following MATLAB functions are used in the design of FIR filters.
b=fir1(N,Wn,’low’)
It designs an Nth order lowpass FIR digital filter and returns the filter coefficients in
vector b having length N+1. The cut off frequency ωn must be between 0<ωn<1.0 with
1.0 corresponding to half the sampling rate. The filter coefficients b is real and filter has
linear phase. The normalized gain of the filter at ωn is -6dB.
b=fir1(N,Wn,’ftype’,W) returnes the coefficients of the filter specified by ‘ftype’
using the window specifiedby W. W is the window impulse response have length N+1. If
the window type is not specified, fir1 uses hamming window of length N+1. If the filter
type is not specified the function design a low pass filter in default. For BPF and BSF,
Wn=[W1,W2], where W1 and W2 will be the upper and lower cut off frequencies. The
response of window can be calculated using the functions given below
58
1. W=WINDOW (W_NAME,N)
It returns an N-point window of type specified by the function handle W_NAME in a
column vector and stored it in variable W
2. There is individual built in functions are there in MATLAB for each window.
rectwin(N) N point rectangular window
hann(N) N point symmetric hanning window
hamm(N) N point symmetric hamming window
blackman(n) N point rectangular window
The fuinction used to find the frequency response from the filter coefficient and order
is [h,w]=freqz(b,a,N)
It returns the N-point complex frequency response vector H and the N-point frequency
vector w in radians/sample of the filter.The frequency response is given by
Given numerator and denominator coefficients in vector b and a.The frequency response is evaluated at N points equally spaced around the upper half the unit circle.The default value is 512.The other functions used in filter design problem are,CEIL(X)
It rounds the elements of x to the nearest integers towards infinityREM(x,y)
Function returns the value of remainder after division. Remainder (x,y) is x-n*y where n=fix(x/y) if Y!=0.If y is not an integer, and the coefficient x/y is within the round off errors of an integer then n is that integer. Rem(x,y) and mod(x,y) are equal if x and y have same sign.
ALGORITHM
1. Get the pass band, stop band and sampling frequency2. Determine FIR filter coefficients using desired window3. Determine frequency response using the FREQZ function4. Calculate amplitude and phase response using the frequency response5. Plot all of them graphically
PROCEDURE1. Write the program and save it with a name and extension .m2. After running the program substitute values lowpass 3. Observe the result and verify.
59
PROGRAM
%program to design an FIR low pass filter%%*********************************************************% close all; clear all; clc;fp=input('Enter the pass band frequency');%pass band frequencyfs=input('Enter the stop band frequency');%stop band frequencyf=input('enter the sampling frequency');%sampling frequencyrp=input('Enter the pass band ripple');%pass band ripplers=input('Enter the stop band attenuation');%stop band attenuation %calculation of the filter ordernum=-20*log10(sqrt(rp*rs))-13;dem=14.6*(fs-fp)/f;n=ceil(num/dem); %normalization of frequencies and calculation of cut off frequencieswp=2*fp/f;ws=2*fs/f;wn=(wp+ws)/2; %display the normalized frequencies and cut off frequencydisp('The normalized frequencies are')wpwsdisp('cut off frequency');wn %the order of window must be an odd number and the order of filter must %be one less than that of windowif(n/2==0) m=n+1;else m=n; n=n-1;end %the winodw sequence calculation. Here used hanning windowW = hann(m); b = fir1(n,wn,'low',W);%filter coefficient calculation. If the keyword %is ‘high’ then we can design a high pass filter with the same %specifiacatin. %calculation of frequency response and plot the magnitude and phase%responsesfreqz(b,1,n);title('The magnitude and phase response')
%sample input % Enter the pass band frequency1000% Enter the stop band frequency1200% enter the sampling frequency3000% Enter the pass band ripple.02% Enter the stop band ripple.03
60
% The normalized frequencies are% % wp = % 0.6667% % ws = % 0.8000% % cut off frequency% % wn =% 0.7333
RESULT
A FIR filter having lowpass characteristics has been designed using hanning window and the frequency responses were plotted
FREQUENCY RESPONSE
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-2000
-1500
-1000
-500
0
Normalized Frequency ( rad/sample)
Pha
se (d
egre
es)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-100
-80
-60
-40
-20
0
20
Normalized Frequency ( rad/sample)
Mag
nitu
de (d
B)
FIR filter....The magnitude and phase response
61
EXPERIMENT NO:6
IIR LOWPASS BUTTERWORTH FILTER
AIM
To design and find the frequency response of an IIR low pass filter, having
Butterworth characteristics. Plot the magnitude and phase response.
THEORY
IIR filter design involves two steps. In the first step, the filter order N, and the
frequency scaling factor ωn are determined from the given specifications. Using these
parameters and the specified ripple level, the coefficients of the transfer function are then
determined.
The following function can be used to determine the order N and frequency
scaling factor Wn.
[N,Wn]=buttord (Wp,Ws,Rp,Rs);
, where wp and Ws are the normalized pass band and stop band edge frequencies
respectively. For lowpass filter, Wp < Ws. These frequency points must be between 0
and 1 because the sampling frequency is normalized to 2. If the sampling frequency f,
pass band edge frequency fp and stop band edge frequency fs specified in Hz, then
Wp=2fp/f and Ws=2fs/f. The other two parameters Rp and Rs, are pass band ripple and
minimum stop attenuation specified in dB, respectively. This function returns the order of
the filter N
The function [b,a] = butter(n,Wn,'ftype','s') is to find out the filter coefficient.
The keyword 'ftype', is to specify the filter type. If it is not specified a low pass filter will
be designed. The function returns the numerator and denominator coefficients of the filter
transfer function, b and a. For BPF and BSF, Wn=[W1,W2], where W1 and W2 will be
the upper and lower cut off frequencies
Frequency response of the filter is computed using the function
[h,w]=freqz(b,a,n). It generates an n-point complex vector frequency response samples
from which magnitudes and phase response samples can be readily computed. The
function freqz(b,a) plot the magnitude and frequency response directly.
Butterworth filters sacrifice rolloff steepness for monotonicity in the pass- and
stopbands. Unless the smoothness of the Butterworth filter is needed, an elliptic or
62
Chebyshev filter can generally provide steeper rolloff characteristics with a lower filter
order. For Chebyshev filter design, the functions are [n,Wn] = cheb1ord(Wp,Ws,Rp,Rs)
and [b,a] = cheby1(n,Rp,Wn,'ftype','s').
ALGORITHM
1. Get the pass band ripple and stop band attenuation
2. Get the pass band and stop band edge frequencies
3. Get the sampling frequency
4. Calculate the orders and frequency scaling factor
5. Find the filter coefficients
6. Plot the magnitude and phase responses
PROCEDURE
1. Program is written in the edit window
2. The program file is saved as an M-file and executed.
3. For the case of errors they are rectified
4. The graphical responses are obtained and output verified.
PROGRAM
%program to design an IIR butterworth low pass filter %%*****************************************************% close all; clear all; clc;fp=input('Enter the pass band frequency');%pass band frequencyfs=input('Enter the stop band frequency');%stop band frequencyf=input('enter the sampling frequency');%sampling frequencyRp=input('Enter the pass band ripple');%pass band rippleRs=input('Enter the stop band ripple');%stop band ripple %normalization of frequencies disp('normalized frequencies are')Wp=2*fp/fWs=2*fs/f %calculation of filter order and cut off frequencydisp('the order of filter and cut off frequencies are')[n,Wn] = buttord(Wp,Ws,Rp,Rs) [b,a] = butter(n,Wn,’low’);%filter coefficient calculation%calculation of frequency response and plot the magnitude and phase%responsesfreqz(b,a,n), title('IIR filter response--magnitude and phase responses'); % sample input% Enter the pass band frequency1000% Enter the stop band frequency1200
63
% enter the sampling frequency3000% Enter the pass band ripple4% Enter the stop band ripple50% normalized frequencies are% % Wp =% 0.6667% % Ws =% 0.8000 % the order of filter and cut off frequencies are% % n =% 10 % % Wn =% 0.6665
RESULT
An IIR Butterworth low pass filter has been designed the frequency responses
were plotted
FREQUENCY RESPONSE
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-1000
-800
-600
-400
-200
0
Normalized Frequency ( rad/sample)
Pha
se (d
egre
es)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-300
-250
-200
-150
-100
-50
0
Normalized Frequency ( rad/sample)
Mag
nitu
de (d
B)
IIR filter response--magnitude and phase responses
64
EXPERIMENT NO:7
IIR HIGH PASS CHEBYSHEV TYPE 1 FILTER
AIM
To design and find the frequency response of an IIR high pass filter, having
chebyshev type1 characteristics. Plot the magnitude and phase response.
THEORY
The IIR filter has much lower order than the corresponding FIR filter
which has same responses. But IIr filters have nonlinear phase, so data processing within
MATLAB is commenly performed ‘off-line.’ That is entire data sequence is available
prior to filtering. this allows for a non causal zero phase filtering approach, which
eliminates the linear phase distortion of IIR filter.
[n,Wn] = cheb1ord(Wp,Ws,Rp,Rs) returns the lowest order n of the Chebyshev
Type I filter that loses no more than Rp dB in the passband and has at least Rs dB of
attenuation in the stopband. The scalar (or vector) of corresponding cutoff frequencies
Wn, is also returned. Use the output arguments n and Wn with the cheby1 function.
cheby1 designs lowpass, bandpass, highpass, and bandstop digital and analog
Chebyshev Type I filters. Chebyshev Type I filters are equiripple in the passband and
monotonic in the stopband. Type I filters roll off faster than type II filters, but at the
expense of greater deviation from unity in the passband.
[b,a] = cheby1(n,Rp,Wn) designs an order n Chebyshev lowpass digital
Chebyshev filter with normalized cutoff frequency Wn and Rp dB of peak-to-peak ripple
in the passband. It returns the filter coefficients in the length n+1 row vectors b and a,
with coefficients in descending powers of z. Normalized cutoff frequency is the
frequency at which the magnitude response of the filter is equal to -Rp dB. For cheby1,
the normalized cutoff frequency Wn is a number between 0 and 1, where 1 corresponds
to the Nyquist frequency, radians per sample. Smaller values of passband ripple Rp lead
to wider transition widths (shallower rolloff characteristics).
[b,a] = cheby1(n,Rp,Wn,'ftype') designs a highpass , lowpass, or bandstop filter,
where the string 'ftype' is one of the following 'high' for a highpass digital filter with
normalized cutoff frequency Wn 'low' for a lowpass digital filter with normalized cutoff
frequency Wn 'stop' for an order 2*n bandstop digital filter if Wn is a two-element vector,
Wn = [w1 w2]. The stopband is w1 < < w2.
65
ALGORITHM
1. Get the pass band ripple and stop band attenuation
2. Get the pass band and stop band edge frequencies
3. Get the sampling frequency
4. Calculate the orders and frequency scaling factor
5. Find the filter coefficients
6. Plot the magnitude and phase responses
PROCEDURE
1. Program is written in the edit window
2. The program file is saved as an M-file and executed.
3. For the case of errors they are rectified
4. The graphical responses are obtained and output verified.
PROGRAM
%program to design an IIR chebyshav type 1 high pass filter%%***********************************************************% close all; clear all; clc;fp=input('Enter the pass band frequency');%pass band frequencyfs=input('Enter the stop band frequency');%stop band frequencyf=input('enter the sampling frequency');%sampling frequencyRp=input('Enter the pass band ripple');%pass band rippleRs=input('Enter the stop band ripple');%pass band ripple %normalization of frequencies disp('normalized frequencies are')Wp=2*fp/fWs=2*fs/f %calculation of filter order and cut off frequencydisp('the order of filter and cut off frequencies are')[n,Wn] = cheb1ord(Wp,Ws,Rp,Rs) [b,a] = cheby1(n,Rp,Wn,'high');%filter coefficient calculation%calculation of frequency response and plot the magnitude and phase%responsesfreqz(b,a), title('IIR filter response--magnitude and phase responses'); % sample input% Enter the pass band frequency900% Enter the stop band frequency700% enter the sampling frequency8000% Enter the pass band ripple4% Enter the stop band ripple10% normalized frequencies are% % Wp =% 0.2250
66
% Ws =% % 0.1750% % the order of filter and cut off frequencies are% % n =% 3% Wn =% 0.2250
RESULT
An IIR Chebyshev type 1 high pass filter has been designed and the frequency
responses were plotted
FREQUENCY RESPONSE
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-400
-350
-300
-250
-200
-150
-100
-50
Normalized Frequency ( rad/sample)
Pha
se (
degr
ees)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1-140
-120
-100
-80
-60
-40
-20
0
Normalized Frequency ( rad/sample)
Mag
nitu
de (
dB)
IIR filter response--magnitude and phase responses
67