digital filter implementation using matlab

Upload: acajahuaringa

Post on 03-Jun-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Digital Filter Implementation Using MATLAB

    1/9

    Ing. Armando Alberto Cajahuaringa Camaco

    Digital Filter Implementation Using MATLAB http://asic-soc.blogspot.com/2009/01/digital-filter-implementation-using.html

    MATLAB SOFTWAREABOUT MATLAB The name MATLAB stands for matrix laboratory . MATLAB is a high-performance technicalcomputing. It integrates computation, visualization, and programming in an easy-to-use environmentwhere problems and solutions are expressed in familiar mathematical notation. Typical uses include:

    Math and computation Algorithm development 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 requiredimensioning. This allows you to solve many technical computing problems, especially those withmatrix and vector formulations, in a fraction of the time it would take to write a program in a scalar

    non-interactive language such as C or Fortran.MATLAB features a family of application-specific solutions called toolboxes. Very important to most

    users of MATLAB , toolboxes allow you to learn and apply specialized technology. Toolboxes arecomprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment tosolve particular classes of problems. Areas in which toolboxes are available include signal processing,control systems, neural networks, fuzzy logic, wavelets, simulation, and many others.THE MATLAB SYSTEM The MATLAB system consists of five main parts: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, and browsers for viewing help, the workspace, files, andthe search path.The MATLAB Mathematical Function Library: This is a vast collection of computational algorithmsranging from elementary functions like sum, sine, cosine, and complex arithmetic, to moresophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fouriertransforms.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 quickly and dirty throwaway programs, and"programming in the large" to create complete large and complex application programs.

    Handle Graphics: This is the MATLAB graphics system. It includes high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentationgraphics. It also includes low-level commands that allow you to fully customize the appearance ofgraphics as well as to build complete graphical user interfaces on your MATLAB applications.The MATLAB Application Program Interface (API)This is a library that allows you to write C and Fortran programs that interact with MATLAB . It includesfacilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computationalengine, and for reading and writing MAT-files.MATLAB WORKSPACE

    The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. You add variables to the workspace by using functions, running M-files, and loading saved workspaces. For example, if you typet = 0:pi/4:2*pi;y = sin(t);

    http://asic-soc.blogspot.com/2009/01/digital-filter-implementation-using.htmlhttp://asic-soc.blogspot.com/2009/01/digital-filter-implementation-using.htmlhttp://asic-soc.blogspot.com/2009/01/digital-filter-implementation-using.htmlhttp://asic-soc.blogspot.com/2009/01/digital-filter-implementation-using.html
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    2/9

    Ing. Armando Alberto Cajahuaringa Camaco

    The workspace includes two variables, y and t, each having nine values.ABOUT SIMULINK

    Simulink is a software package for modeling, simulating, and analyzing dynamical systems. Itsupports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of thetwo. Systems can also be multirate, i.e., have different parts that are sampled or updated at differentrates.

    For modeling, Simulink provides a Graphical User Interface (GUI) for building models as blockdiagrams, using click-and-drag mouse operations. With this interface, you can draw the models justas you would with pencil and paper. This is a far cry from previous simulation packages that requireyou to formulate differential equations and difference equations in a language or program. Simulink includes a comprehensive block library of sinks, urges, linear and nonlinear components, andconnectors. You can also customize and create your own blocks.

    Models are hierarchical, so you can build models using both top-down and bottom-up approaches.You can view the system at a high level, then double-click on blocks to go down through the levels tosee increasing levels of model detail. This approach provides insight into how a model is organizedand how its parts interact. After you define a model, you can simulate it, using a choice of integration

    methods, either from the Simulink menus or by entering commands in MATLAB 's command window.The menus are particularly convenient for interactive work, while the command-line approach is

    very useful for running a batch of simulations (for example, if you are doing Monte Carlo simulationsor want to sweep a parameter across a range of values). Using scopes and other display blocks, youcan see the simulation results while the simulation is running. In addition, you can change parametersand immediately see what happens. The simulation results can be put in the MATLAB workspace forpost processing and visualization.

    Model analysis tools include linearization and trimming tools, which can be accessed from theMATLAB command line, plus the many tools in MATLAB and its application toolboxes. And becauseMATLAB and Simulink are integrated, you can simulate, analyze, and revise your models in either

    environment at any pointDESIGN AND STUDY OF FILTERS DESIGN STEPS FOLLOWED

    MATLAB offers varieties of toolboxes using that we can easily design the required digital filter andcan observe its phase and magnitude characteristics; construct realization structure of the designedfilter; analyze working of the filter.

    To design a filter and analyze it we followed below mentioned steps:

    1. Using Filter Designer And Analyzer window we designed our required filter. To open thiswindow type fdatool in Command Window and press Enter. The obtained filter coefficients (i.e.numerator and denominator coefficients) are noted.2. Using Filter Realization Wizard window we have constructed the filter structure by inputtingfilter coefficients and selecting the appropriate form. To open this window type dspfwiz on CommandWindow and press enter key. Using Launch Pad also we can open this window. Select DSP Blocksetfrom the Launch Pad and click on the +ve mark corresponding to it. A drop down list opens up. Fromthis list select Filter Realization Wizard and double click on it. This opens that window. The constructedstructure appears as a subsystem model. A double click on the subsystem block opens the filterstructure in Simulink window, which can be simulated.3. Using Simulink block library function generator, oscilloscope and MUX are connected to the filterstructure. Using Simulink debugger the structure is simulated and the results are observed on theoscilloscope.

    IIR FILTER DESIGN ISSUES We restrict our discussion to the design and analysis of IIR filters only, even though FIR filters

    provide linear phase throughout the frequency range. In application of our project phase angle

  • 8/12/2019 Digital Filter Implementation Using MATLAB

    3/9

    Ing. Armando Alberto Cajahuaringa Camaco

    variation is of no importance; if phase angle variation is also important then automatically discussionorients towards FIR filters.

    Before directly going into the analysis of IIR filters let us have a glance over Shannons samplingtheorem.

    A signal containing maximum frequency f1Hz may be completely represented by regularly spacedsamples, provided the sampling rate fs is at least 2f1 sample per second.

    i.e. fs=2f1 Nyquist sampling rate

    If signal is sampled at less than 2f1 rate, aliasing error occurs. Signal is then represented withdistortion, which depends on the degree of aliasing. To avoid such distortions use antialiasing filter, alow pass filter with cutoff frequency at f1 (or fs/2).Because of above reason designing any digital filter at higher frequency side becomes difficult owingto higher sampling rate and its generation. Hence we need to restrict ourselves to lower frequencyside. Further discussion on these issues will be elaborated in respective filter design studies to forthcome.IIR Low pass And High pass Filter Design Issues The ideal response of low pass and high pass filters is as shown in Figure 1

    Practically such sharp roll off is not achievable. Using MATLAB we can easily design these filters

    and simulate it. Even at higher frequencies (like 40 KHz) simulink work satisfactorily. The filternicely exhibits passband and stopband action.

    In most of the applications lowpass/highpass filters are used at lower frequencies with increasedorder, so that sharp roll-off is achieved.

    Figure 1IIR Bandpass Filter Design and Its Implementation Ideally bandpass filter should have a perfect passband as shown in the Figure 2

    But practically such a sharp cutoff at passband edges is not possible. Therefore practically we aimtowards a response, which has as much sharper role-off as possible, so that channel selection isperformed noiselessly. Chebyshev and elliptic filters provide very good response in this regard. Hencewe select Chebyshev type of filter for our study and analysis as it provides satisfactory bandpass

    characteristics.

    Figure 2Chebyshev Type-II Filter Design Filter parameters are as shown belowOrder = 2; Sampling frequency Fs = 100 KHz; Fstop1 = 39 KHz; Fstop2 = 41 KHz; Astop= 60 dB

    http://3.bp.blogspot.com/_Se0VANaI9uM/SX6pgw23DGI/AAAAAAAAAqw/G8his300G_o/s1600-h/fig+2+band+pass.jpghttp://2.bp.blogspot.com/_Se0VANaI9uM/SX6ppU8wrvI/AAAAAAAAAq4/U1rsaqNMFqw/s1600-h/fig+1+low+pass+high+pass.jpg
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    4/9

    Ing. Armando Alberto Cajahuaringa Camaco

    Input the above parameters to the respective places of Filter Design & Analysis Tool . Aftercompleting this click on Design Filter button. This creates the required filter .To observe theresponse (step or frequency or impulse) click on the respective icon of the toolbar. Toolbar also hasicons to observe pole-zero plot, group delay, filter coefficients etc. Thus the obtained filter coefficientsare as follows:Numerator (b) Denominator (a) 0.000062910740701 1.000000000000000

    0.000000000000000 1.621131129004091-0.000062910740701 0.999874178518599

    For the above parameters magnitude response can be observed by clicking on corresponding iconof the toolbar. The corresponding frequency response is as shown below in Figure 3.

    Figure 3For the same above filter parameters MATLAB program is written in a M-file to create chebyshev

    type-II bandpass filter.The program is as follows.

    File name:cheby.m

    clc;clear all;close all;

    As=60; %stopband attenuationwp1=3.8e+004; %lower cutoff frequencywp2=4.2e+004; %higher cutoff frequencyn=1; %orderfs=100000; %sampling frequencywn=[wp1 wp2]/(fs/2); %Nyquist frequency[b,a] = cheby2(n,As,wn); %compute filter coefficients[h,f]=freqz(b,a,fs/2); %compute frequency responsemag=20*log10(abs(h)); %get magnitude responsesubplot (2,1,1);plot(f*(fs/2)/pi, mag);grid; %plot response with grid linesang=angle(h); %get phase responsesubplot(2,1,2);plot(f*(fs/2)/pi,ang);grid; %plot response with grid lines

    Run this program either by pressing F5 key on keyboard or select Run from debug menu. Theobtained magnitude and phase response is as shown below in Figure 4

    http://2.bp.blogspot.com/_Se0VANaI9uM/SX6pWVvQXfI/AAAAAAAAAqo/1xHTGXL7bRU/s1600-h/figure+3.jpg
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    5/9

    Ing. Armando Alberto Cajahuaringa Camaco

    Figure 4For both of the above filter designs, the corresponding filter realization structure of Direct Form 2is as shown in Figure 5. This can be created using Filter Realization Wizard by inputting filtercoefficients.From the frequency response curves (Figure 4) of the above filter we can analyze the filter.

    Thus the Chebyshev type-2 filter designed with n=1(implies order 2n=2) and pass band =2 KHz(implies 1 KHz from 40 KHz) has very sharp (like a pulse) passband and also not exactly centeredat 40 KHz.Owing to this shift of passband either towards the left or right side of frequency domain,the center frequency may get attenuated or noise signals may creep through the filter resulting in adistorted output. Another possibility is suppose by some means frequency of input signal itself variesfrom its central value then filter may pass unwanted signals and it may attenuate the original signalitself creating a noisy output. This may due to the inconsistency of function generator. We cant sayeven crystal oscillator can produce exactly 40 KHz signal. It may vary a little (100 Hz) due tovariation of temperature, pressure, applied voltage etc.

    Figure 5

    Therefore we need a filter, which has a passband, so that even though center frequency variesfrom its value, the signal is reproduced faithfully at the output and all other unwanted signalfrequencies are completely attenuated.

    We can meet the requirements by changing the filter parameters like order, pass band, edgefrequency or stop band attenuation. But it is found that keeping order n=1 even though we increase

    http://4.bp.blogspot.com/_Se0VANaI9uM/SX6o-3mU-WI/AAAAAAAAAqY/cqKZ18l14tM/s1600-h/figure+5.jpghttp://4.bp.blogspot.com/_Se0VANaI9uM/SX6pM-G0-hI/AAAAAAAAAqg/rUXLL8b62fU/s1600-h/figure+4.jpg
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    6/9

    Ing. Armando Alberto Cajahuaringa Camaco

    pass band range and decrease stop band attenuation, dont yield satisfactory result instead it justattenuated pass band itself.

    Therefore to improve the filter performance the only left option is to increase the filter order andthis is what done in most of the practical cases. We adjust the pass band frequency so that around500 to 800 Hz pass band with minimum attenuation is obtained.

    Using Filter Design & Analysis Tool we can do this and by noting down the filter coefficientswe can realize filter structure.

    CHEBYSHEV TYPE-II FILTER DESIGN WITH INCREASED ORDER Filter parameter: n = 4 (2n = 4=> n =2)Fs = 100000Hz.Fstop1 = 38000Hz.Fstop2 = 41800Hz.Astop = 40dB.Let the file name given to this filter be filter40.fda

    Figure 6 The obtained magnitude response is as shown in Figure 6 and the corresponding filter coefficients

    are as follows,Numerator (b) Denominator (a) b(0)=0.010045097978992. a(0)=1.000000000000000.b(1)=0.031677960303578. a(1)=3.205603560877597.b(2)=0.044659670697279. a(2)=4.521600439016961.b(3)=0.031677960303578. a(3)=3.129988499837994.

    b(4)=0.010045097978992. a(4)=0.953386226509250.

    EFFECT OF TRUNCATION OF COEFFICIENT ON FILTER RESPONSEDigital signal processing algorithms are realized either with special purpose digital hardware or as

    programs for a general-purpose digital computer. In both cases the numbers and coefficients arestored in finite-length registers. Therefore, coefficients and numbers must be quantized by truncationsor rounding before they can be stored.The following errors arise due to quantization of numbers,

    1. Input quantisation error.2. Product quantisation error.

    3. Coeficiente quantisation error.

    http://4.bp.blogspot.com/_Se0VANaI9uM/SX6o2FcHW6I/AAAAAAAAAqQ/F_NUn5gcAoA/s1600-h/figure+6.jpg
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    7/9

    Ing. Armando Alberto Cajahuaringa Camaco

    4. The conversion of a continuous time input signal into digital value produces an error, which isknown as input quantization error arises due to the representation of the input signal by a fixednumber of digits in the A/D conversion process.

    5. Product quantization errors arise at the output of a multiplier. Multiplication of a and b bit with ab bit coefficient results a product having 2b bits. Since ab bit register is used, the multiplieroutput must be rounded or truncated to b bits, which produces an error.

    6. The filter coefficients are computed to infinite precision in theory. If they are quantized, thefrequency response of the resulting filter may differ from the desired response and sometimes thefilter may fail to meet the desired specifications. If the poles of the desired filter are close to theunit circle, then those of the filter with quantized coefficients may lie just outside the unit circle,leading to the instability.

    The other errors arising from quantization are round off noise and limit cycle oscillations.It can be understood from the above points that quantization error due to A/D conversion process

    is difficult to minimize below certain limits in any sophisticated processor. Using higher sampling ratewe can minimize this error.

    Using processors with higher word length registers can minimize product quantisation errors. Aslength of the operating registers become more and more error becomes less and less. If floating pointarithmetic is supported in processor then this error can be eliminated to a very large extent.Now let us analyze the filter40.fda named filter for different truncated values.In this file, the coefficients obtained are 64-bit length (i.e. 16 decimal number excluding decimalpoint). Notice that these are the coefficients, which are obtained by designing the filter in Filterdesign & Analysis tool.

    To find out what is the effect of truncating the coefficient data, we use M-file program cheby.m.Here we directly feed the filter coefficients to the freqz command as shown below:

    clc;clear all;

    close all;b=[b(0) b(1) b(2) b(3) b(4)]; %fill numerator coefficientsa=[a(0) a(1) a(2) a(3) a(4)]; %fill denominator coefficients[h, f]=freqz (b,a,fs/2);

    If you dont put semicolon at the end of the line where numerator and denominator coefficients arewritten and you run the program, you can find that at the command window, these coefficients arerounded up to 4 th decimal point. The software itself automatically does the truncation of data. Theresultant frequency response by this truncated data is same as that of obtained with non-truncateddata with hardly noticeable differences.The rounding up of numerator and denominator to third decimal point causes below response:

    Numerator (b) denominator (a) 0.010 1.0000.032 3.2060.045 4.5220.032 3.1300.010 0.953

  • 8/12/2019 Digital Filter Implementation Using MATLAB

    8/9

    Ing. Armando Alberto Cajahuaringa Camaco

    Figure 7

    The rounding up of numerator and denominator to second decimal point causes heavy variation inpass band attenuation as shown in Figure 8.Numerator (b) Denominator (a) 1. 1.002. 3.213. 4.524. 3.131. 0.95

    Figure 8 Rounding up of filter coefficient to the first decimal point abruptly changes frequency characteristics

    of the filter.From the above discussion it follows that truncating the filter coefficients to 4 th decimal point yields

    good acceptable frequency characteristics and hence can be implemented in hardware.

    The filter structure for the above filter is as shown below in Figure 9.

    http://4.bp.blogspot.com/_Se0VANaI9uM/SX6oYZhWS9I/AAAAAAAAAqA/pJ61GPl2p6I/s1600-h/figure+8.jpghttp://2.bp.blogspot.com/_Se0VANaI9uM/SX6omZIgGAI/AAAAAAAAAqI/TVAqJsjaZA0/s1600-h/figure+7.jpg
  • 8/12/2019 Digital Filter Implementation Using MATLAB

    9/9

    Ing. Armando Alberto Cajahuaringa Camaco

    Figure 9

    SIMULATING THE FILTER STRUCTURE To simulate the above filter structure, it has to be modified a little bit.First open Simulink Library Browser . Select and drag the Sine Wave block from the source

    library to the window where the structure is created. Similarly Scope is dragged from the Sinkslibrary and the Mux is dragged from the Signals & Systems library. Substitute input by sine Waveblock, output by Mux and Scope block. By double clicking on each block we can get the propertiesof each block. For example: double click on sine wave block. This will open a window wherein wecan write frequency of the signal, signal voltage, sampling time etc. In the same way mux and scopecan be configured.

    After connecting all these blocks click on start icon on the toolbar to start simulation. Options arethere to pause the simulation, stop the simulation etc. We can also see the simulation status on

    simulink debugger window. Double click on the scope block. This opens the oscilloscope where wecan observe the input and output waveforms.

    The study and analysis of simulation of the above filter structure as well as many other filter

    structures (like Cheby type-1, 2 Butterworth lowpass/highpass) are carried out successfully.One thing that is particularly noticeable is that for higher frequencies simulation of filter structuretakes more time compared to simulation of filter structure at lower frequencies. Effect of truncationof coeffients can also be observed on the Scope and also works as the study has been done in earliersections.

    References 1. Digital Signal Processing By Sanjit K.Mitra2. Digital Signal Processing By P.Ramesh Babu3. Digital Filters By T.J.Terrel And E.T.Powner

    4. BASIC Digital Signal Processing By Gordon B. Lockart And Barry M.G.Cheetham5. Digital Signal Processing By Alan V.Oppenheim And Ronald W.Schafer6. DSP Microprocessors: Advances and Automotive Applications By Subra Ganeshan And Dr.Gopal

    Arvamudhan7. www.mathworks.com

    http://1.bp.blogspot.com/_Se0VANaI9uM/SX6oQWh_D3I/AAAAAAAAAp4/c2dNRzgKGXs/s1600-h/figure+9.jpg