You are on page 1of 33

MATLAB EXPERIMENTS 1 2 3 4 5 6 7 FAMILIARIZATION OF MATLAB LINEAR CONVOLUTION CIRCULAR CONVOLUTION DISCRETE FOURIER TRANSFORM AND INVERSE DFT FIR

LOW PASS FILTER DESING USING HAMMING WINDOW IIR LOW PASS BUTTERWORTH FILTER IIR HIGH PASS CHEBYSHEV TYPE 1 FILTER

3 6 3 7 5 0 5 3 5 6 5 8 6 2 6 5

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 helpwin help topic lookfor string demo Lists on which help is available opens the interactive help window provide help on topic lists help topic containing string runs the demo program

4.2 Workspace Information who whos clear clear x y z close all clc home clf Lists the variable currently in the workspace lists the variable currently in the workspace with their size clear the workspace, all variables are removed clears only variables x, y and z close all the graphic windows, which are open clears command window same as clc clear figure window

4.3 Directory information pwd cd dir is path editpath copyfile mkdir shows the current working directory changes the current working directory lists the contents of current directory same as dir gets or sets MATLAB search path modify MATLAB search path copies a file creates a directory

4.4 General information computer clock date more tells you the computer type you are using gives you wall clock time and date as vector tells you date as a string controls the paged output according to the screen size 40

4.5 Termination ^C (Control+C) quit exit 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 41 local abort kills the current command execution quits MATLAB same as quit

| or ~ not xor exclusive or 5.2 Functions Basic functions Elementary math functions abs angle sqrt real imag conj gcd lcm round fix floor ceil sign rem exp log log10 absolute value or complex magnitude phase angle square root real part imaginary part complex conjugate greatest common divisor least common multiple round to nearest integer round toward zero round the nearest integers less than or equal to the input round toward 1 signum function remainder exponential base e natural logarithm log base 10

Commonly used programming functions input keyboard menu pause function eval feval global save load prompt for user input invoke keyboard as if it were a script _le generate menu of choices for user input waits for user response define function execute string with MATLAB expression evaluate function speci_ed by string define global variables saving a variable value loading a variable from the specified location.

Commonly used Signal Processing Functions 42

abs angle conv deconv corrcoef cov filter filter2 unwrap nextpow2 fft fft2 ifft ifft2 fftshift circshift fir1 buttord buttord chebyord chebyord1 freqz

complex magnitude phase angle convolution and polynomial multiplication deconvolution and polynomial division correlation coefficients covariance matrix one-dimensional digital filter two-dimensional digital filter remove phase angle jumps across 360_ boundaries next higher power of 2 radix-2 fast Fourier transform two-dimensional FFT inverse fast Fourier transform inverse 2-D FFT zero-th lags to center of spectrum circularly shifting the vector by points specified by user one dimensional FIR filtering order of butterworth filter coefficients of butterworth filter response order of chebyshev type 1 filter coefficients of chebyshev filter response convert to frequency domain from time doamain

Functions for building matrices eye identity matrix zeros matrix of zeros ones matrix of ones diag diagonal matrix triu upper triangular part of a matrix tril lower triangular part of a matrix rand randomly generated matrix Matrix functions svd inv det size singular value decomposition inverse determinant size 43

norm cond rank max min

1-norm, 2-norm, F-norm condition number in the 2-norm rank maximum value in each column 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] 1 2 5 A= 3 9 0 Transpose of Matrix=A Appending row : If B =[4 7 9] 1 2 5 [A;B]= 3 9 0 4 7 9 Appending Column 3 If B= 2 1 2 5 3 [A B]= 3 9 0 2 Deleting a row or column A(2,:)=[] A(:,3:2)=[] Create an empty matrix A=[ ]; deletes the second row of matrix deletes the third row and second column

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 2 >=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.
n

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 text grid place text on the graph using the mouse position text at specified coordinates 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]) axis(axis) axis auto v= axis axis square axis equal axis off axis on set axis scaling to prescribed limits freezes scaling for subsequent graphs returns to auto-scaling returns vector v showing current scaling same scale on both axes same scale and tic marks on both axes turns off axis scaling and tic marks 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 mesh RESULT Familiarized the basic functions and commands in MATLAB. plot the discrete signals three dimensional wire mesh surface plots

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 z ( n) =

k =

x1(k )x2(n k )

And whose rth element is

z (r ) = j x1( j )x 2(r + 1 j )
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 sequence t1=input('enter the starting time of first seqence');%input the starting time of first sequence x2=input('enter the second sequence');%input the second sequence t2=input('enter the starting time of second sequence');%input the starting time of second sequence l1=length(x1);%calculate the number of elements in 1st sequence l2=length(x2);%calculate the number of elements in 2nd sequence %plot the first sequence using stem function subplot(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 function subplot(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 sequence t=t1+t2;%starting time of output sequence n=t:1:l+t-1;%time instances of output sequence z=conv(x1,x2);%convovolution of the two input sequences %plot the output sequence using stem function subplot(3,1,3); stem(n,z),grid on; ylabel('amplitude----->'); xlabel('time----->'); title('convolved output'); %sample % enter % enter % enter % enter input the first sequence[ 1 3 5 7 8 1 ] the starting time of first seqence-2 the second sequence[3 5 7 1 7] the starting time of second sequence-2

RESULT The convolution between two sequences was computed and result plotted. WAVEFORMS
T h e fi rs t s e q u e n c e
10

am plitude----->

5 0 -2

- 1 .5

-1

-0 .5

0 .5

1 .5

2 .5

ti m e - - - - - > The se co nd se q ue nce


10

am plitude----->

5 0 -2

- 1 .5

-1

- 0 .5

0 .5

1 .5

ti m e - - - - - > c o n v o lv e d o u t p u t
150

am plitude----->

100 50 0 -4 -3 -2 -1 0 1 2 3 4 5

ti m e - - - - - >

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 X 1(n) X 2( n) = X 1(m) X 2(n m) N
m =0 N 1

0mN-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. 2. 3. 4. Get the input sequences and their length. If the length are not equal make the shorter sequence length equal to Perform the circular convolution us ing matrix multiplication method. Plot the input and output sequences

longer sequence by appending zeros.

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 sequence l1=length(x1);%find out the no:of elements x2=input('enter the second sequence');%input the second sequence l2=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 method X1=X1';%taking the transpose to make the row vector to column vector sh=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 function t1=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-1 subplot(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

T h e fi rs t s e q u e n c e
10 am plitude-----> 5 0

0 .5

1 .5 tim e - - - - - >

2 .5

The se co nd se q ue nce
10 am plitude-----> 5 0

0 .1

0 .2

0 .3

0 .4

0 .5 0 .6 tim e - - - - - >

0 .7

0 .8

0 .9

c o n v o lv e d o u t p u t
100 am plitude-----> 50 0

0 .5

1 .5 tim e - - - - - >

2 .5

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. 2. 3. 4. 5. Input the sequence. Find the DFT Find the magnitude and phase part of DFT Find the IDFT of the DFT sequence to reconstruct the original input Plot the amplitude spectrum, phase spectrum and IDFT.

PROCEDURE 1. Write the program and save the file with a name and extension .m 2. 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 sequence N=input('Input the length of DFT sequence');% the value of N in N-point DFT %plotting the input siganl subplot(2,2,1),stem(x),grid on; title('Input signal') xlabel('time----->') ylabel('amp----->') a=fft(x,N); %find out the DFT of the sequenece mag=abs(a); % computing magnitude part of each DFT value phase=(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 plot subplot(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

RESULT 1. 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
Input signal
4 3 amp-----> 2 1 0 1 amp-----> 20 15 10 5 0 1

Magnitude part of DFT

4 time----->

4 5 time----->

phase part of DFT


200 100 amp-----> 0 -100 -200 1 amp-----> 4 3 2 1 0 1

IDFT-the reconstructed input sequence

4 5 time----->

4 5 time----->

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) hann(N) hamm(N) blackman(n) N point rectangular window N point symmetric hanning window N point symmetric hamming window 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 B(e j ) b(1)+ b(2)e j + b(3)e j 2 +....+b(m+1)e jm = A(e j ) a(1)+ a(2)e j + a(3)e j 2 +....+a(n+1)e jn 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 infinity REM(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. H (e j ) = ALGORITHM 1. Get the pass band, stop band and sampling frequency 2. Determine FIR filter coefficients using desired window 3. Determine frequency response using the FREQZ function 4. Calculate amplitude and phase response using the frequency response 5. Plot all of them graphically PROCEDURE 1. Write the program and save it with a name and extension .m 2. 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 frequency fs=input('Enter the stop band frequency');%stop band frequency f=input('enter the sampling frequency');%sampling frequency rp=input('Enter the pass band ripple');%pass band ripple rs=input('Enter the stop band attenuation');%stop band attenuation %calculation of the filter order num=-20*log10(sqrt(rp*rs))-13; dem=14.6*(fs-fp)/f; n=ceil(num/dem); %normalization of frequencies and calculation of cut off frequencies wp=2*fp/f; ws=2*fs/f; wn=(wp+ws)/2; %display the normalized frequencies and cut off frequency disp('The normalized frequencies are') wp ws disp('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 window if(n/2==0) m=n+1; else m=n; n=n-1; end %the winodw sequence calculation. Here used hanning window W = 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 %responses freqz(b,1,n);title('The magnitude and phase response')

%sample input % Enter the pass band frequency1000 % Enter the stop band frequency1200

60

% enter the sampling frequency3000 % Enter the pass band ripple.02 % Enter the stop band ripple.03 % % % % % % % % % % % % The normalized frequencies are wp = ws = 0.8000 cut off frequency wn = 0.7333 0.6667

RESULT A FIR filter having lowpass characteristics has been designed using hanning window and the frequency responses were plotted FREQUENCY RESPONSE

F IR filter....The magnitude and phase response


20 0

Magnitude (dB)

-20 -40 -60 -80 -100 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Normalized F requency rad/sample) (


0

Phase (degrees)

-500

-1000

-1500

-2000 0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

Normalized F requency rad/sample) (

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 frequency fs=input('Enter the stop band frequency');%stop band frequency f=input('enter the sampling frequency');%sampling frequency Rp=input('Enter the pass band ripple');%pass band ripple Rs=input('Enter the stop band ripple');%stop band ripple %normalization of frequencies disp('normalized frequencies are') Wp=2*fp/f Ws=2*fs/f %calculation of filter order and cut off frequency disp('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 %responses freqz(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 = Wn = 0.6665 10

RESULT An IIR Butterworth low pass filter has been designed the frequency responses were plotted FREQUENCY RESPONSE
IIR filte r re sp o nse --m a g nitud e a nd p ha s e re s p o ns e s
0 -50

Magnitude (dB)

-100 -150 -200 -250 -300 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

No rm a lize d F re q ue ncy (ra d /sa m p le )

0 -200

Phase (degrees)

-400 -600 -800 -1000 0

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

N o rm a lize d F re q ue nc (ra d /s a m p le ) y

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 frequency fs=input('Enter the stop band frequency');%stop band frequency f=input('enter the sampling frequency');%sampling frequency Rp=input('Enter the pass band ripple');%pass band ripple Rs=input('Enter the stop band ripple');%pass band ripple %normalization of frequencies disp('normalized frequencies are') Wp=2*fp/f Ws=2*fs/f %calculation of filter order and cut off frequency disp('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 %responses freqz(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 =

66

% % % % % % % % % % %

Ws =

0.2250 0.1750

the order of filter and cut off frequencies are n = Wn = 3 0.2250

RESULT An IIR Chebyshev type 1 high pass filter has been designed and the frequency responses were plotted FREQUENCY RESPONSE
IIR filter response--magnitude and phase responses
0 -20 Magnitude (dB) -40 -60 -80 -100 -120 -140 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Norm alized Frequency rad/sam ple) ( 0.8 0.9 1

-50 -100 Phase (degrees) -150 -200 -250 -300 -350 -400 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Norm alized Frequency rad/sam ple) ( 0.8 0.9 1

67

You might also like