معرفی چند منبع در زمینه آموزش برنامه نویسی MATLABیا متلب کتاب های به زبان انگلیسی عنوانMatlab, Third Edition: A Practical Introduction to : Programming and Problem Solving ترجمه عنوان :متلب :مقدمه ای عملی بر برنامه نويسی و حل مساله ،چاپ سوم مولفینStormy Attaway : سال چاپ2013 : انتشاراتButterworth-Heinemann : کتاب های به زبان فارسی عنوان :اصول و مبانی متلب برای علوم مهندسی مولفین :برايان هان ،دانیل تی ،والنتین مترجمین :رامین موالنا پور ،سارا موالناپور ،نینا اسدی پور انتشارات :سها دانش لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB For Dummies : ترجمه عنوان :تلب به زبان ساده مولفینJim Sizemore, John Paul Mueller : سال چاپ2014 : انتشاراتFor Dummies : عنوان :کاربرد MATLABدر علوم مهندسی مولفین :حیدرعلی شايانفر ،حسین شايقی انتشارات :ياوريان لینک دسترسی :لینک لینک دسترسی :لینک عنوانEssential MATLAB for Engineers and Scientists : عنوان :برنامه نويسی MATLABبرای مهندسان ترجمه عنوان :آنچه بايد مهندسین و دانشمندان از متلب بدانند مولفین :محمود کشاورز مهر ،بهزاد عبدی مولفینBrian Hahn, Daniel Valentine: سال چاپ2013 : انتشاراتAcademic Press : انتشارات :نوپردازان لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB: An Introduction with Applications : عنوان :آموزش کاربردی مباحث پیشرفته با MATLAB ترجمه عنوان :مقدمه ای بر متلب و کاربردهای آن مولفین :نیما جمشیدی ،علی ابويی مهريزی ،رسول مواليی مولفAmos Gilat : انتشارات :عابد سال چاپ2014 : انتشاراتWiley : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB For Beginners: A Gentle Approach: عنوان :کاملترين مرجع آموزشی و کاربردی MATLAB ترجمه عنوان :متلب برای افراد مبتدی با يک رويکرد تدريجی مولفین :علی اکبر علمداری ،نسرين علمداری مولفPeter I. Kattan: انتشارات :نگارنده دانش سال چاپ2008 : انتشاراتCreateSpace Independent Publishing Platform : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB for Engineers : عنوان :برنامه نويسی MATLABبرای مهندسین ترجمه عنوان :متلب برای مهندسین مولف :استفن چاپمن مولفHolly Moore : سال چاپ2011 : انتشاراتPrentice Hall : لینک دسترسی :لینک عنوانMastering MATLAB : ترجمه عنوان :تسلط بر متلب مولفینDuane C. Hanselman, Bruce L. Littlefield : سال چاپ2011 : انتشاراتPrentice Hall : لینک دسترسی :لینک مترجم :سعدان زکائی انتشارات :دانشگاه صنعتی خواجه نصیرالدين طوسی لینک دسترسی :لینک عنوان :آموزش گام به گام محاسبات عددی با متلب مولف :کلیو مولر مترجم :رسول نصیری انتشارات :نشر گستر لینک دسترسی :لینک منابع آموزشی آنالین عنوان :مجموعه فرادرسهای برنامهنويسی متلب مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۹ :ساعت و ۳دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای متلب برای علوم و مهندسی مدرس :دکتر سید مصطفی کالمی هريس مدت زمان 14 :ساعت و 2۲دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای برنامه نويسی متلب پیشرفته مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۲ :ساعت و 12دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوانIntroduction to Programming with MATLAB : ترجمه عنوان :آشنايی با برنامهنويسی متلب مدرسینAkos Ledeczi, Michael Fitzpatrick, Robert Tairas : زبان :انگلیسی ارائه دهندهVanderbilt University : لینک دسترسی :لینک عنوانIntroduction to MATLAB : ترجمه عنوان :مقدمهای بر متلب مدرسDanilo Šćepanović : زبان :انگلیسی ارائه دهندهMIT OCW : لینک دسترسی :لینک عنوانUp and Running with MATLAB : ترجمه عنوان :شروع سريع کار با متلب مدرسPatrick Royal : زبان :انگلیسی ارائه دهندهlynda.com : لینک دسترسی :لینک عنوانModelling and Simulation using MATLAB : ترجمه عنوان :مدلسازی و شبیهسازی با استفاده از متلب مدرسین Prof. Dr.-Ing. Georg Fries :و دیگران زبان :انگلیسی ارائه دهندهiversity.org : لینک دسترسی :لینک DSP System Toolbox™ User's Guide R2014b www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان How to Contact MathWorks Latest news: www.mathworks.com Sales and services: www.mathworks.com/sales_and_services User community: www.mathworks.com/matlabcentral Technical support: www.mathworks.com/support/contact_us Phone: 508-647-7000 The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 DSP System Toolbox™ User's Guide © COPYRIGHT 2011–2014 by The MathWorks, Inc. The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to The MathWorks, Inc. Trademarks MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or registered trademarks of their respective holders. Patents MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for more information. Revision History April 2011 September 2011 March 2012 September 2012 March 2013 September 2013 March 2014 October 2014 First printing Online only Online only Online only Online only Online only Online only Online only Revised for Version 8.0 (R2011a) Revised for Version 8.1 (R2011b) Revised for Version 8.2 (R2012a) Revised for Version 8.3 (R2012b) Revised for Version 8.4 (R2013a) Revised for Version 8.5 (R2013b) Revised for Version 8.6 (R2014a) Revised for Version 8.7 (R2014b) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Contents DSP Tutorials 1 Introduction to Streaming Signal Processing in MATLAB . . 1-2 Filter Frames of a Noisy Sine Wave Signal in MATLAB . . . 1-10 Filter Frames of a Noisy Sine Wave Signal in Simulink . . . Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Lowpass Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Spectrum Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 1-13 1-15 1-15 Lowpass Filter Design in MATLAB . . . . . . . . . . . . . . . . . . . . 1-18 Lowpass IIR Filter Design in Simulink . . . . . . . . . . . . . . . . Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Butterworth Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Chebyshev Type I Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . Chebyshev Type II Filter . . . . . . . . . . . . . . . . . . . . . . . . . . Elliptic Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Minimum-Order Designs . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27 1-27 1-28 1-30 1-32 1-34 1-36 Create Moving Average System object . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Create the Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . Moving Average Filter Properties . . . . . . . . . . . . . . . . . . . . Moving Average Filter Constructor . . . . . . . . . . . . . . . . . . . Moving Average Filter Setup . . . . . . . . . . . . . . . . . . . . . . . Moving Average Filter Step . . . . . . . . . . . . . . . . . . . . . . . . Moving Average Filter Reset . . . . . . . . . . . . . . . . . . . . . . . . Input Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object Saving and Loading . . . . . . . . . . . . . . . . . . . . . . . . . System object Usage in MATLAB . . . . . . . . . . . . . . . . . . . . Simulink Customization Methods . . . . . . . . . . . . . . . . . . . . System object Usage in Simulink . . . . . . . . . . . . . . . . . . . . 1-40 1-40 1-41 1-41 1-42 1-43 1-43 1-44 1-44 1-44 1-45 1-46 1-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان iii iv Contents Tunable Lowpass Filtering of Audio Input in Simulink . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48 1-49 1-50 Desktop Real-time Audio Acceleration with MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Notch Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C Code Generation Speedup . . . . . . . . . . . . . . . . . . . . . . . . 1-53 1-53 1-53 1-54 Fixed-Point Filter Design in MATLAB . . . . . . . . . . . . . . . . . 1-56 Sample Rate Conversion of Audio Signal in MATLAB and Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Design and Analysis of Sample Rate Converter . . . . . . . . . . Using the Sample Rate Converter in MATLAB . . . . . . . . . . Using the Sample Rate Converter in Simulink . . . . . . . . . . Specifying Tolerance to Reduce Filter Order . . . . . . . . . . . . 1-65 1-65 1-65 1-67 1-69 1-72 Visualizing Multiple Signals Using Logic Analyzer . . . . . . . Model Programmable FIR Filter . . . . . . . . . . . . . . . . . . . . . Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Use the Logic Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modify the Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-74 1-74 1-75 1-76 1-78 Signal Visualization and Measurements in MATLAB . . . . . 1-88 Filter Frames of a Noisy Sine Wave Signal using Testbench Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-103 Create Composite System object . . . . . . . . . . . . . . . . . . . . . Create MultiNotchFilter . . . . . . . . . . . . . . . . . . . . . . . . . . Contain System Objects as Private Properties . . . . . . . . . . Work with Dependent Properties . . . . . . . . . . . . . . . . . . . Use the Multi-Notch Filter - Initialization . . . . . . . . . . . . . Use the Multi-Notch Filter - Streaming . . . . . . . . . . . . . . . 1-110 1-110 1-110 1-111 1-112 1-112 Measure Audio Latency in MATLAB and Simulink . . . . . . 1-115 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Input, Output, and Display Discrete-Time Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Time and Frequency Terminology . . . . . . . . . . . . . . . . . . . . . Recommended Settings for Discrete-Time Simulations . . . . . Other Settings for Discrete-Time Simulations . . . . . . . . . . . . 2-2 2-2 2-3 2-6 Continuous-Time Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . Continuous-Time Source Blocks . . . . . . . . . . . . . . . . . . . . . Continuous-Time Nonsource Blocks . . . . . . . . . . . . . . . . . . 2-11 2-11 2-11 Create Sample-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . . Create Signals Using Constant Block . . . . . . . . . . . . . . . . . Create Signals Using Signal from Workspace Block . . . . . . 2-12 2-12 2-14 Sample-Based Row Vector Processing Changes . . . . . . . . . 2-17 Create Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . . Create Signals Using Sine Wave Block . . . . . . . . . . . . . . . . Create Signals Using Signal from Workspace Block . . . . . . 2-19 2-19 2-22 Create Multichannel Sample-Based Signals . . . . . . . . . . . . . Multichannel Sample-Based Signals . . . . . . . . . . . . . . . . . . Create Multichannel Signals by Combining Single-Channel Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Create Multichannel Signals by Combining Multichannel Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26 2-26 Create Multichannel Frame-Based Signals . . . . . . . . . . . . . Multichannel Frame-Based Signals . . . . . . . . . . . . . . . . . . . Create Multichannel Signals Using Concatenate Block . . . . 2-32 2-32 2-32 Deconstruct Multichannel Sample-Based Signals . . . . . . . . Split Multichannel Signals into Individual Signals . . . . . . . Split Multichannel Signals into Several Multichannel Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-36 2-36 Deconstruct Multichannel Frame-Based Signals . . . . . . . . . Split Multichannel Signals into Individual Signals . . . . . . . Reorder Channels in Multichannel Frame-Based Signals . . 2-43 2-43 2-47 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-26 2-29 2-39 v 3 vi Contents Import and Export Sample-Based Signals . . . . . . . . . . . . . . Import Sample-Based Vector Signals . . . . . . . . . . . . . . . . . Import Sample-Based Matrix Signals . . . . . . . . . . . . . . . . . Export Sample-Based Signals . . . . . . . . . . . . . . . . . . . . . . . 2-52 2-52 2-55 2-59 Import and Export Frame-Based Signals . . . . . . . . . . . . . . . Import Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . Export Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . 2-64 2-64 2-67 Musical Instrument Digital Interface . . . . . . . . . . . . . . . . . . About MIDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MIDI Control Surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using MIDI Control Surfaces with MATLAB and Simulink . 2-72 2-72 2-72 2-73 Display Time-Domain Data . . . . . . . . . . . . . . . . . . . . . . . . . . . Configure the Time Scope Properties . . . . . . . . . . . . . . . . . Use the Simulation Controls . . . . . . . . . . . . . . . . . . . . . . . . Modify the Time Scope Display . . . . . . . . . . . . . . . . . . . . . . Inspect Your Data (Scaling the Axes and Zooming) . . . . . . . Manage Multiple Time Scopes . . . . . . . . . . . . . . . . . . . . . . . 2-77 2-78 2-83 2-84 2-86 2-89 Display Frequency-Domain Data in Spectrum Analyzer . . 2-93 Visualize Central Limit Theorem in Array Plot . . . . . . . . . Display a Uniform Distribution . . . . . . . . . . . . . . . . . . . . . Display the Sum of Many Uniform Distributions . . . . . . . . Inspect Your Data by Zooming . . . . . . . . . . . . . . . . . . . . . 2-100 2-100 2-101 2-103 Data and Signal Management Sample- and Frame-Based Concepts . . . . . . . . . . . . . . . . . . . . Sample- and Frame-Based Signals . . . . . . . . . . . . . . . . . . . . Model Sample- and Frame-Based Signals in MATLAB and Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . What Is Sample-Based Processing? . . . . . . . . . . . . . . . . . . . . What Is Frame-Based Processing? . . . . . . . . . . . . . . . . . . . . 3-2 3-2 Inspect Sample and Frame Rates in Simulink . . . . . . . . . . . . Sample Rate and Frame Rate Concepts . . . . . . . . . . . . . . . . 3-8 3-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-3 3-4 3-4 Inspect Inspect Inspect Inspect 4 Sample-Based Signals Using Probe Block . . . . . . . . . Frame-Based Signals Using Probe Block . . . . . . . . . Sample-Based Signals Using Color Coding . . . . . . . Frame-Based Signals Using Color Coding . . . . . . . . 3-9 3-11 3-13 3-15 Convert Sample and Frame Rates in Simulink . . . . . . . . . . Rate Conversion Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . Rate Conversion by Frame-Rate Adjustment . . . . . . . . . . . . Rate Conversion by Frame-Size Adjustment . . . . . . . . . . . . Avoid Unintended Rate Conversion . . . . . . . . . . . . . . . . . . . Frame Rebuffering Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . Buffer Signals by Preserving the Sample Period . . . . . . . . . Buffer Signals by Altering the Sample Period . . . . . . . . . . . 3-19 3-19 3-20 3-24 3-28 3-34 3-36 3-39 Buffering and Frame-Based Processing . . . . . . . . . . . . . . . . Frame Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Buffer Sample-Based Signals into Frame-Based Signals . . . Buffer Sample-Based Signals into Frame-Based Signals with Overlap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Buffer Frame-Based Signals into Other Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Buffer Delay and Initial Conditions . . . . . . . . . . . . . . . . . . Unbuffer Frame-Based Signals into Sample-Based Signals . 3-43 3-43 3-43 Delay and Latency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Computational Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Algorithmic Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Zero Algorithmic Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . Basic Algorithmic Delay . . . . . . . . . . . . . . . . . . . . . . . . . . . Excess Algorithmic Delay (Tasking Latency) . . . . . . . . . . . . Predict Tasking Latency . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-59 3-59 3-60 3-61 3-64 3-67 3-69 3-46 3-51 3-54 3-54 Filter Analysis, Design, and Implementation Design a Filter in Fdesign — Process Overview . . . . . . . . . . Process Flow Diagram and Filter Design Methodology . . . . . 4-2 4-2 Design a Filter in the Filterbuilder GUI . . . . . . . . . . . . . . . . The Graphical Interface to Fdesign . . . . . . . . . . . . . . . . . . . 4-10 4-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان vii viii Contents Use FDATool with DSP System Toolbox Software . . . . . . . . Design Advanced Filters in FDATool . . . . . . . . . . . . . . . . . Access the Quantization Features of FDATool . . . . . . . . . . . Quantize Filters in FDATool . . . . . . . . . . . . . . . . . . . . . . . . Analyze Filters with a Noise-Based Method . . . . . . . . . . . . Scale Second-Order Section Filters . . . . . . . . . . . . . . . . . . . Reorder the Sections of Second-Order Section Filters . . . . . View SOS Filter Sections . . . . . . . . . . . . . . . . . . . . . . . . . . Import and Export Quantized Filters . . . . . . . . . . . . . . . . . Generate MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . Import XILINX Coefficient (.COE) Files . . . . . . . . . . . . . . . Transform Filters Using FDATool . . . . . . . . . . . . . . . . . . . . Design Multirate Filters in FDATool . . . . . . . . . . . . . . . . . . Realize Filters as Simulink Subsystem Blocks . . . . . . . . . . . 4-14 4-14 4-18 4-20 4-28 4-33 4-37 4-42 4-47 4-52 4-53 4-53 4-62 4-74 Digital Frequency Transformations . . . . . . . . . . . . . . . . . . . Details and Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . Frequency Transformations for Real Filters . . . . . . . . . . . . Frequency Transformations for Complex Filters . . . . . . . . . 4-77 4-77 4-85 4-99 Digital Filter Design Block . . . . . . . . . . . . . . . . . . . . . . . . . . Overview of the Digital Filter Design Block . . . . . . . . . . . . Select a Filter Design Block . . . . . . . . . . . . . . . . . . . . . . . Create a Lowpass Filter in Simulink . . . . . . . . . . . . . . . . . Create a Highpass Filter in Simulink . . . . . . . . . . . . . . . . Filter High-Frequency Noise in Simulink . . . . . . . . . . . . . 4-111 4-111 4-112 4-113 4-114 4-116 Filter Realization Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview of the Filter Realization Wizard . . . . . . . . . . . . . Design and Implement a Fixed-Point Filter in Simulink . . Set the Filter Structure and Number of Filter Sections . . . Optimize the Filter Structure . . . . . . . . . . . . . . . . . . . . . . 4-121 4-121 4-121 4-130 4-131 Digital Filter Implementations . . . . . . . . . . . . . . . . . . . . . . Using Digital Filter Blocks . . . . . . . . . . . . . . . . . . . . . . . . Implement a Lowpass Filter in Simulink . . . . . . . . . . . . . Implement a Highpass Filter in Simulink . . . . . . . . . . . . . Filter High-Frequency Noise in Simulink . . . . . . . . . . . . . Specify Static Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specify Time-Varying Filters . . . . . . . . . . . . . . . . . . . . . . . Specify the SOS Matrix (Biquadratic Filter Coefficients) . . 4-133 4-133 4-133 4-134 4-135 4-140 4-140 4-141 Analog Filter Design Block . . . . . . . . . . . . . . . . . . . . . . . . . . 4-143 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Removing High-Frequency Noise from an ECG Signal . . . 4-145 Adaptive Filters 5 Overview of Adaptive Filters and Applications . . . . . . . . . . . Introduction to Adaptive Filtering . . . . . . . . . . . . . . . . . . . . . Adaptive Filtering Methodology . . . . . . . . . . . . . . . . . . . . . . Choosing an Adaptive Filter . . . . . . . . . . . . . . . . . . . . . . . . . System Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inverse System Identification . . . . . . . . . . . . . . . . . . . . . . . . Noise or Interference Cancellation . . . . . . . . . . . . . . . . . . . . Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 5-2 5-2 5-4 5-5 5-6 5-7 5-7 Adaptive Filters in DSP System Toolbox Software . . . . . . . . Overview of Adaptive Filtering in DSP System Toolbox Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using Adaptive Filter Objects . . . . . . . . . . . . . . . . . . . . . . . 5-9 5-9 5-9 5-12 LMS Adaptive Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . LMS Methods for adaptfilt Objects . . . . . . . . . . . . . . . . . . . System Identification Using adaptfilt.lms . . . . . . . . . . . . . . System Identification Using adaptfilt.nlms . . . . . . . . . . . . . Noise Cancellation Using adaptfilt.sd . . . . . . . . . . . . . . . . . Noise Cancellation Using adaptfilt.se . . . . . . . . . . . . . . . . . Noise Cancellation Using adaptfilt.ss . . . . . . . . . . . . . . . . . 5-13 5-13 5-15 5-18 5-20 5-23 5-27 RLS Adaptive Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compare RLS and LMS Adaptive Filter Algorithms . . . . . . Inverse System Identification Using adaptfilt.rls . . . . . . . . . 5-32 5-32 5-33 Signal Enhancement Using LMS and Normalized LMS . . . Create the Signals for Adaptation . . . . . . . . . . . . . . . . . . . . Construct Two Adaptive Filters . . . . . . . . . . . . . . . . . . . . . . Choose the Step Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Set the Adapting Filter Step Size . . . . . . . . . . . . . . . . . . . . Filter with the Adaptive Filters . . . . . . . . . . . . . . . . . . . . . Compute the Optimal Solution . . . . . . . . . . . . . . . . . . . . . . Plot the Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-37 5-37 5-38 5-38 5-39 5-40 5-40 5-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان ix 6 x Contents Compare the Final Coefficients . . . . . . . . . . . . . . . . . . . . . . Reset the Filter Before Filtering . . . . . . . . . . . . . . . . . . . . . Investigate Convergence Through Learning Curves . . . . . . . Compute the Learning Curves . . . . . . . . . . . . . . . . . . . . . . Compute the Theoretical Learning Curves . . . . . . . . . . . . . 5-42 5-43 5-43 5-44 5-45 Adaptive Filters in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . Create an Acoustic Environment in Simulink . . . . . . . . . . . LMS Filter Configuration for Adaptive Noise Cancellation . Modify Adaptive Filter Parameters During Model Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adaptive Filtering Examples . . . . . . . . . . . . . . . . . . . . . . . . 5-46 5-46 5-48 Selected Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-60 5-54 5-59 Multirate and Multistage Filters Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why Are Multirate Filters Needed? . . . . . . . . . . . . . . . . . . . Overview of Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . . 6-2 6-2 6-2 Multistage Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Why Are Multistage Filters Needed? . . . . . . . . . . . . . . . . . . . Optimal Multistage Filters in DSP System Toolbox . . . . . . . . 6-6 6-6 6-6 Example Case for Multirate/Multistage Filters . . . . . . . . . . . Example Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Single-Rate/Single-Stage Equiripple Design . . . . . . . . . . . . . Reduce Computational Cost Using Mulitrate/Multistage Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compare the Responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . Further Performance Comparison . . . . . . . . . . . . . . . . . . . . . 6-7 6-7 6-7 6-8 6-8 6-9 Filter Banks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Dyadic Analysis Filter Banks . . . . . . . . . . . . . . . . . . . . . . . Dyadic Synthesis Filter Banks . . . . . . . . . . . . . . . . . . . . . . 6-11 6-11 6-15 Multirate Filtering in Simulink . . . . . . . . . . . . . . . . . . . . . . . 6-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Transforms, Estimation, and Spectral Analysis Transform Time-Domain Data into Frequency Domain . . . . 7-2 Transform Frequency-Domain Data into Time Domain . . . . 7-7 Linear and Bit-Reversed Output Order . . . . . . . . . . . . . . . . FFT and IFFT Blocks Data Order . . . . . . . . . . . . . . . . . . . . Find the Bit-Reversed Order of Your Frequency Indices . . . 7-12 7-12 7-12 Calculate Channel Latencies Required for Wavelet Reconstruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Analyze Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Calculate the Group Delay of Your Filters . . . . . . . . . . . . . Reconstruct the Filter Bank System . . . . . . . . . . . . . . . . . . Equalize the Delay on Each Filter Path . . . . . . . . . . . . . . . Update and Run the Model . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14 7-14 7-16 7-18 7-18 7-21 7-22 Spectral Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23 Power Spectrum Estimates . . . . . . . . . . . . . . . . . . . . . . . . . . Create the Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . Set the Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . View the Power Spectrum Estimates . . . . . . . . . . . . . . . . . . 7-24 7-24 7-25 7-32 Spectrograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modify the Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . Set the Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . View the Spectrogram of the Speech Signal . . . . . . . . . . . . . 7-35 7-35 7-37 7-41 Mathematics 8 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Statistics Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Basic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Running Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-2 8-2 8-2 8-3 xi Linear Algebra and Least Squares . . . . . . . . . . . . . . . . . . . . . Linear Algebra Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Linear System Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Matrix Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Matrix Inverses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fixed-Point Design 9 xii Contents 8-5 8-5 8-5 8-7 8-8 Fixed-Point Signal Processing . . . . . . . . . . . . . . . . . . . . . . . . . Fixed-Point Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Benefits of Fixed-Point Hardware . . . . . . . . . . . . . . . . . . . . . Benefits of Fixed-Point Design with System Toolboxes Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2 9-2 9-2 Fixed-Point Concepts and Terminology . . . . . . . . . . . . . . . . . Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Precision and Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4 9-4 9-5 9-6 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modulo Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Two's Complement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Addition and Subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9 9-9 9-10 9-11 9-12 9-14 Fixed-Point Support for MATLAB System Objects . . . . . . . Get Information About Fixed-Point System Objects . . . . . . . Display Fixed-Point Properties for System Objects . . . . . . . Set System Object Fixed-Point Properties . . . . . . . . . . . . . . Full Precision for Fixed-Point System Objects . . . . . . . . . . . 9-19 9-19 9-22 9-23 9-24 Specify Fixed-Point Attributes for Blocks . . . . . . . . . . . . . . Fixed-Point Block Parameters . . . . . . . . . . . . . . . . . . . . . . . Specify System-Level Settings . . . . . . . . . . . . . . . . . . . . . . . Inherit via Internal Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . Specify Data Types for Fixed-Point Blocks . . . . . . . . . . . . . 9-25 9-25 9-28 9-29 9-39 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-3 Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scalar Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Vector Quantizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-47 9-47 9-54 Fixed-Point Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . Overview of Fixed-Point Filters . . . . . . . . . . . . . . . . . . . . . . Data Types for Filter Functions . . . . . . . . . . . . . . . . . . . . . Floating-Point to Fixed-Point Filter Conversion . . . . . . . . . Create an FIR Filter Using Integer Coefficients . . . . . . . . . Fixed-Point Filtering in Simulink . . . . . . . . . . . . . . . . . . . . 9-61 9-61 9-61 9-62 9-71 9-87 C Code Generation 10 11 Understanding C Code Generation . . . . . . . . . . . . . . . . . . . . C Code Generation with the Simulink Coder Product . . . . . Highly Optimized Generated ANSI C Code . . . . . . . . . . . . . 10-2 10-2 10-3 Functions and System Objects Supported for C Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-4 C Code Generation from MATLAB . . . . . . . . . . . . . . . . . . . 10-12 C Code Generation from Simulink . . . . . . . . . . . . . . . . . . . Open and Run the Model . . . . . . . . . . . . . . . . . . . . . . . . . Generate Code from the Model . . . . . . . . . . . . . . . . . . . . . Build and Run the Generated Code . . . . . . . . . . . . . . . . . . 10-13 10-13 10-15 10-15 How to Run a Generated Executable Outside MATLAB . . 10-18 DSP System Toolbox Supported Hardware . . . . . . . . . . . . 10-19 Define New System Objects Summary List of Methods for Defining New System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-3 xiii xiv Contents Define Basic System Objects . . . . . . . . . . . . . . . . . . . . . . . . . 11-5 Change Number of Step Inputs or Outputs . . . . . . . . . . . . . 11-7 Specify System Block Input and Output Names . . . . . . . . 11-11 Validate Property and Input Values . . . . . . . . . . . . . . . . . . 11-13 Initialize Properties and Setup One-Time Calculations . . 11-16 Set Property Values at Construction Time . . . . . . . . . . . . . 11-19 Reset Algorithm State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-21 Define Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23 Hide Inactive Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-27 Limit Property Values to Finite String Set . . . . . . . . . . . . 11-29 Process Tuned Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32 Release System Object Resources . . . . . . . . . . . . . . . . . . . . 11-34 Define Composite System Objects . . . . . . . . . . . . . . . . . . . . 11-36 Define Finite Source Objects . . . . . . . . . . . . . . . . . . . . . . . . 11-39 Save System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-41 Load System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-44 Clone System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-47 Define System Object Information . . . . . . . . . . . . . . . . . . . 11-48 Define System Block Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-50 Add Header to System Block Dialog . . . . . . . . . . . . . . . . . . 11-52 Add Property Groups to System Object and Block Dialog 11-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 Set Output Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-58 Set Output Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-60 Set Output Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-62 Specify Whether Output Is Fixed- or Variable-Size . . . . . . 11-64 Specify Discrete State Output Specification . . . . . . . . . . . 11-66 Use Update and Output for Nondirect Feedthrough . . . . . 11-68 Enable For Each Subsystem Support . . . . . . . . . . . . . . . . . 11-71 Methods Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setup Method Call Sequence . . . . . . . . . . . . . . . . . . . . . . . Step Method Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . Reset Method Call Sequence . . . . . . . . . . . . . . . . . . . . . . . Release Method Call Sequence . . . . . . . . . . . . . . . . . . . . . 11-73 11-73 11-73 11-74 11-75 System Object Input Arguments and ~ in Code Examples 11-76 What Are Mixin Classes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-77 Best Practices for Defining System Objects . . . . . . . . . . . . 11-78 HDL Code Generation What is HDL Code Generation? . . . . . . . . . . . . . . . . . . . . . . . 12-2 Blocks With HDL Support . . . . . . . . . . . . . . . . . . . . . . . . . . . Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Signal Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Signal Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3 12-3 12-3 12-3 12-3 12-4 12-4 12-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان xv System Objects With HDL Support . . . . . . . . . . . . . . . . . . . . 13 14 15 Links to Category Pages Signal Management Library . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2 Sinks Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-3 Math Functions Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4 Filtering Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5 Designing Lowpass FIR Filters Lowpass FIR Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2 Controlling Design Specifications in Lowpass FIR Design . 14-7 Designing Filters with Non-Equiripple Stopband . . . . . . . 14-13 Minimizing Lowpass FIR Filter Length . . . . . . . . . . . . . . . 14-18 FDATool: A Filter Design and Analysis GUI Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . FDATool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Filter Design Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the Filter Design and Analysis Tool . . . . . . . . . . . . . Analyzing Filter Responses . . . . . . . . . . . . . . . . . . . . . . . . . Filter Design and Analysis Tool Panels . . . . . . . . . . . . . . . . Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi Contents 12-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-2 15-2 15-2 15-3 15-4 15-4 15-5 16 Using FDATool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Choosing a Response Type . . . . . . . . . . . . . . . . . . . . . . . . . Choosing a Filter Design Method . . . . . . . . . . . . . . . . . . . . Setting the Filter Design Specifications . . . . . . . . . . . . . . . . Computing the Filter Coefficients . . . . . . . . . . . . . . . . . . . Analyzing the Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Editing the Filter Using the Pole/Zero Editor . . . . . . . . . . Converting the Filter Structure . . . . . . . . . . . . . . . . . . . . . Exporting a Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . Generating a C Header File . . . . . . . . . . . . . . . . . . . . . . . Generating MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . Managing Filters in the Current Session . . . . . . . . . . . . . . Saving and Opening Filter Design Sessions . . . . . . . . . . . . 15-6 15-6 15-7 15-8 15-12 15-12 15-17 15-21 15-23 15-28 15-29 15-30 15-32 Importing a Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . . Import Filter Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Filter Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-33 15-33 15-34 Designing a Filter in the Filterbuilder GUI Filterbuilder Design Process . . . . . . . . . . . . . . . . . . . . . . . . . Introduction to Filterbuilder . . . . . . . . . . . . . . . . . . . . . . . . Design a Filter Using Filterbuilder . . . . . . . . . . . . . . . . . . . Select a Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Select a Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Select an Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Customize the Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . Analyze the Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Realize or Apply the Filter to Input Data . . . . . . . . . . . . . . Designing a FIR Filter Using filterbuilder . . . . . . . . . . . . . FIR Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-2 16-2 16-2 16-2 16-5 16-5 16-7 16-9 16-9 16-11 16-11 xvii Bibliography A xviii Contents Advanced Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2 Adaptive Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3 Multirate Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4 Frequency Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . A-5 Fixed-Point Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 DSP Tutorials • “Introduction to Streaming Signal Processing in MATLAB” on page 1-2 • “Filter Frames of a Noisy Sine Wave Signal in MATLAB” on page 1-10 • “Filter Frames of a Noisy Sine Wave Signal in Simulink” on page 1-12 • “Lowpass Filter Design in MATLAB” on page 1-18 • “Lowpass IIR Filter Design in Simulink” on page 1-27 • “Create Moving Average System object” on page 1-40 • “Tunable Lowpass Filtering of Audio Input in Simulink” on page 1-48 • “Desktop Real-time Audio Acceleration with MATLAB Coder” on page 1-53 • “Fixed-Point Filter Design in MATLAB” on page 1-56 • “Sample Rate Conversion of Audio Signal in MATLAB and Simulink” on page 1-65 • “Visualizing Multiple Signals Using Logic Analyzer” on page 1-74 • “Signal Visualization and Measurements in MATLAB” on page 1-88 • “Filter Frames of a Noisy Sine Wave Signal using Testbench Generator” on page 1-103 • “Create Composite System object” on page 1-110 • “Measure Audio Latency in MATLAB and Simulink” on page 1-115 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 DSP Tutorials Introduction to Streaming Signal Processing in MATLAB This example shows how to do basic signal processing on an audio signal streamed frame by frame from a file. The same framework applies to streaming live audio from a microphone or audio line input. Introduction This example shows how to use components in the DSP System Toolbox called System objects, which are optimized for streaming signal processing. The signals are read in and processed frame by frame (or block by block). You control the frame size. In this example, frames of 1024 samples are read from an audio file every time a while loop executes. The audio in the file is sampled at 44.1 kHz and contains two channels (stereo). Each frame of data is approximately 23.2 milliseconds. The example filters the audio signal using a notch filter. Because filtering is done on each frame, the state of the filter must be maintained from one frame to the next to ensure smooth processing. Initialization Streaming components must be initialized before use. Initialize the audio file reader and audio player to listen to the filtered audio. FrameSize = 1024; AR = dsp.AudioFileReader('Filename','guitar10min.ogg',... 'SamplesPerFrame',FrameSize); Fs = AR.SampleRate; AP = dsp.AudioPlayer('SampleRate',Fs,... 'OutputNumUnderrunSamples',true); Notch Filter This example uses a simple second order IIR notch filter with a biquad (second-order sections) structure to filter the audio signal. The filter has a notch at 200 Hz and a Qfactor of 35. The higher the Q-factor, the narrower the 3 dB bandwidth of the notch. You can change these values and listen to the resulting audio for different filter specifications if desired. The notch filter retains state each time it is executed making it well-suited for streaming data. 1-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Introduction to Streaming Signal Processing in MATLAB Wo = 200/(Fs/2); Q = 35; BW = Wo/Q; [b,a] = iirnotch(Wo,BW); NotchFilter = dsp.BiquadFilter('SOSMatrix',[b,a]); Streaming Next, stream in and process your signal. Construct a while loop to run for 20 seconds. A counter keeps track of how many frames are processed during the 20-second period. Because each frame is 23.2 ms of audio, at least 861 frames must be processed in the 20second period for the system to operate in real time or faster. tic Tstop = 20; count = 0; while toc < Tstop audioIn = step(AR); audioOut = step(NotchFilter,audioIn); plot(audioOut) drawnow count = count + 1; end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-3 1 DSP Tutorials On a reasonably fast computer, the value of count exceeds 861 frames meaning the processing can be done in real time or faster. Streaming Without DSP Components Instead of using System objects, you can use the audioread and filter functions. However, audioread is not well-suited for streaming, because the file name and position must be provided at each call. As a result, the performance of audioread is considerably slower than the performance of the System object file reader in a streaming application. filter provides adequate performance, but state must be passed in and out of filter for use in a streaming application. This can result in inefficient and complicated code if there are many components with state that must be handled manually. z = []; 1-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Introduction to Streaming Signal Processing in MATLAB tic count = 0; while toc < Tstop audioIn = audioread('guitar10min.ogg',count*FrameSize+[1 FrameSize]); [audioOut,z] = filter(b,a,audioIn,z); plot(audioOut) drawnow count = count + 1; end The plot update gives a visual indication of how much slower the code is with audioread and filter is compared to the System object implementation. In particular, count is considerably less than 861 frames, and therefore processing real-time audio in this fashion is not feasible. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-5 1 DSP Tutorials Listening to The Filtered Signal On computers capable of processing the data in real time or better, you have to add only a single line of code to listen to the filtered signal as it is being processed. A new variable, dropped, keeps count of any dropped samples due to buffer underrun. tic dropped = 0; count = 0; while toc < Tstop audioIn = step(AR); audioOut = step(NotchFilter,audioIn); plot(audioOut) drawnow count = count + 1; dropped = dropped + step(AP,audioOut); end 1-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Introduction to Streaming Signal Processing in MATLAB On most machines, there are no dropped samples. Better Way of Plotting Rather than using plot and drawnow to monitor the audio signal, use a System object time scope. The time scope provides better performance along with many other features, for example, measurements and panning. If you want to plot the spectrum of the signal in real time, you can use a spectrum analyzer (dsp.SpectrumAnalyzer). TS = dsp.TimeScope('YLimits',[-1,1],'SampleRate',Fs,... 'TimeSpan',FrameSize/Fs); step(TS,audioOut); tic count = 0; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-7 1 DSP Tutorials while toc < Tstop % Run for 20 seconds audioIn = step(AR); audioOut = step(NotchFilter,audioIn); step(TS,audioOut); count = count + 1; dropped = dropped + step(AP,audioOut); end However, for maximum performance, avoid plotting the signal in time or frequency. 1-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Introduction to Streaming Signal Processing in MATLAB Streaming Live Audio To stream audio from a microphone or line input, use the audio recorder, dsp.AudioRecorder. If you want to write the processed audio to disk, use the audio file writer, dsp.AudioFileWriter. The audio file writer supports a number of the most common audio formats such as WAV, OGG, FLAC, and M4A. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-9 1 DSP Tutorials Filter Frames of a Noisy Sine Wave Signal in MATLAB This example shows how to lowpass filter a noisy signal and visualize the original and filtered signals using a spectrum analyzer. There is a Simulink version of this example: Filter Frames of a Noisy Signal in Simulink Source The input signal is the sum of two sine waves with frequencies of 1 kHz and 10 kHz. The sampling frequency is 44.1 kHz. Sine1 = dsp.SineWave('Frequency',1e3,'SampleRate',44.1e3); Sine2 = dsp.SineWave('Frequency',10e3,'SampleRate',44.1e3); Lowpass Filter The lowpass FIR filter uses a constrained equiripple filter design (firceqrip). The filter's cutoff frequency is 5 kHz and the linear ripples in the passband and stopband are equal to 0.05 and 0.001. FIRLowPass = dsp.FIRFilter('Numerator', ... firceqrip(30,5e3*2/44.1e3,[0.05 1e-3])); Spectrum Analyzer Set up the spectrum analyzer to compare the power spectra of the original and filtered signals. The spectrum units are dBm. SpecAna = dsp.SpectrumAnalyzer('PlotAsTwoSidedSpectrum',false, ... 'SampleRate',Sine1.SampleRate, ... 'ReducePlotRate',false, ... 'ShowLegend',true, ... 'YLimits',[-145,45]); Frame-Based Processing This example uses frame-based processing. In frame-based processing, the data is processed one frame at a time. Each frame of data contains sequential samples from an independent channel. Frame-based processing is advantageous for many signal processing applications because you can process multiple samples at once. By buffering your data into frames and processing multi-sample frames of data, you often improve the computational time of your signal processing algorithms. In this example, the number of samples per frame is 1024. The FIR filter uses frame-based processing if the input is frame based. 1-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal in MATLAB Sine1.SamplesPerFrame = 1024; Sine2.SamplesPerFrame = 1024; Simulation Results Add zero-mean white Gaussian noise with a standard deviation of 0.1 to the sum of sine waves and filter the result with the FIR filter. While running the simulation, you see in the spectrum analyzer that frequencies above 4 kHz in the source signal are attenuated. The resulting signal maintains the peak at 1 kHz because it falls in the passband of the lowpass filter. tic while toc<5 x = step(Sine1)+step(Sine2)+0.1.*randn(Sine1.SamplesPerFrame,1); y = step(FIRLowPass,x); step(SpecAna,[x,y]); end release(SpecAna) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-11 1 DSP Tutorials Filter Frames of a Noisy Sine Wave Signal in Simulink This example shows how to lowpass filter a noisy signal in Simulink® and visualize the power spectra of the original and filtered signals with a spectrum analyzer. There is also a MATLAB® version of this example: “Filter Frames of a Noisy Sine Wave Signal in MATLAB” on page 1-10. The example is based on the following model: model = 'ex_filtering_frames'; open_system(model); In this section... “Source” on page 1-13 1-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal in Simulink In this section... “Lowpass Filter” on page 1-15 “Spectrum Analyzer” on page 1-15 Source Three source blocks comprise the input signal. The input signal consists of the sum of two sine waves and white Gaussian noise with mean 0 and variance 0.01. The frequencies of the sine waves are 1 kHz and 10 kHz. The sampling frequency is 44.1 kHz. The following figure shows the block parameters for the 1 kHz sine wave. Open the other source blocks to see their parameters. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-13 DSP Tutorials ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 1-14 Filter Frames of a Noisy Sine Wave Signal in Simulink Lowpass Filter The lowpass filter is modeled using a Discrete FIR Filter block. The example uses a constrained equiripple FIR filter design, firceqrip. The filter's cutoff frequency is 5 kHz, and the linear ripples in the passband and stopband are equal to 0.05 and 1e-3. Spectrum Analyzer The power spectra of the original and filtered signals are compared using a spectrum analyzer (Spectrum Analyzer). The spectrum units are in dBm. This example uses frame-based processing. In frame-based processing, blocks process data one frame at a time. Each frame of data contains sequential samples from an www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-15 1 DSP Tutorials independent channel. Frame-based processing is advantageous for many signal processing applications because you can process multiple samples at once. By buffering your data into frames and processing multi-sample frames of data, you often improve the computational time of your signal processing algorithms. In this example, the number of samples per frame is 1024. Specify frame-based processing on the FIR filter by setting the Input Processing parameter to 'Columns as channels (frame based)'. To run the simulation, click the Run button in the model. To stop the simulation, click the Stop button in the Spectrum Analyzer. Alternatively, you can execute the following code to run the simulation for 200 frames of data. set_param(model,'StopTime','1024/44100 * 200') sim(model); 1-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal in Simulink In the spectrum analyzer you see that frequencies above 4 kHz in the source signal are attenuated. The resulting signal maintains the peak at 1 kHz because it falls in the passband of the lowpass filter. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-17 1 DSP Tutorials Lowpass Filter Design in MATLAB This example shows how to design lowpass filters. The example highlights some of the most commonly used command-line tools in the DSP System Toolbox. Alternatively, you can use the Filter Builder app to implement all the designs presented here. For more design options, see Designing Low Pass FIR Filters. Introduction When designing a lowpass filter, the first choice you make is whether to design an FIR or IIR filter. You generally choose FIR filters when a linear phase reponse is important. FIR filters also tend to be preferred for fixed-point implementations because they are typically more robust to quantization effects. FIR filters are also used in many high-speed implementations such as FPGAs or ASICs because they are suitable for pipelining. IIR filters (in particular biquad filters) are used in applications (such as audio signal processing) where phase linearity is not a concern. IIR filters are generally computationally more efficient in the sense that they can meet the design specifications with fewer coefficients than FIR filters. IIR filters also tend to have a shorter transient response and a smaller group delay. However, the use of minimum-phase and multirate designs can result in FIR filters comparable to IIR filters in terms of group delay and computational efficiency. FIR Lowpass Designs - Specifying the Filter Order There are many practical situations in which you must specify the filter order. One such case is if you are targeting hardware which has constrained the filter order to a specific number. Another common scenario is when you have computed the available computational budget (MIPS) for your implementation and this affords you a limited filter order. FIR design functions in the Signal Processing Toolbox (including fir1, firpm, and firls) are all capable of designing lowpass filters with a specified order. In the DSP System Toolbox, the preferred function for lowpass FIR filter design with a specified order is firceqrip. This function designs optimal equiripple lowpass/highpass FIR filters with specified passband/stopband ripple values and with a specified passbandedge frequency. The stopband-edge frequency is determined as a result of the design. Design a lowpass FIR filter for data sampled at 48 kHz. The passband-edge frequency is 8 kHz. The passband ripple is 0.01 dB and the stopband attenuation is 80 dB. Constrain the filter order to 120. N Fs 1-18 = 120; = 48e3; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass Filter Design in MATLAB Fp = 8e3; Ap = 0.01; Ast = 80; Obtain the maximum deviation for the passband and stopband ripples in linear units. Rp = (10^(Ap/20) - 1)/(10^(Ap/20) + 1); Rst = 10^(-Ast/20); Design the filter using firceqrip and view the magnitude frequency response. NUM = firceqrip(N,Fp/(Fs/2),[Rp Rst],'passedge'); fvtool(NUM,'Fs',Fs) The resulting stopband-edge frequency is about 9.64 kHz. Minimum-Order Designs Another design function for optimal equiripple filters is firgr. firgr can design a filter that meets passband/stopband ripple constraints as well as a specified transition www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-19 1 DSP Tutorials width with the smallest possible filter order. For example, if the stopband-edge frequency is specified as 10 kHz, the resulting filter has an order of 100 rather than the 120thorder filter designed with firceqrip. The smaller filter order results from the larger transition band. Specify the stopband-edge frequency of 10 kHz. Obtain a minimum-order FIR filter with a passband ripple of 0.01 dB and 80 dB of stopband attenuation. Fst = 10e3; NumMin = firgr('minorder',[0 Fp/(Fs/2) Fst/(Fs/2) 1], [1 1 0 0],[Rp,Rst]); Plot the magnitude frequency responses for the minimum-order FIR filter obtained with firgr and the 120th-order filter designed with firceqrip. The minimum-order design results in a filter with order 100. The transition region of the 120th-order filter is, as expected, narrower than that of the filter with order 100. fvtool(NUM,1,NumMin,1,'Fs',Fs); legend('N = 120','N = 100'); 1-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass Filter Design in MATLAB Filtering Data To apply the filter to data, you can use the filter command or you can use dsp.FIRFilter. dsp.FIRFilter has the advantage of managing state when executed in a loop. dsp.FIRFilter also has fixed-point capabilities. Filter 10 seconds of white noise with zero mean and unit standard deviation in frames of 256 samples with the 120th-order FIR lowpass filter. View the result on a spectrum analyzer. LP_FIR = dsp.FIRFilter('Numerator',NUM); SA = dsp.SpectrumAnalyzer('SampleRate',Fs,'SpectralAverages',5); tic while toc < 10 x = randn(256,1); y = step(LP_FIR,x); step(SA,y); end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-21 1 DSP Tutorials Using FDESIGN fdesign is an alternative to firceqrip and firgr that provides several additional capabilities. The fdesign filter design process consists of two steps. In the first step, you provide your design specifications. In the second step, you design the filter based on your specifications. With fdesign, you can enter magnitude specifications directly in decibels and frequency specifications directly in Hz. Design a lowpass FIR filter for data sampled at 48 kHz. The passband-edge frequency is 8 kHz. The passband ripple is 0.01 dB and the stopband attenuation is 80 dB. Constrain the filter order to 120. Create a dsp.FIRFilter based on your specifications. LP_Specs = fdesign.lowpass('N,Fp,Ap,Ast',N,Fp,Ap,Ast,Fs); LP_FIR = design(LP_Specs,'equiripple','SystemObject',true); The coefficients in LP_FIR.Numerator are identical to the coefficients in NUM. Because LP_FIR is a dsp.FIRFilter object, you can use LP_FIR to filter data directly, as shown in the preceding example. You can also analyze the filter using FVTool or measure the response using measure. fvtool(LP_FIR,'Fs',Fs); measure(LP_FIR) ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width 1-22 : : : : : : : : 48 kHz 8 kHz 8.5843 kHz 8.7553 kHz 9.64 kHz 0.01 dB 79.9981 dB 1.64 kHz www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass Filter Design in MATLAB Minimum-Order Designs with FDESIGN You can use fdesign to design minimum-order filters and use measure to verify that the design meets the prescribed specifications. The order of the filter is again 100. LP_Specs_minOrd = fdesign.lowpass('Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast,Fs); LP_FIR_minOrd = design(LP_Specs_minOrd,'equiripple','SystemObject',true); measure(LP_FIR_minOrd) Order = length(LP_FIR_minOrd.Numerator)-1 ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple : : : : : : 48 kHz 8 kHz 8.7134 kHz 8.9219 kHz 10 kHz 0.0099327 dB www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-23 1 DSP Tutorials Stopband Atten. : 80.0363 dB Transition Width : 2 kHz Order = 100 Designing IIR Filters Elliptic filters are the IIR counterpart to optimal equiripple FIR filters. Accordingly, you can use the same specifications to design elliptic filters. The filter order you obtain for an IIR filter is much smaller than the order of the corresponding FIR filter. Design an elliptic filter with the same sampling frequency, cutoff frequency, passbandripple constraint, and stopband attenuation as the 120th-order FIR filter. Reduce the filter order for the elliptic filter to 10. LP_Specs.FilterOrder = 10; LP_IIR = design(LP_Specs,'ellip','SystemObject',true); Compare the FIR and IIR designs. Compute the cost of the two implementations. hfvt = fvtool(LP_FIR,LP_IIR,'Fs',Fs); legend(hfvt,'FIR Equiripple, N = 120', 'IIR Elliptic, N = 10'); cost_FIR = cost(LP_FIR) cost_IIR = cost(LP_IIR) cost_FIR = Number of Multipliers Number of Adders Number of States Multiplications per Input Sample Additions per Input Sample : : : : : 121 120 120 121 120 : : : : : 20 20 10 20 20 cost_IIR = Number of Multipliers Number of Adders Number of States Multiplications per Input Sample Additions per Input Sample 1-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass Filter Design in MATLAB The FIR and IIR filters have similar magnitude responses. The cost of the IIR filter is about 1/6 the cost of the FIR filter. Running the IIR Filters The IIR filter is designed as a biquad filter and implemented using dsp.BiquadFilter. To apply the filter to data, use the same commands as in the FIR case. Filter 10 seconds of white Gaussian noise with zero mean and unit standard deviation in frames of 256 samples with the 10th-order IIR lowpass filter. View the result on a spectrum analyzer. SA = dsp.SpectrumAnalyzer('SampleRate',Fs,'SpectralAverages',5); tic while toc < 10 x = randn(256,1); y = step(LP_IIR,x); step(SA,y); end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-25 DSP Tutorials ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 1-26 Lowpass IIR Filter Design in Simulink Lowpass IIR Filter Design in Simulink In this section... “Model” on page 1-27 “Butterworth Filter” on page 1-28 “Chebyshev Type I Filter” on page 1-30 “Chebyshev Type II Filter” on page 1-32 “Elliptic Filter” on page 1-34 “Minimum-Order Designs” on page 1-36 This example shows how to design classic lowpass IIR filters in Simulink. The initial focus is on the situation in which the critical design parameter is the cutoff frequency where the filter's power decays to half (-3 dB) the nominal passband value. The example shows how to replace a Butterworth design with either a Chebyshev or elliptic filter of the same order and obtain a steeper roll-off at the expense of some ripple in the passband and/or stopband of the filter. The example also explores minimum-order designs. Model This example is based on the Simulink model ex_iir_design. The model includes one lowpass filter for each of the four designs: Butterworth, Chebyshev type 1, Chebyshev type 2, and elliptic. You can use the link under Select Filter to switch between designs at any point during the simulation. A stereo audio signal sampled at 44.1 kHz is passed through the filter. The audio input is corrupted by N(0,10-5) Gaussian noise passed through a highpass filter. The original and filtered signals are displayed in a spectrum analyzer. You can listen to either the original or filtered signal by toggling the Manual Switch at the input of the To Audio Device block. The filters in this example all use direct-form II second-order sections (SOS). model = 'ex_iir_design'; open_system(model); set_param(model,'StopTime','1024/44100 * 100') sim(model); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-27 1 DSP Tutorials Butterworth Filter The first filter block is an 8-th order Butterworth lowpass filter with a cutoff frequency of 5 kHz. This filter is maximally flat (no ripple in the passband or in the stopband). Double click on the block to open the block dialog. You can visualize the filter's frequency response by clicking the View Filter Response button on the block's dialog. 1-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-29 1 DSP Tutorials Chebyshev Type I Filter A Chebyshev type I design allows you to control the passband. There are still no ripples in the stopband. Larger ripples enable a steeper roll-off. In this model, the peak-to-peak ripple is specified to be 0.5 dB. 1-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-31 1 DSP Tutorials Zooming in on the passband, you can see that the ripples are contained in the range [-0.5, 0] dB. Chebyshev Type II Filter A Chebyshev type II design allows you to control the stopband attenuation. There are no ripples in the passband. A smaller stopband attenuation enables a steeper roll-off. In this example, the stopband attenuation is 80 dB. 1-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-33 1 DSP Tutorials Elliptic Filter An elliptic filter can provide steeper roll-off compared to previous designs by allowing ripples in both the stopband and passband. To illustrate this, use the same passband and stopband characteristics specified in the Chebyshev designs. 1-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-35 1 DSP Tutorials Minimum-Order Designs In cases where you specify the passband and stopband in terms of frequencies and the amount of tolerable ripple, you can use a minimum-order design. As an example, the Order mode of the Butterworth filter is set to Minimum. The normalized passband and stopband frequencies are set to 0.1*22050 Hz and 0.3*22050 Hz. The passband ripple is 1 dB and the stopband attenuation is 60 dB. A 7-th order filter is necessary to meet the specifications with a Butterworth design. By following the same approach on the other filter blocks, you can verify that a 5-th order filter is required for Chebyshev type I and type II designs. A 4-th order filter is sufficient for the elliptic design. 1-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-37 1 DSP Tutorials The following figure shows the magnitude response for the 7-th order Butterworth design. The pole-zero plot for the 7-th order Butterworth design shows the expected clustering of 7 poles around an angle of zero radians on the unit circle and the corresponding 7 zeros at angle of π radians. 1-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass IIR Filter Design in Simulink Close the model to finish the tutorial. close_system(model,0); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-39 1 DSP Tutorials Create Moving Average System object In this section... “Introduction” on page 1-40 “Create the Class Definition ” on page 1-41 “Moving Average Filter Properties” on page 1-41 “Moving Average Filter Constructor” on page 1-42 “Moving Average Filter Setup” on page 1-43 “Moving Average Filter Step” on page 1-43 “Moving Average Filter Reset” on page 1-44 “Input Validation” on page 1-44 “Object Saving and Loading” on page 1-44 “System object Usage in MATLAB” on page 1-45 “Simulink Customization Methods” on page 1-46 “System object Usage in Simulink” on page 1-46 Introduction This example shows how to create a System object™ that implements a moving average filter. The example shows how to use the System object in MATLAB and Simulink through the MATLAB System block. MovingAverageFilter is a simple moving average System object filter, which computes the unweighted mean of the previous WindowLength input samples, where WindowLength is the length of the moving average window. The System object accepts single-precision and double-precision 2-D input matrices. Each column of the input matrix is treated as an independent (1-D) channel. The first dimension of the input defines the length of the channel (or the input frame size). MovingAverageFilter independently computes the moving average of each input channel over time. “System object Usage in MATLAB” on page 1-45 and “System object Usage in Simulink” on page 1-46 show how to use your System object with data. 1-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Moving Average System object Create the Class Definition In the MATLAB Home tab select New -> System Object -> Simulink Extension to open a System object template. This template includes customizations of the System object for use in the MATLAB System block. You can edit the template file, using it as guideline, to create your own System object. Replace all occurrences of Untitled in the file with MovingAverageFilter and save the file as MovingAverageFilter.m in a folder where you have write permission. You need to add this folder to the MATLAB path to use the System object. For convenience, the entire System object is provided in the file dspdemo.MovingAverageFilter.m. To view this file enter edit dspdemo.MovingAverageFilter at the MATLAB command prompt. The prefix dspdemo on dspdemo.MovingAverageFilter is a package name. Packages are special folders that can contain class folders, function and class definition files, and other packages. Package folders always begin with the + character such as +dspdemo. Packages define the scope of the contents of the package folder (that is, a namespace in which names must be unique). This means function and class names need to be unique only within the package. Using a package provides a means to organize classes and functions and to select names for these components that other packages can reuse. You do not have to use packages when creating your System object. For more information on packages in MATLAB, see “Packages Create Namespaces”. The remainder of this example shows you how to create the MovingAverageFilter object from the System object template without using a package. However, you can also review and use the completed version, dspdemo.MovingAverageFilter. Moving Average Filter Properties The MovingAverageFilter object has one public property that controls the length of the moving average. Because the algorithm depends on this value being constant once data processing begins, the property is defined as nontunable. Additionally, the property only accepts real, positive integers. To ensure correct input, add the PositiveInteger attribute to the property. The default value of this property is 5. properties (PositiveInteger, Nontunable) % WindowLength Moving average filter length % Specify the length of the moving average filter as a % scalar positive integer value. The default value of this % property is 5. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-41 1 DSP Tutorials WindowLength = 5 end The state of the moving average filter is defined with the DiscreteState attribute. Get the value of the state by calling the getDiscreteState method. properties (DiscreteState) State; end A moving average filter is an FIR Filter with numerator coefficients equal to ones(WindowLength,1)/WindowLength. Because the coefficients do not change during the streaming operation, the coefficients are defined in a property for optimization purposes. Additionally, to ensure the coefficients are not accessible to users of the System object, use the private attribute. properties (Access = private, Nontunable) pCoefficients; end Finally, the System object operates on a possibly multichannel input and therefore requires a property for the number of channels. This property is not accessible to users and therefore you use the private attribute. The value of this property is determined from the number of columns in the input. properties (Access = private) % pNumChannels Property used to cache the number of input channels % (columns). Varying the number of channels during the streaming % operation is not allowed (since it modifes the number of required % states). The default of -1 means that the streaming operation has % not started yet (i.e. the number ofo channels is still unknown). pNumChannels = -1; end Moving Average Filter Constructor The System object constructor is a method that has the same name as the class (MovingAverageFilter in this example). Within that method, use the setProperties method to allow standard name-value pair handling at construction, filt = MovingAverageFilter('WindowLength',10). methods % Constructor function obj = MovingAverageFilter(varargin) 1-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Moving Average System object % Support name-value pair arguments when constructing the % object. setProperties(obj,nargin,varargin{:}); end end Moving Average Filter Setup The setupImpl method sets up the object and implements one-time initialization tasks. The filter coefficients are computed based on the specified window length. The filter's states are initialized to zero. Note that there are WindowLength-1 states per input channel. If you would like to initialize the states to a custom value, you can create a public InitialConditions property and use the property value to set the object state (obj.State) in setupImpl. Finally, the number of channels is determined from the number of columns in the input. function setupImpl(obj,x) numChannels = size(x,2); obj.State = zeros(obj.WindowLength-1,numChannels,'like',x); % Cache the number of channels obj.pNumChannels = numChannels; obj.pCoefficients = ones(1,obj.WindowLength)/obj.WindowLength; end Note: You must set Access = protected for this method. Moving Average Filter Step The object's algorithm is defined in the stepImpl method. The algorithm in stepImpl is executed when the user of the System object calls step at the command line. In this example, stepImpl calculates the output and updates the object's state values using the filter function. function Y = stepImpl(obj,X) % Compute output and update state [Y,obj.State] = filter(obj.pCoefficients,1,X,obj.State); end Note: You must set Access = protected for this method. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-43 1 DSP Tutorials Moving Average Filter Reset The state reset equations are defined in the resetImpl method. In this example, the states are reset to zero. If you want to reset the states to a custom value, you can create a public InitialConditions property and use the property value to reset state in resetImpl. function resetImpl(obj) obj.State(:) = 0; end Note: You must set methods(Access = protected) for this method. Input Validation validateInputsImpl validates inputs to the step method at initialization and at each subsequent call to step where the input attributes (such as dimensions, data type or complexity) change. In this example, validattributes ensures that the input is a 2-D matrix with floating-point data. function validateInputsImpl(obj, u) validateattributes(u,{'double','single'}, {'2d',... 'nonsparse'},'','input'); % The number of input channels is not allowed to change. If % pNumChannels = -1. This means that the streaming operation % has not started yet (i.e. setupImpl has not been invoked % yet). Do not perform the check in that case. coder.internal.errorIf(obj.pNumChannels~=-1 && obj.pNumChannels ~= size(u,2 end Note: You must set methods(Access = protected) for this method. Object Saving and Loading saveObjectImpl defines what property and state values are saved in a MAT-file when you call save on that object. If you do not define a saveObjectImpl method for your System object class, only public properties and properties with the DiscreteState attribute are saved. Save the state of an object only if the object is locked. When you load 1-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Moving Average System object the saved object, the object loads in that locked state. In this System object, the filter coefficients are saved if the object is locked. function s = saveObjectImpl(obj) s = [email protected](obj); if isLocked(obj) s.pCoefficients = obj.pCoefficients; s.pNumChannels = obj.pNumChannels; end end loadObjectImpl defines what System object property and state values are loaded when you load a MAT-file. loadObjectImpl should correspond to your saveObjectImpl to ensure that all saved properties and data are loaded. function loadObjectImpl(obj,s,wasLocked) if wasLocked obj.pCoefficients = s.pCoefficients; obj.pNumChannels = s.pNumChannels; end [email protected](obj,s,wasLocked); end Note: You must set Access = protected for this method. System object Usage in MATLAB This example uses the System object to remove noise from a noisy pulse sequence. The length of the moving average filter is 30 samples. If you are using the predefined dspdemo.MovingAverageFilter, substitute that name for MovingAverageFilter in the class constructor, for example movingAverageFilter = dspdemo.MovingAverageFilter('WindowLength',30);. movingAverageFilter = MovingAverageFilter('WindowLength',30); scope = dsp.TimeScope('SampleRate',1e3,... 'TimeSpan',256 * .01,... 'ShowGrid',true,... 'NumInputPorts',2,... 'LayoutDimensions',[2 1]); for i=1:100 input = (1-2*randi([0 1],1)) * ones(256,1) + 0.5 * randn(256,1); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-45 1 DSP Tutorials output = step(movingAverageFilter,input); step(scope,input,output) end Simulink Customization Methods You need to define a few more methods to be able to use the System object in a Simulink MATLAB System block. These methods are not required if you use the System object only in MATLAB. getOutputSizeImpl returns the sizes of each output port. For System objects with one input and one output and where you want the input and output sizes to be the same, you do not need to implement this method. In the case of MovingAverageFilter, there is one input and output and the size of each is the same. Therefore, remove this method from the class definition of MovingAverageFilter. getDiscreteStateSpecificationImpl returns the size, data type, and complexity of a property. This property must be a discrete-state property. You must define this method if your System object has discrete-state properties and is used in the MATLAB System block. In this example, the method is used to define the State property. function [sz,dt,cp] = getDiscreteStateSpecificationImpl(obj,~) inputSize = propagatedInputSize(obj,1); sz = [obj.WindowLength-1 inputSize(2)]; dt = propagatedInputDataType(obj,1); cp = propagatedInputComplexity(obj,1); end Note: You must set Access = protected for this method. System object Usage in Simulink To use your System object in a Simulink model, drag a MATLAB System block from the User-Defined Functions library in Simulink to your model. Open the block dialog box and set the System object name to MovingAverageFilter. The model ex_movingaverage_filter illustrates the use of the System object in Simulink to filter a noisy pulse sequence. model = 'ex_movingaverage_filter'; open_system(model); 1-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Moving Average System object Run the model by clicking the Run button in the model or entering: sim(model) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-47 1 DSP Tutorials Tunable Lowpass Filtering of Audio Input in Simulink In this section... “Introduction” on page 1-49 “Simulation” on page 1-50 This example shows how to lowpass filter a streaming audio signal by dynamically setting the passband frequency. A slider is used to set this parameter while the simulation is running. The power spectrum of the input and filtered audio are compared using a spectrum analyzer. This example is based on the following Simulink model. model = 'ex_tunable_audio_lowpass'; open_system(model); 1-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Tunable Lowpass Filtering of Audio Input in Simulink Introduction The input signal in this example is audio sampled at 22.5 kHz. The audio is read in from a file 256 samples at a time. The audio is passed through a lowpass variable bandwidth IIR filter and the result is played through the system's default audio output device. You can use the switch in the model to compare the filtered and unfiltered audio. The filter is implemented in dsp.VariableBandwidthIIRFilter and used in Simulink in a MATLAB System block. Having a variable bandwidth filter allows you to change the filter parameters while the simulation is running. In this example, the passband frequency of the lowpass filter is tunable. The algorithm in dsp.VariableBandwidthIIRFilter works by using frequency transformations to recompute the filter coefficients when the passband www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-49 1 DSP Tutorials frequency is changed. This removes the need to redesign the whole filter. This also explains why the filter order, passband ripple, and stopband attenuation are not tunable in real time. Simulation Simulating the model, you can hear the filtered audio and compare the power spectrum of the filtered audio to the original unfiltered version. 1-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Tunable Lowpass Filtering of Audio Input in Simulink You can also change the passband frequency of the filter while the simulation is running. In order to do this, either double-click the Variable Bandwidth IIR Filter block or click on the blue Tune passband frequency link. In the dialog that opens, change the value of the Filter passband frequency. The effect of this change is immediately applied and www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-51 1 DSP Tutorials you can observe the effects in the spectrum analyzer as well as hear the change in the audio output. 1-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Desktop Real-time Audio Acceleration with MATLAB Coder Desktop Real-time Audio Acceleration with MATLAB Coder In this section... “Introduction” on page 1-53 “Notch Filtering” on page 1-53 “C Code Generation Speedup” on page 1-54 This example shows how to accelerate a real-time audio application using C code generation with MATLAB Coder™. You must have the MATLAB Coder software installed to run this example. Introduction Replacing parts of your MATLAB code with an automatically generated MATLAB executable (MEX-function) can speedup simulation. Using MATLAB Coder, you can generate readable and portable C code and compile it into a MEX-function that replaces the equivalent section of your MATLAB algorithm. This example showcases code generation using an audio notch filtering application. Notch Filtering A notch filter is used to eliminate a specific frequency from a signal. Typical filter design parameters for notch filters are the notch center frequency and the 3 dB bandwidth. The center frequency is the frequency at which the filter has a linear gain of zero. The 3 dB bandwidth measures the frequency width of the notch of the filter computed at the halfpower or 3 dB attenuation point. The helper function used in this example is helperAudioToneRemoval. The function reads an audio signal corrupted by a 250 Hz sinusoidal tone from a file. helperAudioToneRemoval uses a notch filter to remove the interfering tone and writes the filtered signal to a file. You can visualize the corrupted audio signal using a spectrum analyzer. scope = dsp.SpectrumAnalyzer('SampleRate',44.1e3,... 'RBWSource','Property','RBW',5,... 'PlotAsTwoSidedSpectrum',false,... 'SpectralAverages',10,... www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-53 1 DSP Tutorials 'FrequencySpan','Start and stop frequencies',... 'StartFrequency',20,... 'StopFrequency',1000,... 'Title','Audio signal corrupted by 250 Hz tone'); reader = dsp.AudioFileReader('guitar_plus_tone.ogg'); while ~isDone(reader) audio = step(reader); step(scope,audio(:,1)); end C Code Generation Speedup Measure the time it takes to read the audio file, filter out the interfering tone, and write the filtered output using MATLAB code. Because helperAudioToneRemoval writes 1-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Desktop Real-time Audio Acceleration with MATLAB Coder an audio file output, you must have write permission in the current directory. To ensure write access, change directory to your system’s temporary folder. mydir = pwd; addpath(mydir); cd(tempdir); tic; helperAudioToneRemoval; t1 = toc; fprintf('MATLAB Simulation Time: %d\n',t1); Next, generate a MEX-function from helperAudioToneRemoval using the MATLAB Coder function, codegen. codegen helperAudioToneRemoval Measure the time it takes to execute the MEX-function and calculate the speedup gain with a compiled function. tic; helperAudioToneRemoval_mex t2 = toc; fprintf('Code Generation Simulation Time: %d\n',t2); fprintf('Speedup factor: %6.2f\n',t1/t2); cd(mydir); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-55 1 DSP Tutorials Fixed-Point Filter Design in MATLAB This example shows how to design filters for use with fixed-point input. The example analyzes the effect of coefficient quantization on filter design. You must have the FixedPoint Designer software™ to run this example. Introduction Fixed-point filters are commonly used in digital signal processors where data storage and power consumption are key limiting factors. With the constraints you specify, DSP System Toolbox software allows you to design efficient fixed-point filters. The filter for this example is a lowpass equiripple FIR filter. Design the filter first for floating-point input to obtain a baseline. You can use this baseline for comparison with the fixed-point filter. FIR Filter Design The lowpass FIR filter has the following specifications: • Sample rate: 2000 Hz • Center frequency: 450 Hz • Transition width: 100 Hz • Equiripple design • Maximum 1 dB of ripple in the passband • Minimum 80 dB of attenuation in the stopband samplingFrequency = 2000; centerFrequency = 450; transitionWidth = 100; passbandRipple = 1; stopbandAttenuation = 80; designSpec = fdesign.lowpass('Fp,Fst,Ap,Ast',... centerFrequency-transitionWidth/2, ... centerFrequency+transitionWidth/2, ... passbandRipple,stopbandAttenuation, ... samplingFrequency); LPF = design(designSpec,'equiripple','SystemObject',true) 1-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design in MATLAB LPF = System: dsp.FIRFilter Properties: Structure: NumeratorSource: Numerator: InitialConditions: FrameBasedProcessing: 'Direct form' 'Property' [1x52 double] 0 true View the baseline frequency response. The dotted red lines show the design specifications used to create the filter. fvtool(LPF) Full-Precision Fixed-Point Operation www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-57 1 DSP Tutorials The fixed-point properties of the filter are contained in the Fixed-point properties section in the display of the object. By default, the filter uses full-precision arithmetic to deal with fixed-point inputs. With full-precision arithmetic, the filter uses as many bits for the product, accumulator, and output as needed to prevent any overflow or rounding. If you do not want to use full-precision arithmetic, you can set the FullPrecisionOverride property to false and then set the product, accumulator, and output data types independently. rng default inputWordLength = 16; fixedPointInput = fi(randn(100,1),true,inputWordLength); floatingPointInput = double(fixedPointInput); floatingPointOutput = step(LPF,floatingPointInput); release(LPF) fullPrecisionOutput = step(LPF,fixedPointInput); norm(floatingPointOutput-double(fullPrecisionOutput),'inf') ans = 6.8994e-05 The result of full-precision fixed-point filtering comes very close to floating point, but the results are not exact. The reason for this is coefficient quantization. In the fixedpoint filter, the CoefficientsDataType property has the same word length (16) for the coefficients and the input. The frequency response of the filter in full-precision mode shows this more clearly. The measure function shows that the minimum stopband attenuation of this filter with quantized coefficients is 76.6913 dB, less than the 80 dB specified for the floating-point filter. LPF.CoefficientsDataType fvtool(LPF) measure(LPF) ans = Same word length as input 1-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design in MATLAB ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : 2 kHz 400 Hz 416.2891 Hz 428.1081 Hz 500 Hz 0.96325 dB 76.6913 dB 100 Hz The filter was last used with fixed-point input and is still in a locked state. For that reason, fvtool displays the fixed-point frequency response. The dash-dot response is that of the reference floating-point filter, and the solid plot is the response of the filter that was used with fixed-point input. The desired frequency response cannot be matched because the coefficient word length has been restricted to 16 bits. This accounts for the difference between the floating-point and fixed-point designs. Increasing the number of www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-59 1 DSP Tutorials bits allowed for the coefficient word length makes the quantization error smaller and enables you to match the design requirement for 80 dB of stopband attenuation. Use a coefficient word length of 24 bits to achieve an attenuation of 80.1275 dB. LPF24bitCoeff = design(designSpec,'equiripple','SystemObject',true); LPF24bitCoeff.CoefficientsDataType = 'Custom'; coeffNumerictype = numerictype(fi(LPF24bitCoeff.Numerator,true,24)); LPF24bitCoeff.CustomCoefficientsDataType = numerictype(true, ... coeffNumerictype.WordLength,coeffNumerictype.FractionLength); fullPrecisionOutput32bitCoeff = step(LPF24bitCoeff,fixedPointInput); norm(floatingPointOutput-double(fullPrecisionOutput32bitCoeff),'inf') fvtool(LPF24bitCoeff) measure(LPF24bitCoeff) ans = 4.1077e-07 ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width 1-60 : : : : : : : : 2 kHz 400 Hz 416.2901 Hz 428.1091 Hz 500 Hz 0.96329 dB 80.1275 dB 100 Hz www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design in MATLAB Design Parameters and Coefficient Quantization In many fixed-point design applications, the coefficient word length is not flexible. For example, supposed you are restricted to work with 14 bits. In such cases, the requested minimum stopband attenuation of 80 dB cannot be reached. A filter with 14bit coefficient quantization can achieve a minimum attenuation of only 67.2987 dB. LPF14bitCoeff = design(designSpec,'equiripple','SystemObject',true); coeffNumerictype = numerictype(fi(LPF14bitCoeff.Numerator,true,14)); LPF14bitCoeff.CoefficientsDataType = 'Custom'; LPF14bitCoeff.CustomCoefficientsDataType = numerictype(true, ... coeffNumerictype.WordLength,coeffNumerictype.FractionLength); measure(LPF14bitCoeff,'Arithmetic','fixed') ans = Sample Rate Passband Edge : 2 kHz : 400 Hz www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-61 1 DSP Tutorials 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : 416.2939 Hz 428.1081 Hz 500 Hz 0.96405 dB 67.2987 dB 100 Hz For FIR filters in general, each bit of coefficient word length provides approximately 5 dB of stopband attenuation. Accordingly, if your filter's coefficients are always quantized to 14 bits, you can expect the minimum stopband attenuation to be only around 70 dB. In such cases, it is more practical to design the filter with stopband attenuation less than 70 dB. Relaxing this requirement results in a design of lower order. designSpec.Astop = 60; LPF60dBStopband = design(designSpec,'equiripple','SystemObject',true); LPF60dBStopband.CoefficientsDataType = 'Custom'; coeffNumerictype = numerictype(fi(LPF60dBStopband.Numerator,true,14)); LPF60dBStopband.CustomCoefficientsDataType = numerictype(true, ... coeffNumerictype.WordLength,coeffNumerictype.FractionLength); measure(LPF60dBStopband,'Arithmetic','fixed') order(LPF14bitCoeff) order(LPF60dBStopband) ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : 2 kHz 400 Hz 419.3391 Hz 432.9718 Hz 500 Hz 0.92801 dB 59.1829 dB 100 Hz ans = 51 ans = 1-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design in MATLAB 42 The filter order decreases from 51 to 42, implying that fewer taps are required to implement the new FIR filter. If you still want a high minimum stopband attenuation without compromising on the number of bits for coefficients, you must relax the other filter design constraint: the transition width. Increasing the transition width might enable you to get higher attenuation with the same coefficient word length. However, it is almost impossible to achieve more than 5 dB per bit of coefficient word length, even after relaxing the transition width. designSpec.Astop = 80; transitionWidth = 200; designSpec.Fpass = centerFrequency-transitionWidth/2; designSpec.Fstop = centerFrequency+transitionWidth/2; LPF300TransitionWidth = design(designSpec,'equiripple', ... 'SystemObject',true); LPF300TransitionWidth.CoefficientsDataType = 'Custom'; coeffNumerictype = numerictype(fi(LPF300TransitionWidth.Numerator, ... true, 14)); LPF300TransitionWidth.CustomCoefficientsDataType = numerictype(true, ... coeffNumerictype.WordLength,coeffNumerictype.FractionLength); measure(LPF300TransitionWidth,'Arithmetic','fixed') ans = Sample Rate Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : 2 kHz 350 Hz 385.4095 Hz 408.6465 Hz 550 Hz 0.74045 dB 74.439 dB 200 Hz As you can see, increasing the transition width to 200 Hz allows 74.439 dB of stopband attenuation with 14-bit coefficients, compared to the 67.2987 dB attained when the transition width was set to 100 Hz. An added benefit of increasing the transition width is that the filter order also decreases, in this case from 51 to 27. order(LPF300TransitionWidth) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-63 DSP Tutorials 1 = ans 27 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-64 Sample Rate Conversion of Audio Signal in MATLAB and Simulink Sample Rate Conversion of Audio Signal in MATLAB and Simulink In this section... “Introduction” on page 1-65 “Design and Analysis of Sample Rate Converter ” on page 1-65 “Using the Sample Rate Converter in MATLAB” on page 1-67 “Using the Sample Rate Converter in Simulink” on page 1-69 “Specifying Tolerance to Reduce Filter Order” on page 1-72 Introduction This example shows how to use a multistage/multirate approach to sample rate conversion between different audio rates. The example features both MATLAB and Simulink implementations. Digital audio recordings use many different sample rates. Examples include: 8 kHz, 11.025 kHz, 16 kHz, 22.05 kHz, 24 kHz, 44.1 kHz, 48 kHz, and 96 kHz. The lower rates are used for speech or low fidelity audio, while the higher rates are primarily used for high fidelity audio. Data is commonly resampled for use with different media or equipment. When lower fidelity is acceptable, resampling can reduce data storage requirements. This example uses simple-to-design polyphase filters to convert a speech signal sampled at 44.1 kHz (CD quality) to a signal sampled at 8 kHz (telephone systems). Design and Analysis of Sample Rate Converter You are required to specify three parameters: • Audio input sampling frequency • Audio output sampling frequency • Two-sided bandwidth of interest, for example [-3600, 3600] or 7200 Hz. inFs = 44100; outFs = 8000; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-65 1 DSP Tutorials bw = 7200; SRC = dsp.SampleRateConverter('Bandwidth',bw,'InputSampleRate',inFs,... 'OutputSampleRate',outFs); Obtain information on the filters and visualize the filter responses. info(SRC) visualizeFilterStages(SRC) ans = Overall Interpolation Factor : 80 Overall Decimation Factor : 441 Number of Filters : 2 Multiplications per Input Sample: 23.619048 Number of Coefficients : 7350 Filters: Filter 1: dsp.FIRDecimator - Decimation Factor : 3 Filter 2: dsp.FIRRateConverter - Interpolation Factor: 80 - Decimation Factor : 147 1-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample Rate Conversion of Audio Signal in MATLAB and Simulink The sample rate converter is a cascade of two stages: a FIR decimator followed by a FIR fractional rate converter. The sample rate converter preserves the band of interest between 0 and 3600 Hz, and suppresses the spectral replicas outside that band. Using the Sample Rate Converter in MATLAB To execute the following example, change to a directory where you have write permission. Read in an audio file sampled at 44100 Hz in frames of 441 samples at a time. Use a sample-rate converter to lowpass filter the input and convert the sample rate to 8000 Hz. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-67 1 DSP Tutorials View the short-time Fourier transform (spectrogram) of the sample-rate converter output in a spectrum analyzer and write the output to a FLAC file in the current directory. afr = dsp.AudioFileReader('dft_speech44100.wav','SamplesPerFrame',441); afw = dsp.AudioFileWriter('dft_speech8000.flac','SampleRate',outFs,... 'FileFormat','FLAC','DataType','int16'); specana = dsp.SpectrumAnalyzer('SpectrumType','Spectrogram',... 'SampleRate',outFs,... 'PlotAsTwoSidedSpectrum',false,... 'FrequencyResolutionMethod', 'WindowLength',... 'WindowLength',441, ... 'FFTLengthSource','Property',... 'FFTLength',512,... 'OverlapPercent',25); while ~isDone(afr) audio = step(afr); audioconvert = step(SRC, audio); step(specana,audioconvert); step(afw, audioconvert); end release(afr); release(afw); 1-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample Rate Conversion of Audio Signal in MATLAB and Simulink Using the Sample Rate Converter in Simulink You can use the sample rate converter in Simulink with a MATLAB System block. The model ex_audio_src, which is a Simulink version of “Using the Sample Rate Converter in MATLAB”, is provided for convenience. The model writes an audio file output so make sure you run the example from a folder where you have write permission. open_system('ex_audio_src'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-69 1 DSP Tutorials To run the model, click the Run button on the model toolbar or enter the following command. sim('ex_audio_src') 1-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample Rate Conversion of Audio Signal in MATLAB and Simulink The model reads in a speech signal sampled at 44.1 kHz. The sample rate is converted to 8 kHz and the short-time Fourier transform (spectrogram) of the output is displayed in a spectrum analyzer. A FLAC file (dft_speech8000.flac) is written containing the output sampled at 8 kHz. You can verify the sample rate of the output file after you run the model with the following code. audioinfo('dft_speech8000.flac') ans = Filename: 'tmp/\dft_speech8000.flac' CompressionMethod: 'FLAC' NumChannels: 1 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-71 1 DSP Tutorials SampleRate: 8000 TotalSamples: 41280 Duration: 5.1600 Title: [] Comment: [] Artist: [] BitsPerSample: 16 Specifying Tolerance to Reduce Filter Order If you do not have an exact requirement for the output sample rate, you can allow for a certain tolerance by setting the ‘OutputRateTolerance’ property to a non-zero value. Setting a non-zero tolerance for the output rate can often result in a filter design with fewer coefficients. Compare the filter design with and without a specified output rate tolerance. tol = 0.01; SRCwithTolerance = dsp.SampleRateConverter('Bandwidth', bw, ... 'InputSampleRate', inFs, ... 'OutputSampleRate', outFs, ... 'OutputRateTolerance', tol); info(SRC) info(SRCwithTolerance) ans = Overall Interpolation Factor : 80 Overall Decimation Factor : 441 Number of Filters : 2 Multiplications per Input Sample: 23.619048 Number of Coefficients : 7350 Filters: Filter 1: dsp.FIRDecimator - Decimation Factor : 3 Filter 2: dsp.FIRRateConverter - Interpolation Factor: 80 - Decimation Factor : 147 ans = Output Sample Rate Tolerance Adjusted Output Sample Rate 1-72 : 1.000000 % : 8018.181818 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample Rate Conversion of Audio Signal in MATLAB and Simulink Overall Interpolation Factor : 2 Overall Decimation Factor : 11 Number of Filters : 1 Multiplications per Input Sample: 45.363636 Number of Coefficients : 499 Filters: Filter 1: dsp.FIRRateConverter - Interpolation Factor: 2 - Decimation Factor : 11 With a 0.01 tolerance, the number of coefficients of the sample rate converter reduces from 7350 to 499. One of the stages in the cascade is eliminated and the interpolation and decimation factors are reduced. Using this tolerance, the output sample rate is 8018.18 Hz, which may be an acceptable approximation in most cases to the desired rate of 8000 Hz. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-73 1 DSP Tutorials Visualizing Multiple Signals Using Logic Analyzer This example shows how to visualize multiple signals of a programmable FIR filter using a logic analyzer. For more information on the model used in this example and how to configure the model to generate HDL code, see “Generate HDL Code for Programmable FIR Filter”. Model Programmable FIR Filter Open the example model. modelname = 'dspprogfirhdl'; open_system(modelname); Consider two FIR filters, one with a lowpass response and the other with a highpass response. The coefficients can be specified using the InitFcn* callback function. To specify the callback, select File > Model Properties > Model Properties. In the dialog box, in the Callbacks tab, select InitFcn*. 1-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer The Programmable FIR via Registers block loads the lowpass coefficients from the Host Behavioral Model block and processes the input chirp samples first. The block then loads the highpass coefficients and processes the same chirp samples again. Open the Programmable FIR via Registers block. systemname = [modelname '/Programmable FIR via Registers']; open_system(systemname); Simulation Run the example model. sim(modelname) Open the scope. open_system([modelname '/Scope']); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-75 1 DSP Tutorials Compare the DUT (Design under Test) output with the reference output. Use the Logic Analyzer The logic analyzer enables you to view multiple signals in one window. It also makes it easy to detect signal transitions. The signals of interest (input coefficient, write address, write enable, write done, filter in, filter out, reference out, and error) have been logged to a Simulink.SimulationData.Dataset named dspprogfirhdl_logsout in the MATLAB workspace. The helper function dspprogfirhdlReorderDataset creates a waveform for every input provided in the dspprogfirhdl_logsout data set. Tto make the default order of display more meaningful, the data set is reordered to make the coefficient signals appear first and the data signals next. The error values are converted to logical values. 1-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer logsout_r = dspprogfirhdlReorderDataset(dspprogfirhdl_logsout); Display the data in the logic analyzer. Use the helper function analyzeLogicFromSimulink, which launches a logic analyzer, adds in a waveform for every input, labels the waveform, and displays the data. analyzeLogicFromSimulink returns a handle to the logic analyzer that you can use to modify the display. analyzer = analyzeLogicFromSimulink(logsout_r); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-77 1 DSP Tutorials Modify the Display In the logic analyzer, you can modify the height of all the displayed channels, the spacing between the channels, and the time span of the display. analyzer.DisplayChannelSpacing = 2; 1-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer analyzer.DisplayChannelHeight analyzer.TimeSpan = 12; = 2; You can also control the display on a per-waveform or per-divider basis. To modify an individual waveform or divider, use the tag associated with it. You can obtain the tag associated with a waveform or divider as the return value www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-79 1 DSP Tutorials of addWave and addDivider, or you can get all the tags for the waveforms and dividers using the getDisplayChannelTags method. Get the tags for all the displayed waveforms. displayTags = analyzer.getDisplayChannelTags; View the write address (second waveform in the display) in decimal mode. modifyDisplayChannel(analyzer, 'DisplayChannelTag', displayTags{2}, ... 'Radix', 'Signed decimal'); 1-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer Another useful mode of visualization in the logic analyzer is the analog format. View the Filter In, Filter Out, and Ref Out signals in analog format. modifyDisplayChannel(analyzer, 'DisplayChannelTag', displayTags{5}, ... 'Format', 'Analog'); modifyDisplayChannel(analyzer, 'DisplayChannelTag', displayTags{6}, ... 'Format', 'Analog'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-81 1 DSP Tutorials modifyDisplayChannel(analyzer, 'DisplayChannelTag', displayTags{7}, ... 'Format', 'Analog'); analyzer.TimeSpan = 500; You can also add dividers and waveforms. By default, a new waveform or divider is added to the bottom of the display. If you want, you can pass in the display channel while 1-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer adding in the waveform or divider. You can also move the waveform or divider after it has been added to the display. Add dividers for the coefficient and data signals. The divider for the coefficient signals is set to be shown in Display Channel 1. The divider for the data signals is added to the bottom of the display. addDivider(analyzer, 'DisplayChannel', 1, 'Name', 'Coeff'); divTagData = addDivider(analyzer, 'Name', 'Data'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-83 1 DSP Tutorials Increase the size of the window so that all the waveforms and dividers are visible. 1-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer pos = analyzer.Position; analyzer.Position = [pos(1) pos(2) pos(3) pos(4)+100]; Using the tag for a given waveform or divider, you can use moveDisplayChannel to move it to the display channel of your choice. Move the data signal divider to display channel 6. moveDisplayChannel(analyzer, 'DisplayChannelTag', divTagData, 'DisplayChannel', 6); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-85 1 DSP Tutorials You can also operate on individual channels by right-clicking the channel name. 1-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualizing Multiple Signals Using Logic Analyzer See dsp.LogicAnalyzer for more details. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-87 1 DSP Tutorials Signal Visualization and Measurements in MATLAB This example shows how to visualize and measure signals in the time and frequency domain in MATLAB using a time scope and spectrum analyzer. This example does not demonstrate the full capabilities of the time scope or spectrum analyzer. To learn more about the measurement capabilites of the time scope, see the Simulink example Time Scope Measurements. To learn more about the use of measurements with the spectrum analyzer, see the Simulink example Spectrum Analyzer Measurements. Signal Visualization in Time and Frequency Domains Create a sine wave with a frequency of 100 Hz sampled at 1000 Hz. Generate five seconds of the 100-Hz sine wave with additive white Gaussian noise with mean 0 and standard deviation 0.05. The signal is processed in one-second frames. Send the signal to a time scope and spectrum analyzer for display and measurement. SampPerFrame = 1000; Fs = 1000; SW = dsp.SineWave('Frequency', 100, ... 'SampleRate', Fs, 'SamplesPerFrame', SampPerFrame); TS = dsp.TimeScope('SampleRate', Fs, 'TimeSpan', 0.1, ... 'YLimits', [-2, 2], 'ShowGrid', true); SA = dsp.SpectrumAnalyzer('SampleRate', Fs); tic; while toc < 5 sigData = step(SW) + 0.05*randn(SampPerFrame,1); step(TS, sigData); step(SA, sigData); end release(TS); release(SA); 1-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-89 1 DSP Tutorials Time-Domain Measurements Using the time scope, you can make a number of signal measurements. The following measurements are available: • Cursor Measurements - puts screen cursors on all scope displays. • Signal Statistics - displays maximum, minimum, peak-to-peak difference, mean, median, RMS values of a selected signal, and the times at which the maximum and minimum occur. • Bilevel Measurements - displays information about a selected signal's transitions, overshoots or undershoots, and cycles. • Peak Finder - displays maxima and the times at which they occur. You can enable and disable these measurements from the time scope toolbar or from the Tools > Measurements menu. 1-90 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-91 1 DSP Tutorials To illustrate the use of measurements in the time scope, simulate an ECG signal. Use the ecg function to generate 2700 samples of the signal. Use a Savitzky-Golay filter to smooth the signal and periodically extend the data to obtain approximately 11 periods. x = 3.5*ecg(2700).'; y = repmat(sgolayfilt(x,0,21),[1 13]); sigData = y(1:30000)'; 1-92 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB Display the signal in the time scope and use the Peak Finder, Cursor and Signal Statistics measurements. Assume a sample rate of 4 kHz. TS_ECG = dsp.TimeScope('SampleRate', 4000, ... 'TimeSpanSource', 'Auto', 'ShowGrid', true); step(TS_ECG, sigData); TS_ECG.YLimits = [-4, 4]; release(TS_ECG); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-93 1 DSP Tutorials Peak Measurements Enable Peak Measurements by clicking the corresponding toolbar icon or by clicking the Tools > Measurements > Peak Finder menu item. Click Settings in the Peak Finder panel to expand the Settings pane. Enter 10 for Max Num of Peaks and press Enter. The time scope displays in the Peaks pane a list of 10 peak amplitude values and the times at which they occur. 1-94 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB There is a constant time difference of 0.675 seconds between each heartbeat. Therefore, the heart rate of the ECG signal is given by the following equation: Cursor Measurements Enable Cursor Measurements by clicking the corresponding toolbar icon or by clicking the Tools > Measurements > Cursor Measurements menu item. The Cursor Measurements panel opens and displays two cursors in the time scope. You can drag the cursors and use them to measure the time between events in the waveform. In the following figure, cursors are used to measure the time interval between peaks in the ECG waveform. The measurement in the Cursor Measurements panel demonstrates that the time interval between the two peaks is 0.675 seconds corresponding to a heart rate of 1.482 Hz or 88.9 beats/min. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-95 1 DSP Tutorials Signal Statistics and Bilevel Measurements You can also select Signal Statistics and Bilevel Measurements from the Tools > Measurements menu. Signal Statistics can be used to determine the signal's minimum and maximum values as well as other metrics like the peak-to-peak, mean, median, and RMS values. Bilevel Measurements can be used to determine information about rising and falling transitions, transition aberrations, overshoot and undershoot information, pulse width, and duty cycle. 1-96 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB Frequency-Domain Measurements This section explains how to make frequency domain measurements with the spectrum analyzer. The spectrum analyzer provides the following measurements: • Cursor Measurements - places cursors on the spectrum display. • Peak Finder - displays maxima and the frequencies at which they occur. • Channel Measurements - displays occupied bandwidth and ACPR channel measurements. • Distortion Measurements - displays harmonic and intermodulation distortion measurements. • CCDF Measurements - displays complimentary cumulative distribution function measurements. You can enable and disable these measurements from the spectrum analyzer toolbar or from the Tools > Measurements menu. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-97 DSP Tutorials ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 1-98 Signal Visualization and Measurements in MATLAB Distortion Measurements To illustrate the use of measurements with the spectrum analyzer, create a 2.5 kHz sine wave sampled at 48 kHz with additive white Gaussian noise. Evaluate a high-order polynomial (9th degree) at each signal value to model non-linear distortion. Display the signal in a spectrum analyzer. Fs = 48e3; SW = dsp.SineWave('Frequency', 2500, ... 'SampleRate', Fs, 'SamplesPerFrame', SampPerFrame); SA_Distortion = dsp.SpectrumAnalyzer('SampleRate', Fs, ... 'PlotAsTwoSidedSpectrum', false); y = [1e-6 1e-9 1e-5 1e-9 1e-6 5e-8 0.5e-3 1e-6 1 3e-3]; tic; while toc < 5 x = step(SW) + 1e-8*randn(SampPerFrame,1); sigData = polyval(y, x); step(SA_Distortion, sigData); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-99 1 DSP Tutorials end clear SA_Distortion; Enable the harmonic distortion measurements by clicking the corresponding icon in the toolbar or by clicking the Tools > Measurements > Distortion Measurements menu item. In the Distortion Measurements, change the value for Num. Harmonics to 9 and check the Label Harmonics checkbox. In the panel, you see the value of the fundamental close to 2500 Hz and 8 harmonics as well as their SNR, SINAD, THD and SFDR values, which are referenced with respect to the fundamental output power. Peak Finder You can track time-varying spectral components by using the Peak Finder measurement dialog. You can show and optionally label up to 100 peaks. You can invoke the Peak Finder dialog from the Tools > Measurements > Peak Finder menu item, or by clicking the corresponding icon in the toolbar. 1-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Visualization and Measurements in MATLAB To illustrate the use of Peak Finder, create a signal consisting of the sum of three sine waves with frequencies of 5, 15, and 25 kHz and amplitudes of 1, 0.1, and 0.01 respectively. The data is sampled at 100 kHz. Add white Gaussian noise to the sum of sine waves and display the one-sided power spectrum in the spectrum analyzer. Fs = 100e3; SW1 = dsp.SineWave(1e0, 5e3, 0, 'SampleRate', Fs, 'SamplesPerFrame', SampPerFrame); SW2 = dsp.SineWave(1e-1, 15e3, 0, 'SampleRate', Fs, 'SamplesPerFrame', SampPerFrame); SW3 = dsp.SineWave(1e-2, 25e3, 0, 'SampleRate', Fs, 'SamplesPerFrame', SampPerFrame); SA_Peak = dsp.SpectrumAnalyzer('SampleRate', Fs, 'PlotAsTwoSidedSpectrum', false); tic; while toc < 5 sigData = step(SW1) + step(SW2) + step(SW3) + 1e-4*randn(SampPerFrame,1); step(SA_Peak, sigData); end clear SA_Peak; Enable the Peak Finder to label the three sine wave frequencies. The frequency values and powers in dBm are displayed in the Peak Finder panel. You can increase or decrease the maximum number of peaks, specify a minimum peak distance, and change other settings from the Settings pane in the Peak Finder Measurement panel. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-101 DSP Tutorials ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1 1-102 Filter Frames of a Noisy Sine Wave Signal using Testbench Generator Filter Frames of a Noisy Sine Wave Signal using Testbench Generator This example shows how to use the DSP Testbench Generator app to generate DSP algorithm testbenches. The DSP algorithm generated in this example is similar to the algorithm in the Filter Frames of a Noisy Sine Wave Signal in MATLAB example. That example filters a noisy sine wave signal using a FIR lowpass filter and displays the power spectrum using a spectrum analyzer. Testbench Generator Example App The DSP Testbench Generator app helps you develop and test streaming signal processing algorithms by enabling you to quickly generate testbenches. To launch the Testbench Generator, enter testbenchGeneratorExampleApp at the MATLAB command prompt. The command launches an interface through which you can: 1 Select a set of sources and sinks. 2 Enter the function name of your custom User Algorithm. 3 Customize the properties of each of the added sources and sinks. Each source is treated as a separate input to your algorithm, but you can associate more than one sink with the same output from your algorithm. testbenchGeneratorExampleApp www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-103 1 DSP Tutorials Inputs - Sine Waves and White Noise By default, the testbench generator selects a two-channel sine wave source and a white Gaussian noise source. The two channels of the sine wave source have frequencies of 1 kHz and 10 kHz. The sampling frequency is 44.1 kHz. The white Gaussian noise input has mean 0 and standard deviation 0.1. The data is processed in frames of 1024 samples. To add more sources, use the list under Add a new source to the above list of inputs to select one of the supported sources. Alternatively, you can add your custom System object source by selecting Custom System object from the list and clicking Add. The added source appears in the list of inputs. After adding a source, you can select it and click Configure to change the selected source's properties. 1-104 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal using Testbench Generator User Algorithm - Lowpass Filter The user algorithm in this example is a function hTestbenchLowpass. You can view the code for this function by entering edit hTestbenchLowpass at the MATLAB command prompt. hTestbenchLowpass accepts two inputs, lowpass filters the sum of those two inputs, and returns the filtered signal. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-105 1 DSP Tutorials hTestbenchLowpass uses a constrained equiripple FIR filter design with a cutoff frequency of 5 kHz. The ripples in the passband and stopband are equal to 0.05 and 0.001. Filtering is performing using dsp.FIRFilter, which is optimized for streaming. Output The power spectrum of the output is displayed on a spectrum analyzer in dBm. You can add more sinks to visualize or post-process the outputs. Similar to inputs, you can use the list under Add a new sink to the above list of outputs to add a new sink, and click Configure to modify the properties of the selected sink. You can associate a single output from the user algorithm with one or more sinks. For example, you can visualize the same output signal with both a time scope and spectrum analyzer. To do this, add the required sinks and make sure you associate all of the sinks to desired output from the user algorithm by changing the value under the Associate selected sink with list. Generate Code and Simulate After you add and configure the sources and sinks and enter a function name in the User Algorithm text box, the testbench generator is ready to generate testbench MATLAB 1-106 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal using Testbench Generator code. To generate code, select Generate Code > Generate MATLAB Code. A new untitled document opens in the MATLAB editor containing the generated testbench code. You can edit the generated code to customize it before executing it. For the default example, the generated code is included below. Executing this testbench code, you see in the spectrum analyzer that the frequencies above 4 kHz in the source signal are attenuated. The resulting signal maintains the peak at 1 kHz because 1 kHz falls in the passband of the lowpass filter. % DSP Testbench script % Generated by DSP Testbench Generator Example App % Initialization maxIterations = 10000; % Construct sources (for all inputs) src1 = dsp.SineWave('Frequency',[1000 10000], ... 'SampleRate',44100, ... 'SamplesPerFrame',1024); % Construct sinks (for all outputs) sink1 = dsp.SpectrumAnalyzer('SampleRate',44100, ... 'PlotAsTwoSidedSpectrum',false, ... 'ShowLegend',true); % Stream clear hTestbenchLowpass; for i = 1:maxIterations % Sources in1 = step(src1); in2 = 0.1*randn(1024,2); % User Algorithm out1 = hTestbenchLowpass(in1,in2); % Sinks step(sink1,out1); end % Clean up release(src1); release(sink1); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-107 1 DSP Tutorials More Customizations in Testbench Generator The testbench generator offers additional top-level customizations, which you can configure using the Testbench Generator Settings dialog box. To open this dialog box, select Generate Code > Testbench Generator Settings .... 1-108 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Frames of a Noisy Sine Wave Signal using Testbench Generator You can also tune some of the parameters used in your algorithm during testbench execution. To use the Parameter Tuning UI, check the Enable parameter tuning check box under the User Algorithm and click Edit parameters table to add the details of your tunable parameters before you generate testbench code. Also, make sure that your user algorithm handles parameter tuning during execution. See the MATLAB code for hTestbenchVariableBandwithFIR for an example of how to make your user algorithm work with parameter tuning. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-109 1 DSP Tutorials Create Composite System object This example shows how to create a System object composed of other System objects. In this example, build a multi-notch filter using two dsp.NotchPeakFilter System objects. Multi-notch filters are used in many applications. Examples include audio phasers and applications that require the removal of multiple interfering tones. Create MultiNotchFilter “Create Moving Average System object” on page 1-40 explains in detail how to write a System object using a template file. In this example, the entire System object is provided for convenience in dspdemo.MultiNotchFilter. To view the MATLAB code, at the command prompt enter: edit dspdemo.MultiNotchFilter dspdemo.MultiNotchFilter has five public properties. Public properties are accessible to every user. The first property, SampleRate, is a nontunable property. Nontunable properties cannot change when the filter is locked (after you use step on the filter). The remaining properties, CenterFrequency1, CenterFrequency2, QualityFactor1, and QualityFactor2 control settings in the two notch filters contained in dspdemo.MultiNotchFilter. These four properties are tunable. You can change the values of these properties while streaming data. Contain System Objects as Private Properties dspdemo.MultiNotchFilter uses dsp.NotchPeakFilter to design the two notch filters. The notch filters are created in the class constructor. methods function obj = MultiNotchFilter(varargin) % Construct two notch filters with default values obj.NotchFilter1 = dsp.NotchPeakFilter(... 'Specification', 'Quality factor and center frequency',... 'CenterFrequency',400); obj.NotchFilter2 = dsp.NotchPeakFilter(... 'Specification', 'Quality factor and center frequency',... 'CenterFrequency',800); % Support name-value pair arguments setProperties(obj,nargin,varargin{:}); 1-110 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Composite System object end The ability to create more than one instance of a System object and having each instance manage its own state is one of the biggest advantages of using System objects over functions. The private properties NotchFilter1 and NotchFilter2 are used to store the two notch filters. properties (Access=private) % This example class contains two notch filters (more can be added % in the same way) NotchFilter1 NotchFilter2 end Work with Dependent Properties The SampleRate property as well as the remaining four public properties are implemented as dependent properties in this example. Whenever you assign a value to one of the dependent properties, the value is set in the corresponding single-notch filter. When you read one of the dependent properties, the value is read from the corresponding single-notch filter. Find the following code block in dspdemo.MultiNotchFilter. properties (Dependent) %CenterFrequency1 Center frequency of first notch % Specify the first notch center frequency as a finite positive % numeric scalar in Hertz. The default is 400 Hz. This property % is tunable. CenterFrequency1; %QualityFactor1 Quality factor of first notch % Specify the quality factor (Q factor) for the first notch % filter. The default value is 5. This property is tunable. QualityFactor1; %CenterFrequency2 Center frequency of second notch % Specify the second notch center frequency as a finite positive % numeric scalar in Hertz. The default is 800 Hz. This property % is tunable. CenterFrequency2; %QualityFactor2 Quality factor of second notch % Specify the quality factor (Q factor) for the first notch % filter. The default value is 5. This property is tunable. QualityFactor2; end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-111 1 DSP Tutorials Use the Multi-Notch Filter - Initialization To use dspdemo.MultiNotchFilter, initialize the filter and any other required components. In this example, initialize an audio file reader, a multi-notch filter, a transfer function estimator, an array plotter, and an audio player. FrameSize = 1024; AFR = dsp.AudioFileReader('guitar10min.ogg','SamplesPerFrame',FrameSize); Fs = AFR.SampleRate; MNF = dspdemo.MultiNotchFilter('SampleRate',Fs); TFE = dsp.TransferFunctionEstimator(... 'FrequencyRange','onesided','SpectralAverages',5); AP = dsp.ArrayPlot('PlotType','Line','YLimits',[-85 15],... 'SampleIncrement',Fs/FrameSize); P = dsp.AudioPlayer; Use the Multi-Notch Filter - Streaming To illustrate the tunability of the two notch filter center frequencies, vary the center frequencies sinusoidally in a loop. The starting center frequencies are 500 and 2000 Hz. The first center frequency oscillates over the range [100, 900] Hz with a frequency of 0.2 Hz. The second center frequency oscillates over the range [1200, 2800] Hz with a frequency of 0.5 Hz. Because CenterFrequency1 and CenterFrequency2 are dependent properties, modifying their values in the loop changes the center frequencies in the two notch filters contained in dspdemo.MultiNotchFilter. To visualize the multi-notch filter, estimate and plot the transfer function continuously. The quality factors remain constant. The simulation runs for 20 seconds. MNF.QualityFactor1 = .5; MNF.QualityFactor2 = 1; f0 = 0.2; f1 = 0.5; k = 0; tic, while toc <20 x = step(AFR); t = k*FrameSize/Fs; k = k+1; 1-112 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Composite System object MNF.CenterFrequency1 = 500 + 400*sin(2*pi*f0*t); MNF.CenterFrequency2 = 2000 + 800*sin(2*pi*f1*t); CF1(k) = MNF.CenterFrequency1; CF2(k) = MNF.CenterFrequency2; y = step(MNF,x); H = step(TFE,x(:,1),y(:,1)); magdB = 20*log10(abs(H)); step(AP,magdB); step(P,y); end Execute this code to show how the two notch center frequencies varied over the simulation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-113 1 DSP Tutorials subplot(2,1,1) plot(CF1); title('Center Frequency 1'); ylabel('Notch CF (Hz)'); subplot(2,1,2) plot(CF2); title('Center Frequency 2'); ylabel('Notch CF (Hz)'); xlabel('Iteration') 1-114 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Measure Audio Latency in MATLAB and Simulink Measure Audio Latency in MATLAB and Simulink This example shows how to measure the latency introduced in audio signals when using the audio player and audio recorder in MATLAB or Simulink. The procedure presented here allows you to tune certain parameters that affect latency and observe the effect in a simple measurement. The specific parameters are discussed in detail later in the example. Introduction In general terms, latency is defined as the time it takes for the audio to be heard or recorded after it has been played. There are multiple factors that influence latency. For example: 1 Hardware: CPU, memory, and sound card. 2 Audio drivers that communicate with the system's sound card. 3 Algorithmic complexity of any audio processing between playback and recording. 4 Software used to process the audio: MATLAB or Simulink in this example. This example shows you how to measure the overall latency with a focus on what parameters determine the latency effect of using MATLAB or Simulink. There are two variants of this example: one uses the audio System objects in MATLAB and the other uses the Simulink audio input and output blocks. Set-up Experiment In this example, measure the latency by playing an audio signal through dsp.AudioPlayer (or the To Audio Device block), recording the audio through dsp.AudioRecorder (or the From Audio Device block), and measuring the delay by the cross-correlation of the two signals. No other processing is done on the audio signal. A loopback cable is used to physically connect the audio-out port of the sound card to its audio-in port. The set-up is shown in the following illustration. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-115 1 DSP Tutorials The set-up for another common application is to record live audio with a microphone, process the audio on the computer, and play the audio back in a streaming fashion. In that set-up, the hardware interface latency is the same as the set-up involving the audio System objects or blocks: a sum of latencies due to the player and the recorder. Measure Latency The audioLatencyMeasurementBasicExampleApp function measures the latency for the set-up where an audio signal is played and recorded with System objects or Simulink blocks. Inputs to this function are: • plotFlag: Set this to true to visualize the input to the dsp.AudioPlayer object and the output from the dsp.AudioRecorder object. • frameSize: Number of audio samples that constitute a single frame. This sets the SamplesPerFrame property of the dsp.AudioFileReader object. • bufferSize: The value of this parameter is copied to the BufferSize property of the dsp.AudioPlayer and the dsp.AudioRecorder System objects. • useSimulink: Set this to true to use the Simulink model audiolatencybasicmeasurement.slx to measure the latency. Most of these inputs are parameters that affect audio latency in MATLAB or Simulink. You can try different values and measure the latency for each set. The various sections in the MATLAB code for the audioLatencyMeasurementBasicExampleApp function are: 1-116 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Measure Audio Latency in MATLAB and Simulink 1 Initialization: The default values for the input parameters are assigned. The audio System objects are created with appropriate parameter values. 2 Loopback simulation: For a duration of 10 seconds, audio is read from a file and sent to the computer's audio-out port through dsp.AudioPlayer. Through the loopback cable and audio-in port, the audio is read in using the dsp.AudioRecorder object. When the useSimulink input is true, the loopback simulation is performed through the Simulink model audiolatencybasicmeasurement.slx. The signal read from the file and the recorded signal are stored in a signal sink. 3 Cross-correlation: Using the xcorr function, the cross-correlation sequence is computed between the audio signal sent to the player and the one received by the recorder. The received signal lags the played signal. The time shift corresponding to the maximum value of the cross-correlation sequence is the latency. Additionally, if the plotFlag input is true, the two audio signals are plotted in a figure so you can observe the lag. If the queue is overrun or underrun, a corresponding message is displayed in the command window for the MATLAB version of this example. For the Simulink version, you must monitor the logged variables APunderrun and ARoverrun to determine overrun or underrun. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-117 1 DSP Tutorials Parameters in MATLAB/Simulink Affecting Latency Frame size This is not an explicit property of the audio player or audio recorder System objects. The frame size is the number of samples passed to those objects in each call to their step methods. The bigger the frame size, the longer you must wait to collect the samples. BufferSize The BufferSize is a property of both the dsp.AudioPlayer and dsp.AudioRecorder System objects. The buffer size value is half the size of the sound card buffer. The smaller the BufferSize, the quicker you can send samples to the sound card. However, there is a trade-off because a small buffer can also easily underrun (for the player) or overrun (for the recorder). 1-118 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Measure Audio Latency in MATLAB and Simulink QueueDuration Both dsp.AudioPlayer and dsp.AudioRecorder System objects have the property, QueueDuration. The queue is a storage space between the System object and the sound card buffer. The main use of QueueDuration is to match the throughput of the algorithm in MATLAB and the device. A proper setting for QueueDuration can help prevent buffer underruns and overruns. QueueDuration should be set to a value as small as possible to maintain acceptable latency while not introducing glitches in the audio. The optimal value for the queue size is typically twice the size of the audio frame. Based on this, the QueueDuration is kept to a value of (2*FrameSize+1)/SampleRate. The same parameters are also applicable in the Simulink version that uses audio blocks instead of System objects. More details about BufferSize and QueueDuration can be found in the documentation for the System objects dsp.AudioPlayer and dsp.AudioRecorder, and the blocks To Audio Device and From Audio Device. Sound Card and Drivers Additionally, latency is affected by the sound card and drivers. For low-latency applications, use a low-latency sound card. Drivers can also have an impact on latency. For example, on the Windows™ platform, DirectSound creates an additional virtual device layer between the application and the sound card, increasing latency. On the other hand, ASIO™ drivers communicate with the device directly, which helps to reduce delays. Obtain Parameter Values for Low Latency The latency of your system can depend on multiple parameters. In order to discover the set of parameter values that provides the smallest latency, first fix an audio frame size. Typically, this is 1024 or 512 samples for a sample rate of 44.1 kHz. Initially set the buffer size the same value as the frame size and keep reducing it until the queue starts to overrun or underrun. The smallest buffer size that satisfies this criterion is generally 64 or 128 samples for an audio frame size of 512 or 1024 at 44.1 kHz. Repeat the experiment by starting with a smaller frame size. Sample Results Here are some results obtained by running audioLatencyMeasurementBasicExampleApp with different input parameters on a Mac OS X 10.8.5 system with a 3.4 GHz Core i7 processor and 16 GB of RAM. Measurements were made using the built in audio I/O. The audio is stereo sampled at 44.1 kHz. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-119 1 DSP Tutorials Decrease in latency on decreasing buffer size for constant frame size: latency = audioLatencyMeasurementBasicExampleApp(0,1024,1024,0); Result: Latency of 43 ms latency = audioLatencyMeasurementBasicExampleApp(0,1024,512,0); Result: Latency of 34 ms latency = audioLatencyMeasurementBasicExampleApp(0,1024,64,0); Result: Latency of 14.3 ms Decreasing the frame size further: latency = audioLatencyMeasurementBasicExampleApp(0,512,512,0); Result: Latency of 28 ms latency = audioLatencyMeasurementBasicExampleApp(0,512,64,0); Result: Latency of 13.9 ms Running the Simulink version: latency = audioLatencyMeasurementBasicExampleApp(0,512,64,1); Result: Latency of 13.9 ms Plotting the player and recorder audio signals along with latency measurement: latency = audioLatencyMeasurementBasicExampleApp(1,512,64,0); Result: Latency of 13.9 ms. You can also zoom into the plot to see the delay between the player and recorder waveforms. 1-120 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Measure Audio Latency in MATLAB and Simulink Summary This example discussed the concept of latency in audio signals and demonstrated a way in MATLAB and Simulink to quantify latency. The example also described various parameters that influence audio latency. Some sample results obtained on a specific computer were presented. Note that results vary based on machine configuration. You can follow the advice in this example and experiment with different values to find the combination that best suits your system and application. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-121 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 1-122 2 Input, Output, and Display Learn how to input, output and display data and signals with DSP System Toolbox™. • “Discrete-Time Signals” on page 2-2 • “Continuous-Time Signals” on page 2-11 • “Create Sample-Based Signals” on page 2-12 • “Sample-Based Row Vector Processing Changes” on page 2-17 • “Create Frame-Based Signals” on page 2-19 • “Create Multichannel Sample-Based Signals” on page 2-26 • “Create Multichannel Frame-Based Signals” on page 2-32 • “Deconstruct Multichannel Sample-Based Signals” on page 2-36 • “Deconstruct Multichannel Frame-Based Signals” on page 2-43 • “Import and Export Sample-Based Signals” on page 2-52 • “Import and Export Frame-Based Signals” on page 2-64 • “Musical Instrument Digital Interface” on page 2-72 • “Display Time-Domain Data” on page 2-77 • “Display Frequency-Domain Data in Spectrum Analyzer” on page 2-93 • “Visualize Central Limit Theorem in Array Plot” on page 2-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 Input, Output, and Display Discrete-Time Signals In this section... “Time and Frequency Terminology” on page 2-2 “Recommended Settings for Discrete-Time Simulations” on page 2-3 “Other Settings for Discrete-Time Simulations” on page 2-6 Time and Frequency Terminology Simulink models can process both discrete-time and continuous-time signals. Models built with DSP System Toolbox software are often intended to process discrete-time signals only. A discrete-time signal is a sequence of values that correspond to particular instants in time. The time instants at which the signal is defined are the signal's sample times, and the associated signal values are the signal's samples. Traditionally, a discretetime signal is considered to be undefined at points in time between the sample times. For a periodically sampled signal, the equal interval between any pair of consecutive sample times is the signal's sample period, Ts. The sample rate, Fs, is the reciprocal of the sample period, or 1/Ts. The sample rate is the number of samples in the signal per second. The 7.5-second triangle wave segment below has a sample period of 0.5 second, and sample times of 0.0, 0.5, 1.0, 1.5, ...,7.5. The sample rate of the sequence is therefore 1/0.5, or 2 Hz. A number of different terms are used to describe the characteristics of discrete-time signals found in Simulink models. These terms, which are listed in the following table, are frequently used to describe the way that various blocks operate on sample-based and frame-based signals. Term Symbol Units Notes Sample period Ts Tsi Seconds The time interval between consecutive samples in a sequence, as the input to a block (Tsi) or the output from a block (Tso). 2-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Discrete-Time Signals Term Symbol Tso Units Notes Frame period Tf Tfi Tfo Seconds The time interval between consecutive frames in a sequence, as the input to a block (Tfi) or the output from a block (Tfo). Signal period T Seconds The time elapsed during a single repetition of a periodic signal. Sample frequency Fs Hz (samples per second) The number of samples per unit time, Fs = 1/Ts. Frequency Hz (cycles per The number of repetitions per unit time of a periodic second) signal or signal component, f = 1/T. f Nyquist rate Hz (cycles per The minimum sample rate that avoids aliasing, second) usually twice the highest frequency in the signal being sampled. Nyquist frequency fnyq Hz (cycles per Half the Nyquist rate. second) Normalized frequency fn Two cycles per sample Frequency (linear) of a periodic signal normalized to half the sample rate, fn = ω/π = 2f/Fs. Angular frequency Ω Radians per second Frequency of a periodic signal in angular units, Ω = 2πf. Digital (normalized angular) frequency ω Radians per sample Frequency (angular) of a periodic signal normalized to the sample rate, ω = Ω/Fs = πfn. Note In the Block Parameters dialog boxes, the term sample time is used to refer to the sample period, Ts. For example, the Sample time parameter in the Signal From Workspace block specifies the imported signal's sample period. Recommended Settings for Discrete-Time Simulations Simulink allows you to select from several different simulation solver algorithms. You can access these solver algorithms from a Simulink model: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-3 2 Input, Output, and Display 1 In the Simulink model window, from the Simulation menu, select Model Configuration Parameters. The Configuration Parameters dialog box opens. 2 In the Select pane, click Solver. The selections that you make here determine how discrete-time signals are processed in Simulink. The recommended Solver options settings for signal processing simulations are • Type: Fixed-step • Solver: Discrete (no continuous states) • Fixed step size (fundamental sample time): auto • Tasking mode for periodic sample times: SingleTasking 2-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Discrete-Time Signals You can automatically set the above solver options for all new models by running the dspstartup.m file. See “Configure the Simulink Environment for Signal Processing Models” in the DSP System Toolbox Getting Started Guide for more information. In Fixed-step SingleTasking mode, discrete-time signals differ from the prototype described in “Time and Frequency Terminology” on page 2-2 by remaining defined between sample times. For example, the representation of the discrete-time triangle wave looks like this. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-5 2 Input, Output, and Display The above signal's value at t=3.112 seconds is the same as the signal's value at t=3 seconds. In Fixed-step SingleTasking mode, a signal's sample times are the instants where the signal is allowed to change values, rather than where the signal is defined. Between the sample times, the signal takes on the value at the previous sample time. As a result, in Fixed-step SingleTasking mode, Simulink permits cross-rate operations such as the addition of two signals of different rates. This is explained further in “Cross-Rate Operations” on page 2-7. Other Settings for Discrete-Time Simulations It is useful to know how the other solver options available in Simulink affect discretetime signals. In particular, you should be aware of the properties of discrete-time signals under the following settings: • Type: Fixed-step, Mode: MultiTasking • Type: Variable-step (the Simulink default solver) • Type: Fixed-step, Mode: Auto When the Fixed-step MultiTasking solver is selected, discrete signals in Simulink are undefined between sample times. Simulink generates an error when operations attempt to reference the undefined region of a signal, as, for example, when signals with different sample rates are added. When the Variable-step solver is selected, discrete time signals remain defined between sample times, just as in the Fixed-step SingleTasking case described in “Recommended Settings for Discrete-Time Simulations” on page 2-3. When the Variable-step solver is selected, cross-rate operations are allowed by Simulink. In the Fixed-step Auto setting, Simulink automatically selects a tasking mode, singletasking or multitasking, that is best suited to the model. See“Simulink Tasking Mode” 2-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Discrete-Time Signals for a description of the criteria that Simulink uses to make this decision. For the typical model containing multiple rates, Simulink selects the multitasking mode. Cross-Rate Operations When the Fixed-step MultiTasking solver is selected, discrete signals in Simulink are undefined between sample times. Therefore, to perform cross-rate operations like the addition of two signals with different sample rates, you must convert the two signals to a common sample rate. Several blocks in the Signal Operations and Multirate Filters libraries can accomplish this task. See “Convert Sample and Frame Rates in Simulink” for more information. Rate change can happen implicitly, depending on diagnostic settings. See “Multitask rate transition”, “Single task rate transition”. However, this is not recommended. By requiring explicit rate conversions for cross-rate operations in discrete mode, Simulink helps you to identify sample rate conversion issues early in the design process. When the Variable-step solver or Fixed-step SingleTasking solver is selected, discrete time signals remain defined between sample times. Therefore, if you sample the signal with a rate or phase that is different from the signal's own rate and phase, you will still measure meaningful values: 1 At the MATLAB command line, type ex_sum_tut1. The Cross-Rate Sum Example model opens. This model sums two signals with different sample periods. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-7 2 Input, Output, and Display 2 Double-click the upper Signal From Workspace block. The Block Parameters: Signal From Workspace dialog box opens. 3 Set the Sample time parameter to 1. This creates a fast signal, (Ts=1), with sample times 1, 2, 3, ... 2-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Discrete-Time Signals 4 Double-click the lower Signal From Workspace block 5 Set the Sample time parameter to 2. This creates a slow signal, (Ts=2), with sample times 1, 3, 5, ... 6 From the Display menu choose Sample Time > Colors. Checking the Colors option allows you to see the different sampling rates in action. For more information about the color coding of the sample times see “View Sample Time Information” in the Simulink documentation. 7 Run the model. Note Using the dspstartup configurations with cross-rate operations generates errors even though the Fixed-step SingleTasking solver is selected. This is due to the fact that Single task rate transition is set to error in the Sample Time pane of the Diagnostics section of the Configuration Parameters dialog box. 8 At the MATLAB command line, type dsp_examples_yout. The following output is displayed: dsp_examples_yout = 1 1 2 2 1 3 3 2 5 4 2 6 5 3 8 6 3 9 7 4 11 8 4 12 9 5 14 10 5 15 0 6 6 The first column of the matrix is the fast signal, (Ts=1). The second column of the matrix is the slow signal (Ts=2). The third column is the sum of the two signals. As expected, the slow signal changes once every 2 seconds, half as often as the fast signal. Nevertheless, the slow signal is defined at every moment because Simulink holds the previous value of the slower signal during time instances that the block doesn't run. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-9 2 Input, Output, and Display In general, for Variable-step and Fixed-step SingleTasking modes, when you measure the value of a discrete signal between sample times, you are observing the value of the signal at the previous sample time. 2-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Continuous-Time Signals Continuous-Time Signals In this section... “Continuous-Time Source Blocks” on page 2-11 “Continuous-Time Nonsource Blocks” on page 2-11 Continuous-Time Source Blocks Most signals in a signal processing model are discrete-time signals. However, many blocks can also operate on and generate continuous-time signals, whose values vary continuously with time. Source blocks are those blocks that generate or import signals in a model. Most source blocks appear in the Sources library. The sample period for continuous-time source blocks is set internally to zero. This indicates a continuous-time signal. The Simulink Signal Generator and Constant blocks are examples of continuoustime source blocks. Continuous-time signals are rendered in black when, from the Display menu, you point to Sample Time and select Colors. When connecting continuous-time source blocks to discrete-time blocks, you might need to interpose a Zero-Order Hold block to discretize the signal. Specify the desired sample period for the discrete-time signal in the Sample time parameter of the Zero-Order Hold block. Continuous-Time Nonsource Blocks Most nonsource blocks in DSP System Toolbox software accept continuous-time signals, and all nonsource blocks inherit the sample period of the input. Therefore, continuoustime inputs generate continuous-time outputs. Blocks that are not capable of accepting continuous-time signals include the Biquad Filter, Discrete FIR Filter, FIR Decimation, and FIR Interpolation blocks. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-11 2 Input, Output, and Display Create Sample-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Create Signals Using Constant Block” on page 2-12 “Create Signals Using Signal from Workspace Block” on page 2-14 Create Signals Using Constant Block A constant sample-based signal has identical successive samples. The Sources library provides the following blocks for creating constant sample-based signals: • Constant Diagonal Matrix • Constant • Identity Matrix The most versatile of the blocks listed above is the Constant block. This topic discusses how to create a constant sample-based signal using the Constant block: 1 Create a new Simulink model. 2 From the Sources library, click-and-drag a Constant block into the model. 3 From the Sinks library, click-and-drag a Display block into the model. 4 Connect the two blocks. 5 Double-click the Constant block, and set the block parameters as follows: • Constant value = [1 2 3; 4 5 6] • Interpret vector parameters as 1–D = Clear this check box • Sampling Mode = Sample based • Sample time = 1 2-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Sample-Based Signals Based on these parameters, the Constant block outputs a constant, discrete-valued, sample-based matrix signal with a sample period of 1 second. The Constant block's Constant value parameter can be any valid MATLAB variable or expression that evaluates to a matrix. 6 Save these parameters and close the dialog box by clicking OK. 7 From the Display menu, point to Signals & Ports and select Signal Dimensions. 8 Run the model and expand the Display block so you can view the entire signal. You have now successfully created a six-channel, constant sample-based signal with a sample period of 1 second. To view the model you just created, and to learn how to create a 1–D vector signal from the block diagram you just constructed, continue to the next section. Create an Unoriented Vector Signal You can create an unoriented vector by modifying the block diagram you constructed in the previous section: 1 To add another sample-based signal to your model, copy the block diagram you created in the previous section and paste it below the existing sample-based signal in your model. 2 Double-click the Constant1 block, and set the block parameters as follows: • Constant value = [1 2 3 4 5 6] • Interpret vector parameters as 1–D = Check this box • Sample time = 1 3 Save these parameters and close the dialog box by clicking OK. 4 Run the model and expand the Display1 block so you can view the entire signal. Your model should now look similar to the following figure. You can also open this model by typing ex_usingcnstblksb at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-13 2 Input, Output, and Display The Constant1 block generates a length-6 unoriented vector signal. This means that the output is not a matrix. However, most nonsource signal processing blocks interpret a length-M unoriented vector as an M-by-1 matrix (column vector). Create Signals Using Signal from Workspace Block This topic discusses how to create a four-channel sample-based signal with a sample period of 1 second using the Signal From Workspace block: 2-14 1 Create a new Simulink model. 2 From the Sources library, click-and-drag a Signal From Workspace block into the model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Sample-Based Signals 3 From the Simulink Sinks library, click-and-drag a To Workspace block into the model. 4 Connect the two blocks. 5 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = cat(3,[1 -1;0 5],[2 -2;0 5],[3 -3;0 5]) • Sample time = 1 • Samples per frame = 1 • Form output after final data value by = Setting to zero Based on these parameters, the Signal From Workspace block outputs a four-channel sample-based signal with a sample period of 1 second. After the block has output the signal, all subsequent outputs have a value of zero. The four channels contain the following values: • Channel 1: 1, 2, 3, 0, 0,... • Channel 2: -1, -2, -3, 0, 0,... • Channel 3: 0, 0, 0, 0, 0,... • Channel 4: 5, 5, 5, 0, 0,... 6 Save these parameters and close the dialog box by clicking OK. 7 From the Display menu, point to Signals & Ports, and select Signal Dimensions. 8 Run the model. The following figure is a graphical representation of the model's behavior during simulation. You can also open the model by typing ex_usingsfwblksb at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-15 2 Input, Output, and Display 9 At the MATLAB command line, type yout. The following is a portion of the output: yout(:,:,1) = 1 0 -1 5 yout(:,:,2) = 2 0 -2 5 yout(:,:,3) = 3 0 -3 5 yout(:,:,4) = 0 0 0 0 You have now successfully created a four-channel sample-based signal with sample period of 1 second using the Signal From Workspace block. 2-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample-Based Row Vector Processing Changes Sample-Based Row Vector Processing Changes There are DSP System Toolbox blocks that handle sample-based row vector inputs in a special way. One category of these blocks have a Treat sample-based row input as a column check box which allows you to explicitly specify how the block should treat sample-based row vector inputs. Expand the following section for a full list of these blocks. Blocks with a Check Box • Maximum • Mean • Median • Minimum • Normalization • RMS • Standard Deviation • Variance In a future release these blocks will produce a warning when you provide them with a sample-based row vector input, and eventually, their behavior will change. You can prepare your models for the upcoming change by using slupdate. If the function detects any blocks that have a Treat sample-based row input as a column check box, it performs the following actions: • If the input to the block is a sample-based row vector, and the Treat sample-based row input as a column check box is selected, the slupdate function places a Transpose block in front of the affected block. The Transpose block transposes the sample-based row vector into a column vector, which is then input into the affected block. Transposing the input signal ensures that your model will produce the same results in future releases. • If the Treat sample-based row input as a column check box is not selected, or if the input to the block is not a sample-based row vector, function takes no action. Your model will continue to work as expected in future releases. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-17 2 Input, Output, and Display If the slupdate function detects any blocks that automatically treat sample-based row vectors as a column, it performs the following actions: • If the input to the block is a sample-based row vector, the slupdate function places a Transpose block in front of the affected block. The Transpose block transposes the sample-based row vector into a column vector, which is then input into the affected block. Transposing the input signal ensures that your model will produce the same results in future releases. • If the input to the block is not a sample-based row vector, the slupdate function takes no action. Your model will continue to work as expected in future releases. 2-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Frame-Based Signals Create Frame-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Create Signals Using Sine Wave Block” on page 2-19 “Create Signals Using Signal from Workspace Block” on page 2-22 Create Signals Using Sine Wave Block A frame-based signal is propagated through a model in batches of samples called frames. Frame-based processing can significantly improve the performance of your model by decreasing the amount of time it takes your simulation to run. One of the most commonly used blocks in the Sources library is the Sine Wave block. This topic describes how to create a three-channel frame-based signal using the Sine Wave block: 1 Create a new Simulink model. 2 From the Sources library, click-and-drag a Sine Wave block into the model. 3 From the Matrix Operations library, click-and-drag a Matrix Sum block into the model. 4 From the Simulink Sinks library, click-and-drag a To Workspace block into the model. 5 Connect the blocks in the order in which you added them to your model. 6 Double-click the Sine Wave block, and set the block parameters as follows: • Amplitude = [1 3 2] • Frequency = [100 250 500] • Sample time = 1/5000 • Samples per frame = 64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-19 2 Input, Output, and Display Based on these parameters, the Sine Wave block outputs three sinusoids with amplitudes 1, 3, and 2 and frequencies 100, 250, and 500 hertz, respectively. The sample period, 1/5000, is 10 times the highest sinusoid frequency, which satisfies the Nyquist criterion. The frame size is 64 for all sinusoids, and, therefore, the output has 64 rows. 7 Save these parameters and close the dialog box by clicking OK. You have now successfully created a three-channel frame-based signal using the Sine Wave block. The rest of this procedure describes how to add these three sinusoids together. 8 Double-click the Matrix Sum block. Set the Sum over parameter to Specified dimension, and set the Dimension parameter to 2. Click OK. 9 From the Display menu, point to Signals & Ports, and select Signal Dimensions. 10 Run the model. Your model should now look similar to the following figure. You can also open the model by typing ex_usingsinwaveblkfb at the MATLAB command line. 2-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Frame-Based Signals The three signals are summed point-by-point by a Matrix Sum block. Then, they are exported to the MATLAB workspace. 11 At the MATLAB command line, type plot(yout(1:100)). Your plot should look similar to the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-21 2 Input, Output, and Display This figure represents a portion of the sum of the three sinusoids. You have now added the channels of a three-channel frame-based signal together and displayed the results in a figure window. Create Signals Using Signal from Workspace Block A frame-based signal is propagated through a model in batches of samples called frames. Frame-based processing can significantly improve the performance of your model by decreasing the amount of time it takes your simulation to run. This topic describes how to create a two-channel frame-based signal with a sample period of 1 second, a frame period of 4 seconds, and a frame size of 4 samples using the Signal From Workspace block: 2-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Frame-Based Signals 1 Create a new Simulink model. 2 From the Sources library, click-and-drag a Signal From Workspace block into the model. 3 From the Simulink Sinks library, click-and-drag a To Workspace block into the model. 4 Connect the two blocks. 5 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = [1:10; 1 1 0 0 1 1 0 0 1 1]' • Sample time = 1 • Samples per frame = 4 • Form output after final data value by = Setting to zero Based on these parameters, the Signal From Workspace block outputs a twochannel, frame-based signal has a sample period of 1 second, a frame period of 4 seconds, and a frame size of four samples. After the block outputs the signal, all subsequent outputs have a value of zero. The two channels contain the following values: • Channel 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0,... • Channel 2: 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,... 6 Save these parameters and close the dialog box by clicking OK. 7 From the Display menu, point to Signals & Ports, and select Signal Dimensions. 8 Run the model. The following figure is a graphical representation of the model's behavior during simulation. You can also open the model by typing ex_usingsfwblkfb at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-23 2 Input, Output, and Display 9 At the MATLAB command line, type yout. The following is the output displayed at the MATLAB command line. yout = 1 2 3 4 5 6 7 8 9 10 0 2-24 1 1 0 0 1 1 0 0 1 1 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Frame-Based Signals 0 0 Note that zeros were appended to the end of each channel. You have now successfully created a two-channel frame-based signal and exported it to the MATLAB workspace. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-25 2 Input, Output, and Display Create Multichannel Sample-Based Signals In this section... “Multichannel Sample-Based Signals” on page 2-26 “Create Multichannel Signals by Combining Single-Channel Signals” on page 2-26 “Create Multichannel Signals by Combining Multichannel Signals” on page 2-29 Multichannel Sample-Based Signals When you want to perform the same operations on several independent signals, you can group those signals together as a multichannel signal. For example, if you need to filter each of four independent signals using the same direct-form II transpose filter, you can combine the signals into a multichannel signal, and connect the signal to a single Digital Filter Design block. The block applies the filter to each channel independently. A sample-based signal with M*N channels is represented by a sequence of M-by-N matrices. Multiple sample-based signals can be combined into a single multichannel sample-based signal using the Concatenate block. In addition, several multichannel sample-based signals can be combined into a single multichannel sample-based signal using the same technique. Create Multichannel Signals by Combining Single-Channel Signals You can combine individual sample-based signals into a multichannel signal by using the Matrix Concatenate block in the Simulink Math Operations library: 1 Open the Matrix Concatenate Example 1 model by typing ex_cmbsnglchsbsigs at the MATLAB command line. 2-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Multichannel Sample-Based Signals 2 Double-click the Signal From Workspace block, and set the Signal parameter to 1:10. Click OK. 3 Double-click the Signal From Workspace1 block, and set the Signal parameter to -1:-1:-10. Click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-27 2 Input, Output, and Display 4 Double-click the Signal From Workspace2 block, and set the Signal parameter to zeros(10,1). Click OK. 5 Double-click the Signal From Workspace3 block, and set the Signal parameter to 5*ones(10,1). Click OK. 6 Double-click the Matrix Concatenate block. Set the block parameters as follows, and then click OK: • Number of inputs = 4 • Mode = Multidimensional array • Concatenate dimension = 1 7 Double-click the Reshape block. Set the block parameters as follows, and then click OK: • Output dimensionality = Customize • Output dimensions = [2,2] 8 Run the model. Four independent sample-based signals are combined into a 2-by-2 multichannel matrix signal. Each 4-by-1 output from the Matrix Concatenate block contains one sample from each of the four input signals at the same instant in time. The Reshape block rearranges the samples into a 2-by-2 matrix. Each element of this matrix is a separate channel. Note that the Reshape block works columnwise, so that a column vector input is reshaped as shown below. The 4-by-1 matrix output by the Matrix Concatenate block and the 2-by-2 matrix output by the Reshape block in the above model represent the same four-channel sample-based signal. In some cases, one representation of the signal may be more useful than the other. 2-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Multichannel Sample-Based Signals 9 At the MATLAB command line, type dsp_examples_yout. The four-channel, sample-based signal is displayed as a series of matrices in the MATLAB Command Window. Note that the last matrix contains only zeros. This is because every Signal From Workspace block in this model has its Form output after final data value by parameter set to Setting to Zero. Create Multichannel Signals by Combining Multichannel Signals You can combine existing multichannel sample-based signals into larger multichannel signals using the Simulink Matrix Concatenate block: 1 Open the Matrix Concatenate Example 2 model by typing ex_cmbmltichsbsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-29 2 Input, Output, and Display 2-30 2 Double-click the Signal From Workspace block, and set the Signal parameter to [1:10;-1:-1:-10]'. Click OK. 3 Double-click the Signal From Workspace1 block, and set the Signal parameter to [zeros(10,1) 5*ones(10,1)]. Click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Multichannel Sample-Based Signals 4 Double-click the Matrix Concatenate block. Set the block parameters as follows, and then click OK: • Number of inputs = 2 • Mode = Multidimensional array • Concatenate dimension = 1 5 Run the model. The model combines both two-channel sample-based signals into a four-channel signal. Each 2-by-2 output from the Matrix Concatenate block contains both samples from each of the two input signals at the same instant in time. Each element of this matrix is a separate channel. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-31 2 Input, Output, and Display Create Multichannel Frame-Based Signals In this section... “Multichannel Frame-Based Signals” on page 2-32 “Create Multichannel Signals Using Concatenate Block” on page 2-32 Multichannel Frame-Based Signals When you want to perform the same operations on several independent signals, you can group those signals together as a multichannel signal. For example, if you need to filter each of four independent signals using the same direct-form II transpose filter, you can combine the signals into a multichannel signal, and connect the signal to a single Digital Filter Design block. The block applies the filter to each channel independently. A frame-based signal with N channels and frame size M is represented by a sequence of M-by-N matrices. Multiple individual frame-based signals, with the same frame rate and size, can be combined into a multichannel frame-based signal using the Simulink Matrix Concatenate block. Individual signals can be added to an existing multichannel signal in the same way. Create Multichannel Signals Using Concatenate Block 2-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Multichannel Frame-Based Signals You can combine existing frame-based signals into a larger multichannel signal by using the Simulink Concatenate block. All signals must have the same frame rate and frame size. In this example, a single-channel frame-based signal is combined with a twochannel frame-based signal to produce a three-channel frame-based signal: 1 Open the Matrix Concatenate Example 3 model by typing ex_combiningfbsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-33 2 Input, Output, and Display 2 Double-click the Signal From Workspace block. Set the block parameters as follows: • Signal = [1:10;-1:-1:-10]' • Sample time = 1 2-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Create Multichannel Frame-Based Signals • Samples per frame = 4 Based on these parameters, the Signal From Workspace block outputs a frame-based signal with a frame size of four. 3 Save these parameters and close the dialog box by clicking OK. 4 Double-click the Signal From Workspace1 block. Set the block parameters as follows, and then click OK: • Signal = 5*ones(10,1) • Sample time = 1 • Samples per frame = 4 The Signal From Workspace1 block has the same sample time and frame size as the Signal From Workspace block. When you combine frame-based signals into multichannel signals, the original signals must have the same frame rate and frame size. 5 Double-click the Matrix Concatenate block. Set the block parameters as follows, and then click OK: • Number of inputs = 2 • Mode = Multidimensional array • Concatenate dimension = 2 6 Run the model. The 4-by-3 matrix output from the Matrix Concatenate block contains all three input channels, and preserves their common frame rate and frame size. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-35 2 Input, Output, and Display Deconstruct Multichannel Sample-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Split Multichannel Signals into Individual Signals” on page 2-36 “Split Multichannel Signals into Several Multichannel Signals” on page 2-39 Split Multichannel Signals into Individual Signals Multichannel signals, represented by matrices in the Simulink environment, are frequently used in signal processing models for efficiency and compactness. Though most of the signal processing blocks can process multichannel signals, you may need to access just one channel or a particular range of samples in a multichannel signal. You can access individual channels of the multichannel signal by using the blocks in the Indexing library. This library includes the Selector, Submatrix, Variable Selector, Multiport Selector, and Submatrix blocks. You can split a multichannel sample-based signal into single-channel sample-based signals using the Multiport Selector block. This block allows you to select specific rows and/or columns and propagate the selection to a chosen output port. In this example, a three-channel sample-based signal is deconstructed into three independent sample-based signals: 1 2-36 Open the Multiport Selector Example 1 model by typing ex_splitmltichsbsigsind at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Sample-Based Signals 2 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = randn(3,1,10) • Sample time = 1 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-37 2 Input, Output, and Display • Samples per frame = 1 Based on these parameters, the Signal From Workspace block outputs a threechannel, sample-based signal with a sample period of 1 second. 3 Save these parameters and close the dialog box by clicking OK. 4 Double-click the Multiport Selector block. Set the block parameters as follows, and then click OK: • Select = Rows • Indices to output = {1,2,3} Based on these parameters, the Multiport Selector block extracts the rows of the input. The Indices to output parameter setting specifies that row 1 of the input should be reproduced at output 1, row 2 of the input should be reproduced at output 2, and row 3 of the input should be reproduced at output 3. 5 Run the model. 6 At the MATLAB command line, type dsp_examples_yout. The following is a portion of what is displayed at the MATLAB command line. Because the input signal is random, your output might be different than the output show here. dsp_examples_yout(:,:,1) = -0.1199 dsp_examples_yout(:,:,2) = -0.5955 dsp_examples_yout(:,:,3) = -0.0793 This sample-based signal is the first row of the input to the Multiport Selector block. You can view the other two input rows by typing dsp_examples_yout1 and dsp_examples_yout2, respectively. You have now successfully created three, single-channel sample-based signals from a multichannel sample-based signal using a Multiport Selector block. 2-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Sample-Based Signals Split Multichannel Signals into Several Multichannel Signals Multichannel signals, represented by matrices in the Simulink environment, are frequently used in signal processing models for efficiency and compactness. Though most of the signal processing blocks can process multichannel signals, you may need to access just one channel or a particular range of samples in a multichannel signal. You can access individual channels of the multichannel signal by using the blocks in the Indexing library. This library includes the Selector, Submatrix, Variable Selector, Multiport Selector, and Submatrix blocks. You can split a multichannel sample-based signal into other multichannel sample-based signals using the Submatrix block. The Submatrix block is the most versatile of the blocks in the Indexing library because it allows arbitrary channel selections. Therefore, you can extract a portion of a multichannel sample-based signal. In this example, you extract a six-channel, sample-based signal from a 35-channel, sample-based signal (5by-7 matrix): 1 Open the Submatrix Example model by typing ex_splitmltichsbsigsev at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-39 2 Input, Output, and Display 2 Double-click the Constant block, and set the block parameters as follows: • Constant value = rand(5,7) • Interpret vector parameters as 1–D = Clear this check box • Sampling mode = Sample based • Sample Time = 1 2-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Sample-Based Signals Based on these parameters, the Constant block outputs a constant-valued, samplebased signal. 3 Save these parameters and close the dialog box by clicking OK. 4 Double-click the Submatrix block. Set the block parameters as follows, and then click OK: • Row span = Range of rows • Starting row = Index • Starting row index = 3 • Ending row = Last • Column span = Range of columns • Starting column = Offset from last • Starting column offset = 1 • Ending column = Last Based on these parameters, the Submatrix block outputs rows three to five, the last row of the input signal. It also outputs the second to last column and the last column of the input signal. 5 Run the model. The model should now look similar to the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-41 2 Input, Output, and Display Notice that the output of the Submatrix block is equivalent to the matrix created by rows three through five and columns six through seven of the input matrix. You have now successfully created a six-channel, sample-based signal from a 35-channel sample-based signal using a Submatrix block. 2-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Frame-Based Signals Deconstruct Multichannel Frame-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Split Multichannel Signals into Individual Signals” on page 2-43 “Reorder Channels in Multichannel Frame-Based Signals” on page 2-47 Split Multichannel Signals into Individual Signals Multichannel signals, represented by matrices in the Simulink environment, are frequently used in signal processing models for efficiency and compactness. Though most of the signal processing blocks can process multichannel signals, you may need to access just one channel or a particular range of samples in a multichannel signal. You can access individual channels of the multichannel signal by using the blocks in the Indexing library. This library includes the Selector, Submatrix, Variable Selector, Multiport Selector, and Submatrix blocks. It is also possible to use the Permute Matrix block, in the Matrix operations library, to reorder the channels of a frame-based signal. You can use the Multiport Selector block in the Indexing library to extract the individual channels of a multichannel frame-based signal. These signals form single-channel framebased signals that have the same frame rate and size of the multichannel signal. The figure below is a graphical representation of this process. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-43 2 Input, Output, and Display In this example, you use the Multiport Selector block to extract a single-channel and a two channel frame-based signal from a multichannel frame-based signal: 1 Open the Multiport Selector Example 2 model by typing ex_splitmltichfbsigsind at the MATLAB command line. 2-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Frame-Based Signals 2 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = [1:10;-1:-1:-10;5*ones(1,10)]' www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-45 2 Input, Output, and Display • Samples per frame = 4 Based on these parameters, the Signal From Workspace block outputs a threechannel, frame-based signal with a frame size of four. 3 Save these parameters and close the dialog box by clicking OK. 4 Double-click the Multiport Selector block. Set the block parameters as follows, and then click OK: • Select = Columns • Indices to output = {[1 3],2} Based on these parameters, the Multiport Selector block outputs the first and third columns at the first output port and the second column at the second output port of the block. Setting the Select parameter to Columns ensures that the block preserves the frame rate and frame size of the input. 5 Run the model. The figure below is a graphical representation of how the Multiport Selector block splits one frame of the three-channel frame-based signal into a single-channel signal and a two-channel signal. 2-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Frame-Based Signals The Multiport Selector block outputs a two-channel frame-based signal, comprised of the first and third column of the input signal, at the first port. It outputs a single-channel frame-based signal, comprised of the second column of the input signal, at the second port. You have now successfully created a single-channel and a two-channel frame-based signal from a multichannel frame-based signal using the Multiport Selector block. Reorder Channels in Multichannel Frame-Based Signals www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-47 2 Input, Output, and Display Multichannel signals, represented by matrices in Simulink, are frequently used in signal processing models for efficiency and compactness. Though most of the signal processing blocks can process multichannel signals, you may need to access just one channel or a particular range of samples in a multichannel signal. You can access individual channels of the multichannel signal by using the blocks in the Indexing library. This library includes the Selector, Submatrix, Variable Selector, Multiport Selector, and Submatrix blocks. It is also possible to use the Permute Matrix block, in the Matrix operations library, to reorder the channels of a frame-based signal. Some DSP System Toolbox blocks have the ability to process the interaction of channels. Typically, DSP System Toolbox blocks compare channel one of signal A to channel one of signal B. However, you might want to correlate channel one of signal A with channel three of signal B. In this case, in order to compare the correct signals, you need to use the Permute Matrix block to rearrange the channels of your frame-based signals. This example explains how to accomplish this task: 1 2-48 Open the Permute Matrix Example model by typing ex_reordermltichfbsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Frame-Based Signals 2 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = [1:10;-1:-1:-10;5*ones(1,10)]' • Sample time = 1 • Samples per frame = 4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-49 2 Input, Output, and Display Based on these parameters, the Signal From Workspace block outputs a threechannel, frame-based signal with a sample period of 1 second and a frame size of 4. The frame period of this block is 4 seconds. 3 Save these parameters and close the dialog box by clicking OK. 4 Double-click the Constant block. Set the block parameters as follows, and then click OK: • Constant value = [1 3 2] • Interpret vector parameters as 1–D = Clear this check box • Sampling mode = Frame based • Frame period = 4 The discrete-time, frame-based vector output by the Constant block tells the Permute Matrix block to swap the second and third columns of the input signal. Note that the frame period of the Constant block must match the frame period of the Signal From Workspace block. 5 Double-click the Permute Matrix block. Set the block parameters as follows, and then click OK: • Permute = Columns • Index mode = One-based Based on these parameters, the Permute Matrix block rearranges the columns of the input signal, and the index of the first column is now one. 6 Run the model. The figure below is a graphical representation of what happens to the first input frame during simulation. 2-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Deconstruct Multichannel Frame-Based Signals The second and third channel of the frame-based input signal are swapped. 7 At the MATLAB command line, type yout. You can now verify that the second and third columns of the input signal are rearranged. You have now successfully reordered the channels of a frame-based signal using the Permute Matrix block. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-51 2 Input, Output, and Display Import and Export Sample-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Import Sample-Based Vector Signals” on page 2-52 “Import Sample-Based Matrix Signals” on page 2-55 “Export Sample-Based Signals” on page 2-59 Import Sample-Based Vector Signals The Signal From Workspace block generates a sample-based vector signal when the variable or expression in the Signal parameter is a matrix and the Samples per frame parameter is set to 1. Each column of the input matrix represents a different channel. Beginning with the first row of the matrix, the block outputs one row of the matrix at each sample time. Therefore, if the Signal parameter specifies an M-by-N matrix, the output of the Signal From Workspace block is M 1-by-N row vectors representing N channels. The figure below is a graphical representation of this process for a 6-by-4 workspace matrix, A. 2-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals In the following example, you use the Signal From Workspace block to import a samplebased vector signal into your model: 1 Open the Signal From Workspace Example 3 model by typing ex_importsbvectorsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-53 2 Input, Output, and Display 2 At the MATLAB command line, type A = [1:100;-1:-1:-100]'; The matrix A represents a two column signal, where each column is a different channel. 3 At the MATLAB command line, type B = 5*ones(100,1); The vector B represents a single-channel signal. 4 Double-click the Signal From Workspace block, and set the block parameters as follows: • Signal = [A B] • Sample time = 1 2-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals • Samples per frame = 1 • Form output after final data value = Setting to zero The Signal expression [A B] uses the standard MATLAB syntax for horizontally concatenating matrices and appends column vector B to the right of matrix A. The Signal From Workspace block outputs a sample-based signal with a sample period of 1 second. After the block has output the signal, all subsequent outputs have a value of zero. 5 Save these parameters and close the dialog box by clicking OK. 6 Run the model. The following figure is a graphical representation of the model's behavior during simulation. The first row of the input matrix [A B] is output at time t=0, the second row of the input matrix is output at time t=1, and so on. You have now successfully imported a sample-based vector signal into your signal processing model using the Signal From Workspace block. Import Sample-Based Matrix Signals The Signal From Workspace block generates a sample-based matrix signal when the variable or expression in the Signal parameter is a three-dimensional array and the Samples per frame parameter is set to 1. Beginning with the first page of the array, the block outputs a single page of the array to the output at each sample time. Therefore, if the Signal parameter specifies an M-by-N-by-P array, the output of the Signal From Workspace block is P M-by-N matrices representing M*N channels. The following figure is a graphical illustration of this process for a 6-by-4-by-5 workspace array A. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-55 2 Input, Output, and Display In the following example, you use the Signal From Workspace block to import a fourchannel, sample-based matrix signal into a Simulink model: 1 2-56 Open the Signal From Workspace Example 4 model by typing ex_importsbmatrixsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals Also, the following variables are loaded into the MATLAB workspace: Fs 1x1 8 double array dsp_examples_A 2x2x100 3200 double array dsp_examples_sig1 1x1x100 800 double array dsp_examples_sig12 1x2x100 1600 double array dsp_examples_sig2 1x1x100 800 double array www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-57 2 Input, Output, and Display 2 dsp_examples_sig3 1x1x100 800 double array dsp_examples_sig34 1x2x100 1600 double array dsp_examples_sig4 1x1x100 800 double array mtlb 4001x1 32008 double array Double-click the Signal From Workspace block. Set the block parameters as follows, and then click OK: • Signal = dsp_examples_A • Sample time = 1 • Samples per frame = 1 • Form output after final data value = Setting to zero The dsp_examples_A array represents a four-channel, sample-based signal with 100 samples in each channel. This is the signal that you want to import, and it was created in the following way: dsp_examples_sig1 = reshape(1:100,[1 1 100]) dsp_examples_sig2 = reshape(-1:-1:-100,[1 1 100]) dsp_examples_sig3 = zeros(1,1,100) dsp_examples_sig4 = 5*ones(1,1,100) dsp_examples_sig12 = cat(2,sig1,sig2) dsp_examples_sig34 = cat(2,sig3,sig4) dsp_examples_A = cat(1,sig12,sig34) % 2-by-2-by-100 array 3 Run the model. The figure below is a graphical representation of the model's behavior during simulation. 2-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals The Signal From Workspace block imports the four-channel sample based signal from the MATLAB workspace into the Simulink model one matrix at a time. You have now successfully imported a sample-based matrix signal into your model using the Signal From Workspace block. Export Sample-Based Signals The To Workspace and Triggered To Workspace blocks are the primary blocks for exporting signals of all dimensions from a Simulink model to the MATLAB workspace. A sample-based signal, with M*N channels, is represented in Simulink as a sequence of M-by-N matrices. When the input to the To Workspace block is a sample-based signal, the block creates an M-by-N-by-P array in the MATLAB workspace containing the P most recent samples from each channel. The number of pages, P, is specified by the Limit data points to last parameter. The newest samples are added at the end of the array. The following figure is the graphical illustration of this process using a 6-by-4 samplebased signal exported to workspace array A. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-59 2 Input, Output, and Display The workspace array always has time running along its third dimension, P. Samples are saved along the P dimension whether the input is a matrix, vector, or scalar (single channel case). In the following example you use a To Workspace block to export a sample-based matrix signal to the MATLAB workspace: 1 2-60 Open the Signal From Workspace Example 6 model by typing ex_exportsbsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals Also, the following variables are loaded into the MATLAB workspace: dsp_examples_A 2x2x100 3200 double array dsp_examples_sig1 1x1x100 800 double array dsp_examples_sig12 1x2x100 1600 double array dsp_examples_sig2 1x1x100 800 double array www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-61 2 Input, Output, and Display dsp_examples_sig3 1x1x100 800 double array dsp_examples_sig34 1x2x100 1600 double array dsp_examples_sig4 1x1x100 800 double array In this model, the Signal From Workspace block imports a four-channel samplebased signal called dsp_examples_A. This signal is then exported to the MATLAB workspace using a To Workspace block. 2 Double-click the Signal From Workspace block. Set the block parameters as follows, and then click OK: • Signal = dsp_examples_A • Sample time = 1 • Samples per frame = 1 • Form output after final data value = Setting to zero Based on these parameters, the Signal From Workspace block outputs a samplebased signal with a sample period of 1 second. After the block has output the signal, all subsequent outputs have a value of zero. 3 Double-click the To Workspace block. Set the block parameters as follows, and then click OK: • Variable name = dsp_examples_yout • Limit data points to last parameter to inf • Decimation = 1 Based on these parameters, the To Workspace block exports its sample-based input signal to a variable called dsp_examples_yout in the MATLAB workspace. The workspace variable can grow indefinitely large in order to capture all of the input data. The signal is not decimated before it is exported to the MATLAB workspace. 4 Run the model. 5 At the MATLAB command line, type dsp_examples_yout. The four-channel sample-based signal, dsp_examples_A, is output at the MATLAB command line. The following is a portion of the output that is displayed. dsp_examples_yout(:,:,1) = 1 2-62 -1 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Sample-Based Signals 0 5 dsp_examples_yout(:,:,2) = 2 0 -2 5 dsp_examples_yout(:,:,3) = 3 0 -3 5 dsp_examples_yout(:,:,4) = 4 0 -4 5 Each page of the output represents a different sample time, and each element of the matrices is in a separate channel. You have now successfully exported a four-channel sample-based signal from a Simulink model to the MATLAB workspace using the To Workspace block. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-63 2 Input, Output, and Display Import and Export Frame-Based Signals Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Import Frame-Based Signals” on page 2-64 “Export Frame-Based Signals” on page 2-67 Import Frame-Based Signals The Signal From Workspace block creates a frame-based multichannel signal when the Signal parameter is a matrix, and the Samples per frame parameter, M, is greater than 1. Beginning with the first M rows of the matrix, the block releases M rows of the matrix (that is, one frame from each channel) to the output port every M*Ts seconds. Therefore, if the Signal parameter specifies a W-by-N workspace matrix, the Signal From Workspace block outputs a series of M-by-N matrices representing N channels. The workspace matrix must be oriented so that its columns represent the channels of the signal. The figure below is a graphical illustration of this process for a 6-by-4 workspace matrix, A, and a frame size of 2. 2-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Frame-Based Signals Note: Although independent channels are generally represented as columns, a singlechannel signal can be represented in the workspace as either a column vector or row vector. The output from the Signal From Workspace block is a column vector in both cases. In the following example, you use the Signal From Workspace block to create a threechannel frame-based signal and import it into the model: 1 Open the Signal From Workspace Example 5 model by typing ex_importfbsigs at the MATLAB command line. dsp_examples_A = [1:100;-1:-1:-100]'; % 100-by-2 matrix dsp_examples_B = 5*ones(100,1); % 100-by-1 column vector The variable called dsp_examples_A represents a two-channel signal with 100 samples, and the variable called dsp_examples_B represents a one-channel signal with 100 samples. Also, the following variables are defined in the MATLAB workspace: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-65 2 Input, Output, and Display 2 Double-click the Signal From Workspace block. Set the block parameters as follows, and then click OK: • Signal parameter to [dsp_examples_A dsp_examples_B] • Sample time parameter to 1 • Samples per frame parameter to 4 • Form output after final data value parameter to Setting to zero Based on these parameters, the Signal From Workspace block outputs a frame-based signal with a frame size of 4 and a sample period of 1 second. The signal's frame period is 4 seconds. The Signal parameter uses the standard MATLAB syntax for horizontally concatenating matrices to append column vector dsp_examples_B 2-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Frame-Based Signals to the right of matrix dsp_examples_A. After the block has output the signal, all subsequent outputs have a value of zero. 3 Run the model. The figure below is a graphical representation of how your three-channel, framebased signal is imported into your model. You have now successfully imported a three-channel frame-based signal into your model using the Signal From Workspace block. Export Frame-Based Signals The To Workspace and Triggered To Workspace blocks are the primary blocks for exporting signals of all dimensions from a Simulink model to the MATLAB workspace. A frame-based signal with N channels and frame size M is represented by a sequence of M-by-N matrices. When the input to the To Workspace block is a frame-based signal, the block creates a P-by-N array in the MATLAB workspace containing the P most recent samples from each channel. The number of rows, P, is specified by the Limit data points to last parameter. The newest samples are added at the bottom of the matrix. The following figure is a graphical illustration of this process for three consecutive frames of a frame-based signal with a frame size of 2 that is exported to matrix A in the MATLAB workspace. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-67 2 Input, Output, and Display In the following example, you use a To Workspace block to export a frame-based signal to the MATLAB workspace: 1 2-68 Open the Signal From Workspace Example 7 model by typing ex_exportfbsigs at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Frame-Based Signals Also, the following variables are defined in the MATLAB workspace: The variable called dsp_examples_A represents a two-channel signal with 100 samples, and the variable called dsp_examples_B represents a one-channel signal with 100 samples. dsp_examples_A = [1:100;-1:-1:-100]'; % 100-by-2 matrix dsp_examples_B = 5*ones(100,1); % 100-by-1 column vector 2 Double-click the Signal From Workspace block. Set the block parameters as follows, and then click OK: • Signal = [dsp_examples_A dsp_examples_B] • Sample time = 1 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-69 2 Input, Output, and Display • Samples per frame = 4 • Form output after final data value = Setting to zero Based on these parameters, the Signal From Workspace block outputs a frame-based signal with a frame size of 4 and a sample period of 1 second. The signal's frame period is 4 seconds. The Signal parameter uses the standard MATLAB syntax for horizontally concatenating matrices to append column vector dsp_examples_B to the right of matrix dsp_examples_A. After the block has output the signal, all subsequent outputs have a value of zero. 3 Double-click the To Workspace block. Set the block parameters as follows, and then click OK: • Variable name = dsp_examples_yout • Limit data points to last = inf • Decimation = 1 • Frames = Concatenate frames (2-D array) Based on these parameters, the To Workspace block exports its frame-based input signal to a variable called dsp_examples_yout in the MATLAB workspace. The workspace variable can grow indefinitely large in order to capture all of the input data. The signal is not decimated before it is exported to the MATLAB workspace, and each input frame is vertically concatenated to the previous frame to produce a 2D array output. 4 Run the model. The following figure is a graphical representation of the model's behavior during simulation. 2-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Import and Export Frame-Based Signals 5 At the MATLAB command line, type dsp_examples_yout. The output is shown below: dsp_examples_yout = 1 2 3 4 5 6 7 8 9 10 11 12 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 5 5 5 5 5 5 5 5 5 5 5 5 The frames of the signal are concatenated to form a two-dimensional array. You have now successfully output a frame-based signal to the MATLAB workspace using the To Workspace block. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-71 2 Input, Output, and Display Musical Instrument Digital Interface In this section... “About MIDI” on page 2-72 “MIDI Control Surfaces” on page 2-72 “Using MIDI Control Surfaces with MATLAB and Simulink” on page 2-73 About MIDI The Musical Instrument Digital Interface (MIDI) was originally developed to interconnect electronic musical instruments. This interface is very flexible and has many uses in many applications far beyond musical instruments. Its simple unidirectional messaging protocol supports many different kinds of messaging. Windows, Macintosh, and Linux platforms all have native support for MIDI, so software on any of these platforms can send and receive MIDI messages. See http://www.midi.org for more information about MIDI. MIDI Control Surfaces One kind of MIDI message is the Control Change message, used to communicate changes in controls, such as knobs, sliders, and buttons. A MIDI Control Surface is a device with controls that sends MIDI Control Change messages when you turn a knob, move a slider, or push a button on a MIDI control surface. This Control Change message indicates which control changed and what its new position is. MIDI control surfaces are quite generic because the interpretation of the Control Change message is entirely up to the message recipient. Even though some control surfaces are tailored for particular applications, the messages they send can be used to control anything. Hardware MIDI control surfaces are widely available in a range of configurations and prices. MIDI control apps can turn a smartphone or tablet into a virtual MIDI control surface. For custom applications, MIDI control surfaces are not difficult to build using, for example, Arduino boards. Because the MIDI messaging protocol is unidirectional, determining a particular control’s position requires that the receiver listen for Control Change messages that control sends. The protocol does not support querying the control for its position. 2-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Musical Instrument Digital Interface The simplest MIDI control surfaces are unidirectional; they end MIDI Control Change messages, but do not receive them. More sophisticated control surfaces are bidirectional: They can both send and receive Control Change messages. These control surfaces have knobs or sliders that can be operated automatically. For example, a control surface can have sliders or knobs that are motorized. When it receives a Control Change message, the appropriate control is moved to the position in the message. You can use this feature to synchronize software GUI with MIDI control surface. For example, moving a slider on the MIDI control surface sends a Control Change message to a GUI slider, which then moves to match the control surface. Similarly, moving the GUI slider sends a Control Change message to the MIDI control surface, which then moves to match the GUI slider. Using MIDI Control Surfaces with MATLAB and Simulink The DSP System Toolbox product enables you to use MIDI control surfaces to control MATLAB programs and Simulink models by providing the capability to listen to Control Change messages. The toolbox also provides a limited capability to send Control Change messages to support synchronizing MIDI controls. The DSP System Toolbox interface to MIDI control surfaces includes five functions and one block: • midiid function • midicontrols function • midiread function • midisync function • midicallback function • MIDI Controls block Initial Setup Your MIDI control surface should be connected to your computer, and turned on, before starting MATLAB. Instructions for connecting your MIDI device to your computer vary from device to device. See the instructions that came with your particular device. If you start MATLAB before connecting your device, MATLAB may not recognize your device when you connect it. To correct the problem, restart MATLAB with the device already connected. Next, set the MATLAB preference, specifying the name of the default MIDI device. Use midiid to determine the name of the device, and then use setpref to set the preference: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-73 2 Input, Output, and Display >> [control, device] = midiid Move the control you wish to identify; type ^C to abort. Waiting for control message... done control = 1082 device = BCF2000 >> setpref('midi', 'DefaultDevice', device) >> This preference persists across MATLAB sessions, so you only have to set it once, unless you want to change devices. If you do not set this preference, MATLAB and the host operating system choose a device for you. However, such autoselection can cause unpredictable results because many computers have “virtual” (software) MIDI devices installed that you may not be aware of. For predictable behavior, you should set the preference. You can always override this default and explicitly specify a device name. Thus, you can use multiple MIDI devices simultaneously. Identifying Controls Before you can connect a MIDI control with MATLAB or Simulink, you must know the identifiers for that particular control: • Control number • Device name The control number is a fixed integer assigned by the device manufacturer. Some devices may change the assigned number based on various modes, or you can reprogram the number. The device name is determined by the manufacturer and the host operating system. You use midiid to determine both. You do not usually have to use midiid repeatedly. If you use a single device in most cases, then specify that device as the default hardware. the You can save the control numbers in a function, a .mat file, or whatever form you find convenient. This example shows a function returning a struct with all the control numbers for a Behringer BCF2000: function ctls = BCF2000 % BCF2000 return MIDI control number assignments % for Behringer BCF2000 MIDI control surface 2-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Musical Instrument Digital Interface ctls.knobs = 1001:1008; ctls.buttons = [1065:1072;1073:1080]; ctls.sliders = 1081:1088; end MATLAB Interface To use the MATLAB interface functions, first call midicontrols to specify any devices or controls to listen to. midicontrols returns an object, which you pass to the other functions for subsequent operations. You can now read the values of the specified MIDI controls by calling midiread with that object. MATLAB can respond to changes in MIDI controls by periodically calling midiread. You can also set a callback on the specified MIDI controls by calling midicallback with that object and a function handle. The next time the MIDI controls change value, the function handle is invoked and passed to the object. The callback function typically calls midiread to determine the new value of the MIDI controls. You can use this callback when you want a MIDI control to trigger an action (such as update a GUI). Using this approach prevents having a continuously running MATLAB program in the command window. Synchronization If midiread is called before the MIDI control sends a Control Change message, the midicontrols object has no information about the actual state of the MIDI control. During this time, the midicontrols object and the actual MIDI control are out of sync with each other. Thus, calling midiread returns the initial value that was specified in the call to midicontrols (0 by default). You can synchronize the object with the control by moving the MIDI control. The MIDI control responds by sending a Control Change message causing the midicontrols object to sync to the MIDI control. If your MIDI control surface is bidirectional, you can sync in the other direction by calling midisync to send the midicontrols object’s initial value to the actual MIDI control. The MIDI control responds by moving into sync with the midicontrols object. It is generally harmless to call midisync even if the MIDI control surface is not bidirectional, so it is usually good practice to call midisync immediately after calling midicontrols. Synchronization is also useful to link a MIDI control with a GUI control (a uicontrol slider, for example), so that when one control is changed, the other control tracks it. Typically, you implement such tracking by setting callback functions on both the MIDI control (using midicallback) and the GUI control. The MIDI control callback sends its www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-75 2 Input, Output, and Display new value to the GUI control and the GUI control sends its value to the MIDI control, using midisync. Simulink Interface The MIDI Controls block provides the Simulink interface. See the block reference page MIDI Controls for more details. 2-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data Display Time-Domain Data In this section... “Configure the Time Scope Properties” on page 2-78 “Use the Simulation Controls” on page 2-83 “Modify the Time Scope Display” on page 2-84 “Inspect Your Data (Scaling the Axes and Zooming)” on page 2-86 “Manage Multiple Time Scopes” on page 2-89 The following tutorial shows you how to configure the Time Scope blocks in the ex_timescope_tut model to display time-domain signals. To get started with this tutorial, open the model by typing ex_timescope_tut at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-77 2 Input, Output, and Display Use the following workflow to configure the Time Scope blocks in the ex_timescope_tut model: 1 “Configure the Time Scope Properties” on page 2-78 2 “Use the Simulation Controls” on page 2-83 3 “Modify the Time Scope Display” on page 2-84 4 “Inspect Your Data (Scaling the Axes and Zooming)” on page 2-86 5 “Manage Multiple Time Scopes” on page 2-89 Configure the Time Scope Properties The Configuration Properties dialog box provides a central location from which you can change the appearance and behavior of the Time Scope block. To open the Configuration Properties dialog box, you must first open the Time Scope window by double-clicking the Time Scope block in your model. When the window opens, select View > Configuration Properties. Alternatively, in the Time Scope toolbar, click the Configuration Properties button. 2-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data The Configuration Properties dialog box has four different tabs, Main, Time, Display, and Logging, each of which offers you a different set of options. For more information about the options available on each of the tabs, see the Time Scope block reference page. Note: As you progress through this workflow, notice the blue question mark icon ( ) in the lower-left corner of the subsequent dialog boxes. This icon indicates that contextsensitive help is available. You can get more information about any of the parameters on the dialog box by right-clicking the parameter name and selecting What's This? Configure Appearance and Specify Signal Interpretation First, you configure the appearance of the Time Scope window and specify how the Time Scope block should interpret input signals. In the Configuration Properties dialog box, click the Main tab. Choose the appropriate parameter settings for the Main tab, as shown in the following table. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-79 2 Input, Output, and Display Parameter Setting Open at Checked simulation start Number of input 2 ports Input processing Columns as channels (frame based) Maximize axes Auto Axes scaling Manual In this tutorial, you want the block to treat the input signal as frame-based, so you must set the Input processing parameter to Columns as channels (frame based). Configure Axes Scaling and Data Alignment The Main tab also allows you to control when and how Time Scope scales the axes. These options also control how Time Scope aligns your data with respect to the axes. Click the link labeled Configure... to the right of the Axes scaling parameter to see additional options for axes scaling. After you click this button, the label changes to Hide... and new parameters appear. The following table describes these additional options. Parameter Description Axes scaling Specify when the scope should automatically scale the axes. You can select one of the following options: • Manual — When you select this option, the scope does not automatically scale the axes. You can manually scale the axes in any of the following ways: • Select Tools > Axes Scaling Properties. • Press one of the Scale Axis Limits toolbar buttons. • When the scope figure is the active window, press Ctrl and A simultaneously. • Auto — When you select this option, the scope scales the axes as needed, both during and after simulation. Selecting this option shows the Do not allow Y-axis limits to shrink check box. 2-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data Parameter Description • After N Updates — Selecting this option causes the scope to scale the axes after a specified number of updates. Selecting this option shows the Number of updates edit box. By default, this property is set to Auto. This property is “Tunable”. Scale axes limits Select this check box to scale the axes when the simulation stops. The y-axis is always scaled. The x-axis limits are only scaled if you at stop also select the Scale X-axis limits check box. Data range (%) Allows you to specify how much white space surrounds your signal in the Time Scope window. You can specify a value for both the y- and x-axis. The higher the value you enter for the y-axis Data range (%), the tighter the y-axis range is with respect to the minimum and maximum values in your signal. For example, to have your signal cover the entire y-axis range when the block scales the axes, set this value to 100. Align Allows you to specify where the block should align your data with respect to each axis. You can choose to have your data aligned with the top, bottom, or center of the y-axis. Additionally, if you select the Autoscale X-axis limits check box, you can choose to have your data aligned with the right, left, or center of the x-axis. Set the parameters to the values shown in the following table. Parameter Setting Axes scaling Manual Scale axes limits Checked at stop Data range (%) 80 Align Center Autoscale X-axis Unchecked limits Set Time Domain Properties In the Configuration Properties dialog box, click the Time tab. Set the parameters to the values shown in the following table. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-81 2 Input, Output, and Display Parameter Setting Time span One frame period Time span overrun action Wrap Time units Metric (based on Time Span) Time display offset 0 Time-axis labels All Show time-axis label Checked The Time span parameter allows you to enter a numeric value, a variable that evaluates to a numeric value, or select the One frame period menu option. You can also select the Auto menu option; in this mode, Time Scope automatically calculates the appropriate value for time span from the difference between the simulation “Start time” and “Stop time” parameters. The actual range of values that the block displays on the time-axis depends on the value of both the Time span and Time display offset parameters. See the following figure. If the Time display offset parameter is a scalar, the value of the minimum time-axis limit is equal to the Time display offset. In addition, the value of the maximum timeaxis limit is equal to the sum of the Time display offset parameter and the Time span parameter. For information on the other parameters in the Time Scope window, see the Time Scope reference page. In this tutorial, the values on the time-axis range from 0 to One frame period, where One frame period is 0.05 seconds (50 ms). 2-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data Set Display Properties In the Configuration Properties dialog box, click the Display tab. Set the parameters to the values shown in the following table. Parameter Setting Active display 1 Title Show legend Checked Show grid Checked Plot signal(s) as magnitude and phase Unchecked Y-limits (Minimum) -2.5 Y-limits (Maximum) 2.5 Y-label Amplitude Set Logging Properties In the Configuration Properties dialog box, click the Logging tab. Set Log data to workspace to unchecked. Click OK to save your changes and close the Configuration Properties dialog box. Note: If you have not already done so, repeat all of these procedures for the Time Scope1 block (except leave the Number of input ports on the Main tab as 1) before continuing with the other sections of this tutorial. Use the Simulation Controls One advantage to using the Time Scope block in your models is that you can control model simulation directly from the Time Scope window. The buttons on the Simulation Toolbar of the Time Scope window allow you to play, pause, stop, and take steps forward or backward through model simulation. Alternatively, there are several keyboard shortcuts you can use to control model simulation when the Time Scope is your active window. You can access a list of keyboard shortcuts for the Time Scope by selecting Help > Keyboard Command Help. The following procedure introduces you to these features. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-83 2 Input, Output, and Display 1 If the Time Scope window is not open, double-click the block icon in the ex_timescope_tut model. Start model simulation. In the Time Scope window, on the Simulation Toolbar, click the Run button ( ) on the Simulation Toolbar. You can also use one of the following keyboard shortcuts: • Ctrl+T • P • Space 2 While the simulation is running and the Time Scope is your active window, pause the simulation. Use either of the following keyboard shortcuts: • P • Space Alternatively, you can pause the simulation in one of two ways: • In the Time Scope window, on the Simulation Toolbar, click the Pause button ( ). • From the Time Scope menu, select Simulation > Pause. 3 With the model simulation still paused, advance the simulation by a single time step. To do so, in the Time Scope window, on the Simulation Toolbar, click the Next Step button ( ). Next, try using keyboard shortcuts to achieve the same result. Press the Page Down key to advance the simulation by a single time step. 4 Resume model simulation using any of the following methods: • From the Time Scope menu, select Simulation > Continue. • In the Time Scope window, on the Simulation Toolbar, click the Continue button ( ). • Use a keyboard shortcut, such as P or Space. Modify the Time Scope Display You can control the appearance of the Time Scope window using options from the display or from the View menu. Among other capabilities, these options allow you to: 2-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data • Control the display of the legend • Edit the line properties of your signals • Show or hide the available toolbars Change Signal Names in the Legend You can change the name of a signal by double-clicking the signal name in the legend. By default, the Time Scope names the signals based on the block they are coming from. For this example, set the signal names as shown in the following table. Block Name Original Signal Name New Signal Name Time Scope Add Noisy Sine Wave Time Scope Digital Filter – Lowpass Filtered Noisy Sine Wave Time Scope1 Sine Wave Original Sine Wave Modify Axes Colors and Line Properties Use the Style dialog box to modify the appearance of the axes and the lines for each of the signals in your model. In the Time Scope menu, select View > Style. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-85 2 Input, Output, and Display 1 Change the Plot Type parameter to Auto for each Time Scope block. This setting ensures that Time Scope displays a line graph if the signal is continuous and a stairstep graph if the signal is discrete. 2 Change the Axes colors parameters for each Time Scope block. Leave the axes background color as black and set the ticks, labels, and grid colors to white. 3 Set the Properties for line parameter to the name of the signal for which you would like to modify the line properties. Set the line properties for each signal according to the values shown in the following table. Block Name Signal Name Line Line Width Marker Color Time Scope Noisy Sine Wave ———— 0.5 White Time Scope Filtered Noisy Sine Wave ———— 0.5 Red Time Scope1 Original Sine Wave ———— 0.5 Yellow none Show and Hide Time Scope Toolbars You can also use the options on the View menu to show or hide toolbars on the Time Scope window. For example: • To hide the simulation controls, select View > Toolbar. Doing so removes the simulation toolbar from the Time Scope window and also removes the check mark from next to the Toolbar option in the View menu. • You can choose to show the simulation toolbar again at any time by selecting View > Toolbar. Verify that all toolbars are visible before moving to the next section of this tutorial. Inspect Your Data (Scaling the Axes and Zooming) Time Scope has plot navigation tools that allow you to scale the axes and zoom in or out on the Time Scope window. The axes scaling tools allow you to specify when and how often the Time Scope scales the axes. So far in this tutorial, you have configured the Time Scope block for manual axes scaling. Use one of the following options to manually scale the axes: 2-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data • From the Time Scope menu, select Tools > Scale Axes Limits. • Press the Scale Axes Limits toolbar button ( ). • With the Time Scope as your active window, press Ctrl + A. Adjust White Space Around the Signal You can control how much space surrounds your signal and where your signal appears in relation to the axes. To adjust the amount of space surrounding your signal and realign it with the axes, you must first open the Tools—Plot Navigation Properties dialog box. From the Time Scope menu, select Tools > Axes Scaling Properties . In the Tools:Plot Navigation options dialog box, set the Data range (%) and Align parameters. In a previous section, you set these parameters to 80 and Center, respectively. • To decrease the amount of space surrounding your signal, set the Data range (%) parameter on the Tools:Plot Navigation Options dialog box to 90. • To align your signal with the bottom of the Y-axis, set the Align parameter to Bottom. The next time you scale the axes of the Time Scope window, the window appears as follows. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-87 Input, Output, and Display ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 2-88 Display Time-Domain Data Use the Zoom Tools The zoom tools allow you to zoom in simultaneously in the directions of both the x- and yaxes , or in either direction individually. For example, to zoom in on the signal between 5010 ms and 5020 ms, you can use the Zoom X option. • To activate the Zoom X tool, select Tools > Zoom X, or press the corresponding toolbar button ( ). The Time Scope indicates that the Zoom X tool is active by depressing the toolbar button and placing a check mark next to the Tools > Zoom X menu option. • To zoom in on the region between 5010 ms and 5020 ms, in the Time Scope window, click and drag your cursor from the 10 ms mark to the 20 ms mark. • While zoomed in, to activate the Pan tool, select Tools > Pan, or press the corresponding toolbar button ( ). • To zoom out of the Time Scope window, right-click inside the window, and select Zoom Out. Alternatively, you can return to the original view of your signal by rightclicking inside the Time Scope window and selecting Reset to Original View. Manage Multiple Time Scopes The Time Scope block provides tools to help you manage multiple Time Scope blocks in your models. The model used throughout this tutorial, ex_timescope_tut, contains two Time Scope blocks, labeled Time Scope and Time Scope1. The following sections discuss the tools you can use to manage these Time Scope blocks. Open All Time Scope Windows When you have multiple windows open on your desktop, finding the one you need can be difficult. The Time Scope block offers a View > Bring All Time Scopes Forward menu option to help you manage your Time Scope windows. Selecting this option brings all Time Scope windows into view. If a Time Scope window is not currently open, use this menu option to open the window and bring it into view. To try this menu option in the ex_timescope_tut model, open the Time Scope window, and close the Time Scope1 window. From the View menu of the Time Scope window, select Bring All Time Scopes Forward. The Time Scope1 window opens, along with the already active Time Scope window. If you have any Time Scope blocks in other open Simulink models, then these also come into view. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-89 2 Input, Output, and Display Open Time Scope Windows at Simulation Start When you have multiple Time Scope blocks in your model, you may not want all Time Scope windows to automatically open when you start simulation. You can control whether or not the Time Scope window opens at simulation start by selecting File > Open at Start of Simulation from the Time Scope window. When you select this option, the Time Scope GUI opens automatically when you start the simulation. When you do not select this option, you must manually open the scope window by doubleclicking the corresponding Time Scope block in your model. Find the Right Time Scope Block in Your Model Sometimes, you have multiple Time Scope blocks in your model and need to find the location of one that corresponds to the active Time Scope window. In such cases, you can use the View > Highlight Simulink Block menu option or the corresponding toolbar ). When you do so, the model window becomes your active window, and the button ( corresponding Time Scope block flashes three times in the model window. This option can help you locate Time Scope blocks in your model and determine to which signals they are attached. To try this feature, open the Time Scope window, and on the simulation toolbar, click the Highlight Simulink Block button. Doing so opens the ex_timescope_tut model. The Time Scope block flashes three times in the model window, allowing you to see where in your model the block of interest is located. Docking Time Scope Windows in the Scopes Group Container When you have multiple Time Scope blocks in your model you may want to see them in the same window and compare them side-by-side. In such cases, you can select the Dock Time Scope button ( ) at the top-right corner of the Time Scope window for the Time Scope block. 2-90 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Time-Domain Data The Time Scope window now appears in the Scopes group container. Next, press the Dock Time Scope button at the top-right corner of the Time Scope window for the Time Scope1 block. By default, the Scopes group container is situated above the MATLAB Command Window. However, you can undock the Scopes group container by pressing the Show Actions button ( ) at the top-right corner of the container and selecting Undock. The Scopes group container is now independent from the MATLAB Command Window. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-91 2 Input, Output, and Display Once docked, the Scopes group container displays the toolbar and menu bar of the Time Scope window. If you open additional instances of Time Scope, a new Time Scope window appears in the Scopes group container. You can undock any instance of Time Scope by pressing the corresponding Undock button ( ) in the title bar of each docked instance. If you close the Scopes group container, all docked instances of Time Scope close but the Simulink model continues to run. Close All Time Scope Windows If you save your model with Time Scope windows open, those windows will reopen the next time you open the model. Reopening the Time Scope windows when you open your model can increase the amount of time it takes your model to load. If you are working with a large model, or a model containing multiple Time Scopes, consider closing all Time Scope windows before you save and close that model. To do so, use the File > Close All Time Scope Windows menu option. To use this menu option in the ex_timescope_tut model, open the Time Scope or Time Scope1 window, and select File > Close All Time Scope Windows. Both the Time Scope and Time Scope1 windows close. If you now save and close the model, the Time Scope windows do not automatically open the next time you open the model. You can open Time Scope windows at any time by double-clicking a Time Scope block in your model. Alternatively, you can choose to automatically open the Time Scope windows at simulation start. To do so, from the Time Scope window, select File > Open at Start of Simulation. 2-92 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Frequency-Domain Data in Spectrum Analyzer Display Frequency-Domain Data in Spectrum Analyzer You can use DSP System Toolbox blocks to work with signals in both the time and frequency domain. To display frequency-domain signals, you can use blocks from the Sinks library, such as the Vector Scope, Spectrum Analyzer, Matrix Viewer, and Waterfall Scope blocks. With the Spectrum Analyzer block, you can display the frequency spectra of time-domain input data. In contrast to the Vector Scope block, the Spectrum Analyzer block computes the Fast Fourier Transform (FFT) of the input signal internally, transforming the signal into the frequency domain. This example shows how you can use a Spectrum Analyzer block to display the frequency content of two frame-based signals simultaneously: 1 At the MATLAB command prompt, type ex_spectrumanalyzer_tut. The Spectrum Analyzer example opens, and the variables, Fs and mtlb, are loaded into the MATLAB workspace. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-93 2 Input, Output, and Display 2 Double-click the Signal From Workspace block. Set the block parameters as follows, and then click OK: • Signal = mtlb • Sample time = 1 • Samples per frame = 16 • Form output after final data value = Cyclic Repetition Based on these parameters, the Signal From Workspace block repeatedly outputs the input signal, mtlb, as a frame-based signal with a sample period of 1 second. 2-94 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Frequency-Domain Data in Spectrum Analyzer 3 Create two distinct signals to send to the Spectrum Analyzer block. Use the Digital Filter Design block to filter the input signal, using the default parameters. 4 Double-click the Matrix Concatenate block. Set the block parameters as follows, and then click OK: • Number of inputs = 2 • Mode = Multidimensional array www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-95 2 Input, Output, and Display • Concatenate dimension = 2 The Matrix Concatenate block combines the two signals so that each column corresponds to a different signal. 5 Double-click the Spectrum Analyzer block. The Spectrum Analyzer figure appears. In the menu, select View > Spectrum Settings. The Spectrum Settings panel opens. • Expand the Main options pane, if it is not already expanded. • Set Type to Power. • Select the Full frequency span check box. • Set RBW (Hz) to 5.91e-3. • Expand the Trace options pane, if it is not already expanded. • Set Units to dBW. • Set Averages to 2. • Expand the Window options pane, if it is not already expanded. • Set Overlap (%) to 50. • Set Window to Hann. Based on these parameters, the Spectrum Analyzer uses 128 samples from each input channel to calculate a new windowed data segment, as shown in the following equation. D= NENBW ¥ Fs 1 .512 ¥ 1 Hz = = 128 samples RBW 11 .8125 ¥ 10 -3 Hz There are also 128 frequency points in the FFT. Also, because Overlap (%) is set to 50, there is a buffer overlap length of 64 samples in each spectral estimate, as shown in the following equation. OL = OP 100 ¥L= 50 ¥ 128 = 64 samples 100 Every time the scope updates the display, 64 points are plotted for each channel. At 16 samples per frame, Spectrum Analyzer waits for 3 frames or 48 samples before displaying the first power spectral estimate. 2-96 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Display Frequency-Domain Data in Spectrum Analyzer 6 Fit all the calculated data points into the display. In the Spectrum Analyzer menu, select Tools > Automatically Scale Axes Limits. 7 In the Spectrum Analyzer menu, select View > Configuration Properties. Then, select the Show legend check box. 8 Run the model. The Spectrum Analyzer block computes the FFT of each of the input signals. It then displays the power spectra of the frequency-domain signals in the Spectrum Analyzer window. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-97 Input, Output, and Display ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 2-98 Display Frequency-Domain Data in Spectrum Analyzer The power spectrum of the first input signal, from column one, is the yellow line. The power spectrum of the second input signal, from column two, is the blue line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-99 2 Input, Output, and Display Visualize Central Limit Theorem in Array Plot In this section... “Display a Uniform Distribution” on page 2-100 “Display the Sum of Many Uniform Distributions” on page 2-101 “Inspect Your Data by Zooming” on page 2-103 Display a Uniform Distribution This example shows how to use and configure the dsp.ArrayPlot to visualize the Central Limit Theorem. This theorem states that the mean of a large number of independent random variables with finite mean and variance exhibits a normal distribution. First, generate uniformly distributed random variables in MATLAB using the rand function. Find their distributions using the hist function. At the MATLAB command line, type: numsamples = 1e4; numbins = 20; r = rand(numsamples,1); hst = hist(r,numbins); Create a new Array Plot object. hap3 = dsp.ArrayPlot; Configure the properties of the Array Plot object to plot a histogram. hap3 = dsp.ArrayPlot; hap3.XOffset = 0; hap3.SampleIncrement = 1/numbins; hap3.PlotType = 'Stem'; hap3.YLimits = [0, max(hst)+1]; Call the step method to plot the uniform distribution. step(hap3,hst'); The following Array Plot figure appears, showing a uniform distribution. 2-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualize Central Limit Theorem in Array Plot Display the Sum of Many Uniform Distributions Next, calculate the mean of multiple uniformly distributed random variables. As the number of random variables increases, the distribution more closely resembles a normal curve. Run the release method to let property values and input characteristics change. At the MATLAB command line, type: release(hap3); Change the configuration of the Array Plot properties for the display of a distribution function. numbins = 201; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-101 2 Input, Output, and Display numtrials = 100; r = zeros(numsamples,1); hap3.SampleIncrement = 1/numbins; hap3.PlotType = 'Stairs'; Call the step method repeatedly to plot the uniform distribution. for ii = 1:numtrials r = rand(numsamples,1)+r; hst = hist(r/ii,0:1/numbins:1); hap3.YLimits = [min(hst)-1, max(hst)+1]; step(hap3,hst'); pause(0.1); end When the simulation has finished, the Array Plot figure displays a bell curve, indicating a distribution that is close to normal. 2-102 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Visualize Central Limit Theorem in Array Plot Inspect Your Data by Zooming The zoom tools allow you to zoom in simultaneously in the directions of both the x- and y-axes or in either direction individually. For example, to zoom in on the distribution between 0.3 and 0.7, you can use the Zoom X option. • To activate the Zoom X tool, select Tools > Zoom X, or press the corresponding toolbar button ( ). You can determine if the Zoom X tool is active by looking for an indented toolbar button or a check mark next to the Tools > Zoom X menu option. • Next, zoom in on the region between 0.3 and 0.7. In the Array Plot window, click on the 0.3-second mark, and drag to the 0.7-second mark. The display reflects this new xaxis setting, as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2-103 Input, Output, and Display ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 2 2-104 3 Data and Signal Management Learn concepts such as sample- and frame-based processing, sample rate, delay and latency. • “Sample- and Frame-Based Concepts” on page 3-2 • “Inspect Sample and Frame Rates in Simulink” on page 3-8 • “Convert Sample and Frame Rates in Simulink” on page 3-19 • “Buffering and Frame-Based Processing” on page 3-43 • “Delay and Latency” on page 3-59 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3 Data and Signal Management Sample- and Frame-Based Concepts In this section... “Sample- and Frame-Based Signals” on page 3-2 “Model Sample- and Frame-Based Signals in MATLAB and Simulink” on page 3-3 “What Is Sample-Based Processing?” on page 3-4 “What Is Frame-Based Processing?” on page 3-4 Sample- and Frame-Based Signals Sample-based signals are the most basic type of signal and are the easiest to construct from a real-world (physical) signal. You can create a sample-based signal by sampling a physical signal at a given sample rate, and outputting each individual sample as it is received. In general, most Digital-to-Analog converters output sample-based signals. You can create frame-based signals from sample-based signals. When you buffer a batch of N samples, you create a frame of data. You can then output sequential frames of data at a rate that is 1/N times the sample rate of the original sample-based signal. The rate at which you output the frames of data is also known as the frame rate of the signal. Frame-based data is a common format in real-time systems. Data acquisition hardware often operates by accumulating a large number of signal samples at a high rate. The hardware then propagates those samples to the real-time system as a block of data. Doing so maximizes the efficiency of the system by distributing the fixed process overhead across many samples. The faster data acquisition is suspended by slower interrupt processes after each frame is acquired, rather than after each individual sample. See “Benefits of Frame-Based Processing” on page 3-6 for more information. DSP System Toolbox Source Blocks 3-2 Create Sample-Based Signals Create Frame-Based Signals Chirp X X Constant X X Constant Diagonal Matrix X Discrete Impulse X DSP Constant (Obsolete) X From Audio Device X www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان X X Sample- and Frame-Based Concepts DSP System Toolbox Source Blocks Create Sample-Based Signals Create Frame-Based Signals From Multimedia File X X Identity Matrix X MIDI Controls X Multiphase Clock X X N-Sample Enable X X Random Source X Signal From Workspace X X Sine Wave X X UDP Receive X Model Sample- and Frame-Based Signals in MATLAB and Simulink When you process signals using DSP System Toolbox software, you can do so in either a sample- or frame-based manner. When you are working with blocks in Simulink, you can specify, on a block-by-block basis, which type of processing the block performs. In most cases, you specify the processing mode by setting the Input processing parameter. Alternatively, when you are using System objects in MATLAB, you specify the processing mode using the FrameBasedProcessing property. The following table shows the common parameter settings you can use to perform sample- and frame-based processing in MATLAB and Simulink. Sample-Based Processing Frame-Based Processing MATLAB — System objects FrameBasedProcessing = FrameBasedProcessing = False True Simulink — Blocks Input processing = Elements as channels (sample based) Input processing = Columns as channels (frame based) Set the FrameBasedProcessing Property of a System object All System objects support sample-based processing and some System objects support both sample- and frame-based processing. To specify how your System object should process input data, you set the FrameBasedProcessing property. The property has a www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-3 3 Data and Signal Management default value of true, which enables frame-based processing. To specify sample-based processing, set the FrameBasedProcessing property to false. What Is Sample-Based Processing? In sample-based processing, blocks process signals one sample at a time. Each element of the input signal represents one sample in a distinct channel. For example, from a sample-based processing perspective, the following 3-by-2 matrix contains the first sample in each of six independent channels. When you configure a block to perform sample-based processing, the block interprets scalar input as a single-channel signal. Similarly, the block interprets an M-by-N matrix as multichannel signal with M*N independent channels. For example, in sample-based processing, blocks interpret the following sequence of 3-by-2 matrices as a six-channel signal. For more information about the recent changes to frame-based processing, see the “Frame-Based Processing” section of the DSP System Toolbox Release Notes. What Is Frame-Based Processing? In frame-based processing, blocks process data one frame at a time. Each frame of data contains sequential samples from an independent channel. Each channel is represented 3-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample- and Frame-Based Concepts by a column of the input signal. For example, from a frame-based processing perspective, the following 3-by-2 matrix has two channels, each of which contains three samples. When you configure a block to perform frame-based processing, the block interprets an M-by-1 vector as a single-channel signal containing M samples per frame. Similarly, the block interprets an M-by-N matrix as a multichannel signal with N independent channels and M samples per channel. For example, in frame-based processing, blocks interpret the following sequence of 3-by-2 matrices as a two-channel signal with a frame size of 3. Using frame-based processing is advantageous for many signal processing applications because you can process multiple samples at once. By buffering your data into frames and processing multisample frames of data, you can often improve the computational time of your signal processing algorithms. To perform frame-based processing, you must have a DSP System Toolbox license. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-5 3 Data and Signal Management For more information about the recent changes to frame-based processing, see the “Frame-Based Processing” section of the DSP System Toolbox Release Notes. Benefits of Frame-Based Processing Frame-based processing is an established method of accelerating both real-time systems and model simulations. Accelerate Real-Time Systems Frame-based data is a common format in real-time systems. Data acquisition hardware often operates by accumulating a large number of signal samples at a high rate, and then propagating those samples to the real-time system as a block of data. This type of propagation maximizes the efficiency of the system by distributing the fixed process overhead across many samples; the faster data acquisition is suspended by slower interrupt processes after each frame is acquired, rather than after each individual sample is acquired. The following figure illustrates how frame-based processing increases throughput. The thin blocks each represent the time elapsed during acquisition of a sample. The thicker blocks each represent the time elapsed during the interrupt service routine (ISR) that reads the data from the hardware. In this example, the frame-based operation acquires a frame of 16 samples between each ISR. Thus, the frame-based throughput rate is many times higher than the sample-based alternative. 3-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sample- and Frame-Based Concepts Be aware that frame-based processing introduces a certain amount of latency into a process due to the inherent lag in buffering the initial frame. In many instances, however, you can select frame sizes that improve throughput without creating unacceptable latencies. For more information, see “Delay and Latency” on page 3-59. Accelerate Model Simulations The simulation of your model also benefits from frame-based processing. In this case, you reduce the overhead of block-to-block communications by propagating frames of data rather than individual samples. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-7 3 Data and Signal Management Inspect Sample and Frame Rates in Simulink Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Sample Rate and Frame Rate Concepts” on page 3-8 “Inspect Sample-Based Signals Using Probe Block” on page 3-9 “Inspect Frame-Based Signals Using Probe Block” on page 3-11 “Inspect Sample-Based Signals Using Color Coding” on page 3-13 “Inspect Frame-Based Signals Using Color Coding” on page 3-15 Sample Rate and Frame Rate Concepts Sample rates and frame rates are important issues in most signal processing models. This is especially true with systems that incorporate rate conversions. Fortunately, in most cases when you build a Simulink model, you only need to set sample rates for the source blocks. Simulink automatically computes the appropriate sample rates for the blocks that are connected to the source blocks. Nevertheless, it is important to become familiar with the sample rate and frame rate concepts as they apply to Simulink models. The input frame period (Tfi) of a frame-based signal is the time interval between consecutive vector or matrix inputs to a block. Similarly, the output frame period (Tfo) is the time interval at which the block updates the frame-based vector or matrix value at the output port. In contrast, the sample period, Ts, is the time interval between individual samples in a frame, this value is shorter than the frame period when the frame size is greater than 1. The sample period of a frame-based signal is the quotient of the frame period and the frame size, M: Ts = Tf / M 3-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspect Sample and Frame Rates in Simulink More specifically, the sample periods of inputs (Tsi) and outputs (Tso) are related to their respective frame periods by Tsi = Tfi / M i Tso = Tfo / M o where Mi and Mo are the input and output frame sizes, respectively. The illustration below shows a single-channel, frame-based signal with a frame size (Mi) of 4 and a frame period (Tfi) of 1. The sample period, Tsi, is therefore 1/4, or 0.25 second. The frame rate of a signal is the reciprocal of the frame period. For instance, the input frame rate would be 1 / Tfi . Similarly, the output frame rate would be 1 / Tfo . The sample rate of a signal is the reciprocal of the sample period. For instance, the sample rate would be 1 / Ts . In most cases, the sequence sample period Tsi is most important, while the frame rate is simply a consequence of the frame size that you choose for the signal. For a sequence with a given sample period, a larger frame size corresponds to a slower frame rate, and vice versa. Inspect Sample-Based Signals Using Probe Block You can use the Probe block to display the sample period of a sample-based signal. For sample-based signals, the Probe block displays the label Ts, the sample period of the sequence, followed by a two-element vector. The left element is the period of the signal being measured. The right element is the signal's sample time offset, which is usually 0. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-9 3 Data and Signal Management Note Simulink offers the ability to shift the sample time of a signal by an arbitrary value, which is equivalent to shifting the signal's phase by a fractional sample period. However, sample-time offsets are rarely used in signal processing systems, and DSP System Toolbox blocks do not support them. In this example, you use the Probe block to display the sample period of a sample-based signal: 1 At the MATLAB command prompt, type ex_probe_tut1. The Probe Example 1 model opens. 2 Run the model. The figure below illustrates how the Probe blocks display the sample period of the signal before and after each upsample operation. 3-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspect Sample and Frame Rates in Simulink As displayed by the Probe blocks, the output from the Signal From Workspace block is a sample-based signal with a sample period of 1 second. The output from the first Upsample block has a sample period of 0.5 second, and the output from the second Upsample block has a sample period of 0.25 second. Inspect Frame-Based Signals Using Probe Block You can use the Probe block to display the frame period of a frame-based signal. For frame-based signals, the block displays the label Tf, the frame period of the sequence, followed by a two-element vector. The left element is the period of the signal being measured. The right element is the signal's sample time offset, which is usually 0. Note Simulink offers the ability to shift a signal's sample times by an arbitrary value, which is equivalent to shifting the signal's phase by a fractional sample period. However, sample-time offsets are rarely used in signal processing systems, and DSP System Toolbox blocks do not support them. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-11 3 Data and Signal Management In this example, you use the Probe block to display the frame period of a frame-based signal: 1 At the MATLAB command prompt, type ex_probe_tut2. The Probe Example 2 model opens. 2 Run the model. The figure below illustrates how the Probe blocks display the frame period of the signal before and after each upsample operation. 3-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspect Sample and Frame Rates in Simulink As displayed by the Probe blocks, the output from the Signal From Workspace block is a frame-based signal with a frame period of 16 seconds. The output from the first Upsample block has a frame period of 8 seconds, and the output from the second Upsample block has a sample period of 4 seconds. Note that the sample rate conversion is implemented through a change in the frame period rather than the frame size. Inspect Sample-Based Signals Using Color Coding In the following example, you use sample time color coding to view the sample rate of a sample-based signal: 1 At the MATLAB command prompt, type ex_color_tut1. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-13 3 Data and Signal Management The Sample Time Color Example 1 model opens. 2 From the Display menu, point to Sample Time, and select Colors. This selection turns on sample time color coding. Simulink now assigns each sample rate a different color. 3 Run the model. The model should now look similar to the following figure: 3-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspect Sample and Frame Rates in Simulink Every sample-based signal in this model has a different sample rate. Therefore, each signal is assigned a different color. For more information about sample time color coding, see “View Sample Time Information” in the Simulink documentation. Inspect Frame-Based Signals Using Color Coding In this example, you use sample time color coding to view the frame rate of a frame-based signal: 1 At the MATLAB command prompt, type ex_color_tut2. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-15 3 Data and Signal Management The Sample Time Color Example 2 model opens. 2 To turn on sample time color coding, from the Display menu, point to Sample Time, and select Colors. Simulink now assigns each frame rate a different color. 3 Run the model. The model should now look similar to the following figure: 3-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Inspect Sample and Frame Rates in Simulink Because the Rate options parameter in the Upsample blocks is set to Allow multirate processing, each Upsample block changes the frame rate. Therefore, each frame-based signal in the model is assigned a different color. 4 Double-click on each Upsample block and change the Rate options parameter to Enforce single-rate processing. 5 Run the model. Every signal is coded with the same color. Therefore, every signal in the model now has the same frame rate. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-17 3 Data and Signal Management For more information about sample time color coding, see “View Sample Time Information” in the Simulink documentation. 3-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink Convert Sample and Frame Rates in Simulink Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Rate Conversion Blocks” on page 3-19 “Rate Conversion by Frame-Rate Adjustment” on page 3-20 “Rate Conversion by Frame-Size Adjustment” on page 3-24 “Avoid Unintended Rate Conversion” on page 3-28 “Frame Rebuffering Blocks” on page 3-34 “Buffer Signals by Preserving the Sample Period” on page 3-36 “Buffer Signals by Altering the Sample Period” on page 3-39 Rate Conversion Blocks There are two common types of operations that impact the frame and sample rates of a signal: direct rate conversion and frame rebuffering. Direct rate conversions, such as upsampling and downsampling, can be implemented by altering either the frame rate or the frame size of a signal. Frame rebuffering, which is used alter the frame size of a signal in order to improve simulation throughput, usually changes either the sample rate or frame rate of the signal as well. The following table lists the principal rate conversion blocks in DSP System Toolbox software. Blocks marked with an asterisk (*) offer the option of changing the rate by either adjusting the frame size or frame rate. Block Library Downsample * Signal Operations Dyadic Analysis Filter Bank Filtering / Multirate Filters Dyadic Synthesis Filter Bank Filtering / Multirate Filters www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-19 3 Data and Signal Management Block Library FIR Decimation * Filtering / Multirate Filters FIR Interpolation * Filtering / Multirate Filters FIR Rate Conversion Filtering / Multirate Filters Repeat * Signal Operations Upsample * Signal Operations Direct Rate Conversion Rate conversion blocks accept an input signal at one sample rate, and propagate the same signal at a new sample rate. Several of these blocks contain a Rate options parameter offering two options for multirate versus single-rate processing: • Enforce single-rate processing: When you select this option, the block maintains the input sample rate. • Allow multirate processing: When you select this option, the block downsamples the signal such that the output sample rate is K times slower than the input sample rate. Note: When a Simulink model contains signals with various frame rates, the model is called multirate. You can find a discussion of multirate models in “Excess Algorithmic Delay (Tasking Latency)” on page 3-67. Also see “Scheduling ” in the Simulink Coder documentation. Rate Conversion by Frame-Rate Adjustment One way to change the sample rate of a signal, 1/Tso, is to change the output frame rate (Tfo ≠ Tfi), while keeping the frame size constant (Mo = Mi). Note that the sample rate of a signal is defined as 1/Tso = Mo/Tfo: 1 At the MATLAB command prompt, type ex_downsample_tut1. The Downsample Example T1 model opens. 3-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink 2 From the Display menu, point to Signals & Ports, and select Signal Dimensions. When you run the model, the dimensions of the signals appear next to the lines connecting the blocks. 3 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 4 Set the block parameters as follows: • Sample time = 0.125 • Samples per frame = 8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-21 3 Data and Signal Management Based on these parameters, the Signal From Workspace block outputs a frame-based signal with a sample period of 0.125 second and a frame size of 8. 5 Save these parameters and close the dialog box by clicking OK. 6 Double-click the Downsample block. The Function Block Parameters: Downsample dialog box opens. 7 Set the Rate options parameter to Allow multirate processing, and then click OK. The Downsample block is configured to downsample the signal by changing the frame rate rather than the frame size. 8 Run the model. After the simulation, the model should look similar to the following figure. 3-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink Because Tfi = M i ¥ Tsi , the input frame period, Tfi , is Tfi = 8 ¥ 0.125 = 1 second. This value is displayed by the first Probe block. Therefore the input frame rate, 1 / Tfi , is also 1 second. The second Probe block in the model verifies that the output from the Downsample block has a frame period, Tfo , of 2 seconds, twice the frame period of the input. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-23 3 Data and Signal Management However, because the frame rate of the output, 1 Tfo , is 0.5 second, the Downsample block actually downsampled the original signal to half its original rate. As a result, the output sample period, Tso = Tfo / M o , is doubled to 0.25 second without any change to the frame size. The signal dimensions in the model confirm that the frame size did not change. Rate Conversion by Frame-Size Adjustment One way to change the sample rate of a signal is by changing the frame size (that is Mo ≠ Mi), but keep the frame rate constant (Tfo = Tfi). Note that the sample rate of a signal is defined as 1/Tso = Mo/Tfo: 1 At the MATLAB command prompt, type ex_downsample_tut2. The Downsample Example T2 model opens. 3-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink 2 From the Display menu, point to Signals & Ports, and select Signal Dimensions. When you run the model, the dimensions of the signals appear next to the lines connecting the blocks. 3 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 4 Set the block parameters as follows: • Sample time = 0.125 • Samples per frame = 8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-25 3 Data and Signal Management Based on these parameters, the Signal From Workspace block outputs a frame-based signal with a sample period of 0.125 second and a frame size of 8. 5 Save these parameters and close the dialog box by clicking OK. 6 Double-click the Downsample block. The Function Block Parameters: Downsample dialog box opens. 7 Set the Rate options parameter to Enforce single-rate processing, and then click OK. The Downsample block is configured to downsample the signal by changing the frame size rather than the frame rate. 8 Run the model. After the simulation, the model should look similar to the following figure. 3-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink Because Tfi = M i ¥ Tsi , the input frame period, Tfi , is Tfi = 8 ¥ 0.125 = 1 second. This value is displayed by the first Probe block. Therefore the input frame rate, 1 / Tfi , is also 1 second. The Downsample block downsampled the input signal to half its original frame size. The signal dimensions of the output of the Downsample block confirm that the www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-27 3 Data and Signal Management downsampled output has a frame size of 4, half the frame size of the input. As a result, the sample period of the output, Tso = Tfo / M o , now has a sample period of 0.25 second. This process occurred without any change to the frame rate ( Tfi = Tfo ). Avoid Unintended Rate Conversion It is important to be aware of where rate conversions occur in a model. In a few cases, unintentional rate conversions can produce misleading results: 1 At the MATLAB command prompt, type ex_vectorscope_tut1. The Vector Scope Example model opens. 2 Double-click the upper Sine Wave block. The Source Block Parameters: Sine Wave dialog box opens. 3 Set the block parameters as follows: • Frequency (Hz) = 1 • Sample time = 0.1 • Samples per frame = 128 Based on the Sample time and the Samples per frame parameters, the Sine Wave outputs a sinusoid with a frame period of 128*0.1 or 12.8 seconds. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the lower Sine Wave block. 6 Set the block parameters as follows, and then click OK: • Frequency (Hz) = 2 • Sample time = 0.1 • Samples per frame = 128 Based on the Sample time and the Samples per frame parameters, the Sine Wave outputs a sinusoid with a frame period of 128*0.1 or 12.8 seconds. 3-28 7 Double-click the Magnitude FFT block. The Function Block Parameters: Magnitude FFT dialog box opens. 8 Select the Inherit FFT length from input dimensions check box, and then click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink This setting instructs the block to use the input frame size (128) as the FFT length (which is also the output size). 9 Double-click the Vector Scope block. The Sink Block Parameters: Vector Scope dialog box opens. 10 Set the block parameters as follows, and then click OK: • Click the Scope Properties tab. • Input domain = Frequency • Click the Axis Properties tab. • Minimum Y-limit = -10 • Maximum Y-limit = 40 11 Run the model. The model should now look similar to the following figure. Note that the signal leaving the Magnitude FFT block is 128-by-1. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-29 3 Data and Signal Management The Vector Scope window displays the magnitude FFT of a signal composed of two sine waves, with frequencies of 1 Hz and 2 Hz. 3-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink The Vector Scope block uses the input frame size (128) and period (12.8) to deduce the original signal's sample period (0.1), which allows it to correctly display the peaks at 1 Hz and 2 Hz. 12 Double-click the Magnitude FFT block. The Function Block Parameters: Magnitude FFT dialog box opens. 13 Set the block parameters as follows: • Clear the Inherit FFT length from input dimensions check box. • Set the FFT length parameter to 256. Based on these parameters, the Magnitude FFT block zero-pads the length-128 input frame to a length of 256 before performing the FFT. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-31 3 Data and Signal Management 14 Run the model. The model should now look similar to the following figure. Note that the signal leaving the Magnitude FFT block is 256-by-1. The Vector Scope window displays the magnitude FFT of a signal composed of two sine waves, with frequencies of 2 Hz and 4 Hz. 3-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink In this case, based on the input frame size (256) and frame period (12.8), the Vector Scope block incorrectly calculates the original signal's sample period to be (12.8/256) or 0.05 second. As a result, the spectral peaks appear incorrectly at 2 Hz and 4 Hz rather than 1 Hz and 2 Hz. The source of the error described above is unintended rate conversion. The zeropad operation performed by the Magnitude FFT block halves the sample period of the sequence by appending 128 zeros to each frame. To calculate the spectral peaks correctly, the Vector Scope block needs to know the sample period of the original signal. 15 To correct for the unintended rate conversion, double-click the Vector Scope block. 16 Set the block parameters as follows: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-33 3 Data and Signal Management • Click the Axis Properties tab. • Clear the Inherit sample time from input check box. • Set the Sample time of original time series parameter to the actual sample period of 0.1. 17 Run the model. The Vector Scope block now accurately plots the spectral peaks at 1 Hz and 2 Hz. In general, when you zero-pad or overlap buffers, you are changing the sample period of the signal. If you keep this in mind, you can anticipate and correct problems such as unintended rate conversion. Frame Rebuffering Blocks There are two common types of operations that impact the frame and sample rates of a signal: direct rate conversion and frame rebuffering. Direct rate conversions, such as upsampling and downsampling, can be implemented by altering either the frame rate or the frame size of a signal. Frame rebuffering, which is used alter the frame size of a signal in order to improve simulation throughput, usually changes either the sample rate or frame rate of the signal as well. Sometimes you might need to rebuffer a signal to a new frame size at some point in a model. For example, your data acquisition hardware may internally buffer the sampled signal to a frame size that is not optimal for the signal processing algorithm in the model. In this case, you would want to rebuffer the signal to a frame size more appropriate for the intended operations without introducing any change to the data or sample rate. The following table lists the principal DSP System Toolbox buffering blocks. Block Library Buffer Signal Management/ Buffers Delay Line Signal Management/ Buffers Unbuffer Signal Management/ Buffers Variable Selector Signal Management/ Indexing Blocks for Frame Rebuffering with Preservation of the Signal Buffering operations provide another mechanism for rate changes in signal processing models. The purpose of many buffering operations is to adjust the frame size of the 3-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink signal, M, without altering the signal's sample rate Ts. This usually results in a change to the signal's frame rate, Tf, according to the following equation: Tf = MTs However, the equation above is only true if no samples are added or deleted from the original signal. Therefore, the equation above does not apply to buffering operations that generate overlapping frames, that only partially unbuffer frames, or that alter the data sequence by adding or deleting samples. There are two blocks in the Buffers library that can be used to change a signal's frame size without altering the signal itself: • Buffer — redistributes signal samples to a larger or smaller frame size • Unbuffer — unbuffers a frame-based signal to a sample-based signal (frame size = 1) The Buffer block preserves the signal's data and sample period only when its Buffer overlap parameter is set to 0. The output frame period, Tfo, is Tfo = M o Tfi Mi where Tfi is the input frame period, Mi is the input frame size, and Mo is the output frame size specified by the Output buffer size (per channel) parameter. The Unbuffer block unbuffers a frame-based signal to its sample-based equivalent, and always preserves the signal's data and sample period Tso = Tfi / M i where Tfi and Mi are the period and size, respectively, of the frame-based input. Both the Buffer and Unbuffer blocks preserve the sample period of the sequence in the conversion (Tso = Tsi). Blocks for Frame Rebuffering with Alteration of the Signal Some forms of buffering alter the signal's data or sample period in addition to adjusting the frame size. This type of buffering is desirable when you want to create sliding windows by overlapping consecutive frames of a signal, or select a subset of samples from each input frame for processing. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-35 3 Data and Signal Management The blocks that alter a signal while adjusting its frame size are listed below. In this list, Tsi is the input sequence sample period, and Tfi and Tfo are the input and output frame periods, respectively: • The Buffer block adds duplicate samples to a sequence when the Buffer overlap parameter, L, is set to a nonzero value. The output frame period is related to the input sample period by Tfo = ( M o - L) Tsi where Mo is the output frame size specified by the Output buffer size (per channel) parameter. As a result, the new output sample period is Tso = ( M o - L) Tsi Mo • The Delay Line block adds duplicate samples to the sequence when the Delay line size parameter, Mo, is greater than 1. The output and input frame periods are the same, Tfo = Tfi = Tsi, and the new output sample period is Tso = Tsi Mo • The Variable Selector block can remove, add, and/or rearrange samples in the input frame when Select is set to Rows. The output and input frame periods are the same, Tfo = Tfi, and the new output sample period is Tso = M i Tsi Mo where Mo is the length of the block's output, determined by the Elements vector. In all of these cases, the sample period of the output sequence is not equal to the sample period of the input sequence. Buffer Signals by Preserving the Sample Period In the following example, a signal with a sample period of 0.125 second is rebuffered from a frame size of 8 to a frame size of 16. This rebuffering process doubles the 3-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink frame period from 1 to 2 seconds, but does not change the sample period of the signal (Tso = Tsi = 0.125). The process also does not add or delete samples from the original signal: 1 At the MATLAB command prompt, type ex_buffer_tut1. The Buffer Example T1 model opens. 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the parameters as follows: • Signal = 1:1000 • Sample time = 0.125 • Samples per frame = 8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-37 3 Data and Signal Management • Form output after final data value = Setting to zero Based on these parameters, the Signal from Workspace block outputs a framebased signal with a sample period of 0.125 second. Each output frame contains eight samples. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Buffer block. The Function Block Parameters: Buffer dialog box opens. 6 Set the parameters as follows, and then click OK: • Output buffer size (per channel) = 16 • Buffer overlap = 0 • Initial conditions = 0 Based on these parameters, the Buffer block rebuffers the signal from a frame size of 8 to a frame size of 16. 7 Run the model. The following figure shows the model after simulation. 3-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink Note that the input to the Buffer block has a frame size of 8 and the output of the block has a frame size of 16. As shown by the Probe blocks, the rebuffering process doubles the frame period from 1 to 2 seconds. Buffer Signals by Altering the Sample Period Some forms of buffering alter the signal's data or sample period in addition to adjusting the frame size. In the following example, a signal with a sample period of 0.125 second is rebuffered from a frame size of 8 to a frame size of 16 with a buffer overlap of 4: 1 At the MATLAB command prompt, type ex_buffer_tut2. The Buffer Example T2 model opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-39 3 Data and Signal Management 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the parameters as follows: • Signal = 1:1000 • Sample time = 0.125 • Samples per frame = 8 • Form output after final data value = Setting to zero Based on these parameters, the Signal from Workspace block outputs a framebased signal with a sample period of 0.125 second. Each output frame contains eight samples. 4 3-40 Save these parameters and close the dialog box by clicking OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Convert Sample and Frame Rates in Simulink 5 Double-click the Buffer block. The Function Block Parameters: Buffer dialog box opens. 6 Set the parameters as follows, and then click OK: • Output buffer size (per channel) = 16 • Buffer overlap = 4 • Initial conditions = 0 Based on these parameters, the Buffer block rebuffers the signal from a frame size of 8 to a frame size of 16. Also, after the initial output, the first four samples of each output frame are made up of the last four samples from the previous output frame. 7 Run the model. The following figure shows the model after the simulation has stopped. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-41 3 Data and Signal Management Note that the input to the Buffer block has a frame size of 8 and the output of the block has a frame size of 16. The relation for the output frame period for the Buffer block is Tfo = ( M o - L) Tsi Tfo is (16-4)*0.125, or 1.5 seconds, as confirmed by the second Probe block. The sample period of the signal at the output of the Buffer block is no longer 0.125 second. It is now Tso = Tfo / M o = 1.5 / 16 = 0 .0938 second. Thus, both the signal's data and the signal's sample period have been altered by the buffering operation. 3-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing Buffering and Frame-Based Processing Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Frame Status” on page 3-43 “Buffer Sample-Based Signals into Frame-Based Signals” on page 3-43 “Buffer Sample-Based Signals into Frame-Based Signals with Overlap” on page 3-46 “Buffer Frame-Based Signals into Other Frame-Based Signals” on page 3-51 “Buffer Delay and Initial Conditions” on page 3-54 “Unbuffer Frame-Based Signals into Sample-Based Signals” on page 3-54 Frame Status The frame status of a signal refers to whether the signal is sample based or frame based. In a Simulink model, the frame status is symbolized by a single line ,→, for a sample-based signal and a double line, ⇒ for a frame-based signal. One way to convert a sample-based signal to a frame-based signal is by using the Buffer block. You can convert a frame-based signal to a sample-based signal using the Unbuffer block. To change the frame status of a signal without performing a buffering operation, use the Frame Conversion block in the Signal Attributes library. Buffer Sample-Based Signals into Frame-Based Signals Multichannel sample-based and frame-based signals can be buffered into multichannel frame-based signals using the Buffer block. The following figure is a graphical representation of a sample-based signal being converted into a frame-based signal by the Buffer block. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-43 3 Data and Signal Management In the following example, a two-channel sample-based signal is buffered into a twochannel frame-based signal using a Buffer block: 1 At the MATLAB command prompt, type ex_buffer_tut. The Buffer Example model opens. 3-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the parameters as follows: • Signal = [1:10;-1:-1:-10]' • Sample time = 1 • Samples per frame = 1 • Form output after final data value = Setting to zero Based on these parameters, the Signal from Workspace block outputs a samplebased signal with a sample period of 1 second. Because you set the Samples per frame parameter setting to 1, the Signal From Workspace block outputs one twochannel sample at each sample time. 4 Save these parameters and close the dialog box by clicking OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-45 3 Data and Signal Management 5 Double-click the Buffer block. The Function Block Parameters: Buffer dialog box opens. 6 Set the parameters as follows: • Output buffer size (per channel) = 4 • Buffer overlap = 0 • Initial conditions = 0 Because you set the Output buffer size parameter to 4, the Buffer block outputs a frame-based signal with frame size 4. 7 Run the model. Note that the input to the Buffer block is sample based (represented as a single line) while the output is frame-based (represented by a double line). The figure below is a graphical interpretation of the model behavior during simulation. [4 -4] [3 -3] [2 -2] [1 -1] t=3 t=2 t=1 t=0 Four consecutive samples from a 2-channel sample-based signal 1 2 3 4 -1 -2 -3 -4 2-channel frame-based signal Note: Alternatively, you can set the Samples per frame parameter of the Signal From Workspace block to 4 and create the same frame-based signal shown above without using a Buffer block. The Signal From Workspace block performs the buffering internally, in order to output a two-channel frame-based signal. Buffer Sample-Based Signals into Frame-Based Signals with Overlap In some cases it is useful to work with data that represents overlapping sections of an original sample-based or frame-based signal. For example, in estimating the power spectrum of a signal, it is often desirable to compute the FFT of overlapping sections of 3-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing data. Overlapping buffers are also needed in computing statistics on a sliding window, or for adaptive filtering. The Buffer overlap parameter of the Buffer block specifies the number of overlap points, L. In the overlap case (L > 0), the frame period for the output is (Mo-L)*Tsi, where Tsi is the input sample period and Mo is the Buffer size. Note: Set the Buffer overlap parameter to a negative value to achieve output frame rates slower than in the nonoverlapping case. The output frame period is still Tsi*(Mo-L), but now with L < 0. Only the Mo newest inputs are included in the output buffers. The previous L inputs are discarded. In the following example, a four-channel sample-based signal with sample period 1 is buffered to a frame-based signal with frame size 3 and frame period 2. Because of the buffer overlap, the input sample period is not conserved, and the output sample period is 2/3: 1 At the MATLAB command prompt, type ex_buffer_tut3. The Buffer Example T3 model opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-47 3 Data and Signal Management Also, the variable sp_examples_src is loaded into the MATLAB workspace. This variable is defined as follows: sp_examples_src=[1 1 5 -1; 2 1 5 -2; 3 0 5 -3; 4 0 5 -4; 5 1 5 -5; 6 1 5 -6]; 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the block parameters as follows: • Signal = sp_examples_src • Sample time = 1 • Samples per frame = 1 3-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing • Form output after final data value by = Setting to zero Based on these parameters, the Signal from Workspace block outputs a samplebased signal with a sample period of 1 second. Because you set the Samples per frame parameter setting to 1, the Signal From Workspace block outputs one fourchannel sample at each sample time. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Buffer block. The Function Block Parameters: Buffer dialog box opens. 6 Set the block parameters as follows, and then click OK: • Output buffer size (per channel) = 3 • Buffer overlap = 1 • Initial conditions = 0 Because you set the Output buffer size parameter to 3, the Buffer block outputs a frame-based signal with frame size 3. Also, because you set the Buffer overlap parameter to 1, the last sample from the previous output frame is the first sample in the next output frame. 7 Run the model. Note that the input to the Buffer block is sample based (represented as a single line) while the output is frame based (represented by a double line). The following figure is a graphical interpretation of the model's behavior during simulation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-49 3 Data and Signal Management 8 At the MATLAB command prompt, type sp_examples_yout. The following is displayed in the MATLAB Command Window. sp_examples_yout = 0 0 0 0 1 2 2 3 4 4 5 6 6 0 0 0 0 0 3-50 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 5 5 5 5 5 5 5 5 5 0 0 0 0 0 0 0 0 0 -1 -2 -2 -3 -4 -4 -5 -6 -6 0 0 0 0 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing Notice that the inputs do not begin appearing at the output until the fifth row, the second row of the second frame. This is due to the block's latency. See “Excess Algorithmic Delay (Tasking Latency)” on page 3-67 for general information about algorithmic delay. For instructions on how to calculate buffering delay, see “Buffer Delay and Initial Conditions” on page 3-54. Buffer Frame-Based Signals into Other Frame-Based Signals In the following example, a two-channel frame-based signal with frame size 4 is rebuffered to a frame-based signal with frame size 3 and frame period 2. Because of the overlap, the input sample period is not conserved, and the output sample period is 2/3: 1 At the MATLAB command prompt, type ex_buffer_tut4. The Buffer Example T4 model opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-51 3 Data and Signal Management Also, the variable sp_examples_src is loaded into the MATLAB workspace. This variable is defined as sp_examples_src = [1 1; 2 1; 3 0; 4 0; 5 1; 6 1; 7 0; 8 0] 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the block parameters as follows: • Signal = sp_examples_src • Sample time = 1 3-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing • Samples per frame = 4 Based on these parameters, the Signal From Workspace block outputs a twochannel, frame-based signal with a sample period of 1 second and a frame size of 4. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Buffer block. The Function Block Parameters: Buffer dialog box opens. 6 Set the block parameters as follows, and then click OK: • Output buffer size (per channel) = 3 • Buffer overlap = 1 • Initial conditions = 0 Based on these parameters, the Buffer block outputs a two-channel, frame-based signal with a frame size of 3. 7 Run the model. The following figure is a graphical representation of the model's behavior during simulation. Note that the inputs do not begin appearing at the output until the last row of the third output matrix. This is due to the block's latency. See “Excess Algorithmic Delay (Tasking Latency)” on page 3-67 for general information about algorithmic delay. For instructions on how to calculate buffering delay, and see “Buffer Delay and Initial Conditions” on page 3-54. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-53 3 Data and Signal Management Buffer Delay and Initial Conditions In the examples “Buffer Sample-Based Signals into Frame-Based Signals with Overlap” on page 3-46 and “Buffer Frame-Based Signals into Other Frame-Based Signals” on page 3-51, the input signal is delayed by a certain number of samples. The initial output samples correspond to the value specified for the Initial condition parameter. The initial condition is zero in both examples mentioned above. Under most conditions, the Buffer and Unbuffer blocks have some amount of delay or latency. This latency depends on both the block parameter settings and the Simulink tasking mode. You can use the rebuffer_delay function to determine the length of the block's latency for any combination of frame size and overlap. The syntax rebuffer_delay(f,n,v) returns the delay, in samples, introduced by the buffering and unbuffering blocks during multitasking operations, where f is the input frame size, n is the Output buffer size parameter setting, and v is the Buffer overlap parameter setting. For example, you can calculate the delay for the model discussed in the “Buffer FrameBased Signals into Other Frame-Based Signals” on page 3-51 using the following command at the MATLAB command line: d = rebuffer_delay(4,3,1) d = 8 This result agrees with the block's output in that example. Notice that this model was simulated in Simulink multitasking mode. For more information about delay, see “Excess Algorithmic Delay (Tasking Latency)” on page 3-67. For delay information about a specific block, see the “Latency” section of the block reference page. For more information about the rebuffer_delay function, see rebuffer_delay. Unbuffer Frame-Based Signals into Sample-Based Signals You can unbuffer multichannel frame-based signals into multichannel sample-based signals using the Unbuffer block. The Unbuffer block performs the inverse operation of the Buffer block's “sample-based to frame-based” buffering process, and generates an Nchannel sample-based output from an N-channel frame-based input. The first row in each input matrix is always the first sample-based output. 3-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing The following figure is a graphical representation of this process. The sample period of the sample-based output, Tso, is related to the input frame period, Tfi, by the input frame size, Mi. Tso = Tfi / M i The Unbuffer block always preserves the signal's sample period (Tso = Tsi). See “Convert Sample and Frame Rates in Simulink” on page 3-19 for more information about rate conversions. In the following example, a two-channel frame-based signal is unbuffered into a twochannel sample-based signal: 1 At the MATLAB command prompt, type ex_unbuffer_tut. The Unbuffer Example model opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-55 3 Data and Signal Management 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the block parameters as follows: • Signal = [1:10;-1:-1:-10]' • Sample time = 1 • Samples per frame = 4 • Form output after final data value by = Setting to zero Based on these parameters, the Signal From Workspace block outputs a twochannel, frame based-signal with frame size 4. 3-56 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Unbuffer block. The Function Block Parameters: Unbuffer dialog box opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Buffering and Frame-Based Processing 6 Set the Initial conditions parameter to 0, and then click OK. The Unbuffer block unbuffers the frame-based signal into a two-channel samplebased signal. 7 Run the model. The following figures is a graphical representation of what happens during the model simulation. 1 2 3 4 -1 -2 -3 -4 2-channel frame-based signal [4 -4] [3 -3] [2 -2] [1 -1] t=7 t=6 t=5 t=4 Four consecutive samples from a 2-channel sample-based signal Note: The Unbuffer block generates initial conditions not shown in the figure below with the value specified by the Initial conditions parameter. See the Unbuffer reference page for information about the number of initial conditions that appear in the output. 8 At the MATLAB command prompt, type sp_examples_yout. The following is a portion of the output. sp_examples_yout(:,:,1) = 0 0 sp_examples_yout(:,:,2) = 0 0 sp_examples_yout(:,:,3) = 0 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-57 3 Data and Signal Management sp_examples_yout(:,:,4) = 0 0 sp_examples_yout(:,:,5) = 1 -1 sp_examples_yout(:,:,6) = 2 -2 sp_examples_yout(:,:,7) = 3 -3 The Unbuffer block unbuffers the frame-based signal into a two-channel, samplebased signal. Each page of the output matrix represents a different sample time. 3-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency Delay and Latency Note: Starting in R2010b, many DSP System Toolbox blocks received a new parameter to control whether they perform sample- or frame-based processing. The following content has not been updated to reflect this change. For more information, see the “Frame-Based Processing” section of the Release Notes. In this section... “Computational Delay” on page 3-59 “Algorithmic Delay” on page 3-60 “Zero Algorithmic Delay” on page 3-61 “Basic Algorithmic Delay” on page 3-64 “Excess Algorithmic Delay (Tasking Latency)” on page 3-67 “Predict Tasking Latency” on page 3-69 Computational Delay The computational delay of a block or subsystem is related to the number of operations involved in executing that block or subsystem. For example, an FFT block operating on a 256-sample input requires Simulink software to perform a certain number of multiplications for each input frame. The actual amount of time that these operations consume depends heavily on the performance of both the computer hardware and underlying software layers, such as the MATLAB environment and the operating system. Therefore, computational delay for a particular model can vary from one computer platform to another. The simulation time represented on a model's status bar, which can be accessed via the Simulink Digital Clock block, does not provide any information about computational delay. For example, according to the Simulink timer, the FFT mentioned above executes instantaneously, with no delay whatsoever. An input to the FFT block at simulation time t=25.0 is processed and output at simulation time t=25.0, regardless of the number of operations performed by the FFT algorithm. The Simulink timer reflects only algorithmic delay, not computational delay. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-59 3 Data and Signal Management Reduce Computational Delay There are a number of ways to reduce computational delay without actually running the simulation on faster hardware. To begin with, you should familiarize yourself with “Manual Performance Optimization” in the Simulink documentation, which describes some basic strategies. The following information discusses several options for improving performance. A first step in improving performance is to analyze your model, and eliminate or simplify elements that are adding excessively to the computational load. Such elements might include scope displays and data logging blocks that you had put in place for debugging purposes and no longer require. In addition to these model-specific adjustments, there are a number of more general steps you can take to improve the performance of any model: • Use frame-based processing wherever possible. It is advantageous for the entire model to be frame based. See “Benefits of Frame-Based Processing” for more information. • Use the dspstartup file to tailor Simulink for signal processing models, or manually make the adjustments described in “Settings in dspstartup.m” in the DSP System Toolbox Getting Started Guide. • Turn off the Simulink status bar by deselecting the Status bar option in the View menu. Simulation speed will improve, but the time indicator will not be visible. • Run your simulation from the MATLAB command line by typing sim(gcs) This method of starting a simulation can greatly increase the simulation speed, but also has several limitations: • You cannot interact with the simulation (to tune parameters, for instance). • You must press Ctrl+C to stop the simulation, or specify start and stop times. • There are no graphics updates in M-file S-functions, which include blocks such as Vector Scope, etc. • Use Simulink Coder code generation software to generate generic real-time (GRT) code targeted to your host platform, and run the model using the generated executable file. See the Simulink Coder documentation for more information. Algorithmic Delay 3-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency Algorithmic delay is delay that is intrinsic to the algorithm of a block or subsystem and is independent of CPU speed. In this guide, the algorithmic delay of a block is referred to simply as the block's delay. It is generally expressed in terms of the number of samples by which a block's output lags behind the corresponding input. This delay is directly related to the time elapsed on the Simulink timer during that block's execution. The algorithmic delay of a particular block may depend on both the block parameter settings and the general Simulink settings. To simplify matters, it is helpful to categorize a block's delay using the following categories: • “Zero Algorithmic Delay” on page 3-61 • “Basic Algorithmic Delay” on page 3-64 • “Excess Algorithmic Delay (Tasking Latency)” on page 3-67 The following topics explain the different categories of delay, and how the simulation and parameter settings can affect the level of delay that a particular block experiences. Zero Algorithmic Delay The FFT block is an example of a component that has no algorithmic delay. The Simulink timer does not record any passage of time while the block computes the FFT of the input, and the transformed data is available at the output in the same time step that the input is received. There are many other blocks that have zero algorithmic delay, such as the blocks in the Matrices and Linear Algebra libraries. Each of those blocks processes its input and generates its output in a single time step. The Normalization block is an example of a block with zero algorithmic delay: 1 At the MATLAB command prompt, type ex_normalization_tut. The Normalization Example T1 model opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-61 3 Data and Signal Management 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the block parameters as follows: • Signal = 1:100 • Sample time = 1/4 • Samples per frame = 4 3-62 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Frame Conversion block. The Function Block Parameters: Frame Conversion dialog box opens. 6 Set the Sampling mode of output signal parameter to Sample based, and then click OK. 7 Run the model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency The model prepends the current value of the Simulink timer output from the Digital Clock block to each output frame. The Frame Conversion block converts the framebased signal to a sample-based signal so that the output in the MATLAB Command Window is more easily readable. The Signal From Workspace block generates a new frame containing four samples once every second (Tfo = π*4). The first few output frames are: (t=0) (t=1) (t=2) (t=3) (t=4) 8 [ 1 2 3 4]' [ 5 6 7 8]' [ 9 10 11 12]' [13 14 15 16]' [17 18 19 20]' At the MATLAB command prompt, type squeeze(dsp_examples_yout)'. The normalized output, dsp_examples_yout, is converted to an easier-to-read matrix format. The result, ans, is shown in the following figure: ans = 0 1.0000 2.0000 3.0000 4.0000 5.0000 0.0333 0.0287 0.0202 0.0154 0.0124 0.0103 0.0667 0.0345 0.0224 0.0165 0.0131 0.0108 0.1000 0.0402 0.0247 0.0177 0.0138 0.0113 0.1333 0.0460 0.0269 0.0189 0.0146 0.0118 The first column of ans is the Simulink time provided by the Digital Clock block. You can see that the squared 2-norm of the first input, [1 2 3 4]' ./ sum([1 2 3 4]'.^2) appears in the first row of the output (at time t=0), the same time step that the input was received by the block. This indicates that the Normalization block has zero algorithmic delay. Zero Algorithmic Delay and Algebraic Loops When several blocks with zero algorithmic delay are connected in a feedback loop, Simulink may report an algebraic loop error and performance may generally suffer. You can prevent algebraic loops by injecting at least one sample of delay into a feedback www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-63 3 Data and Signal Management loop , for example, by including a Delay block with Delay > 0. For more information, see “Algebraic Loops” in the Simulink documentation. Basic Algorithmic Delay The Variable Integer Delay block is an example of a block with algorithmic delay. In the following example, you use this block to demonstrate this concept: 1 At the MATLAB command prompt, type ex_variableintegerdelay_tut. The Variable Integer Delay Example T1 opens. 2 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 3 Set the block parameters as follows: • Signal = 1:100 • Sample time = 1 3-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency • Samples per frame = 1 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Constant block. The Source Block Parameters: Constant dialog box opens. 6 Set the block parameters as follows: • Constant value = 3 • Interpret vector parameters as 1–D = Clear this check box • Sampling mode = Sample based • Sample time = 1 Click OK to save these parameters and close the dialog box. The input to the Delay port of the Variable Integer Delay block specifies the number of sample periods that should elapse before an input to the In port is released to the output. This value represents the block's algorithmic delay. In this example, since the input to the Delay port is 3, and the sample period at the In and Delay ports is 1, then the sample that arrives at the block's In port at time t=0 is released to the output at time t=3. 7 Double-click the Variable Integer Delay block. The Function Block Parameters: Variable Integer Delay dialog box opens. 8 Set the Initial conditions parameter to -1, and then click OK. 9 From the Display menu, point to Signals & Ports, and select Signal Dimensions and Wide Nonscalar Lines. 10 Run the model. The model should look similar to the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-65 3 Data and Signal Management 11 At the MATLAB command prompt, type dsp_examples_yout The output is shown below: dsp_examples_yout = 0 1 2 3 4 5 -1 -1 -1 1 2 3 The first column is the Simulink time provided by the Digital Clock block. The second column is the delayed input. As expected, the input to the block at t=0 is delayed three samples and appears as the fourth output sample, at t=3. You can also see that the first three outputs from the Variable Integer Delay block inherit the value of the block's Initial conditions parameter, -1. This period of time, from the 3-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency start of the simulation until the first input is propagated to the output, is sometimes called the initial delay of the block. Many DSP System Toolbox blocks have some degree of fixed or adjustable algorithmic delay. These include any blocks whose algorithms rely on delay or storage elements, such as filters or buffers. Often, but not always, such blocks provide an Initial conditions parameter that allows you to specify the output values generated by the block during the initial delay. In other cases, the initial conditions are internally set to 0. Consult the block reference pages for the delay characteristics of specific DSP System Toolbox blocks. Excess Algorithmic Delay (Tasking Latency) Under certain conditions, Simulink may force a block to delay inputs longer than is strictly required by the block's algorithm. This excess algorithmic delay is called tasking latency, because it arises from synchronization requirements of the Simulink tasking mode. A block's overall algorithmic delay is the sum of its basic delay and tasking latency. Algorithmic delay = Basic algorithmic delay + Tasking latency The tasking latency for a particular block may be dependent on the following block and model characteristics: • “Simulink Tasking Mode” on page 3-67 • “Block Rate Type” on page 3-68 • “Model Rate Type” on page 3-68 • “Block Sample Mode” on page 3-68 Simulink Tasking Mode Simulink has two tasking modes: • Single-tasking • Multitasking To select a mode, from the Simulation menu, select Model Configuration Parameters. In the Select pane, click Solver. From the Type list, select Fixed-step. From the Tasking mode for periodic sample times list, choose SingleTasking or MultiTasking. If, from the Tasking mode for periodic sample times list you www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-67 3 Data and Signal Management select Auto, the simulation runs in single-tasking mode if the model is single-rate, or multitasking mode if the model is multirate. Note: Many multirate blocks have reduced latency in the Simulink single-tasking mode. Check the “Latency” section of a multirate block's reference page for details. Also see “Scheduling ” in the Simulink Coder User's Guide. Block Rate Type A block is called single-rate when all of its input and output ports operate at the same frame rate. A block is called multirate when at least one input or output port has a different frame rate than the others. Many blocks are permanently single-rate. This means that all input and output ports always have the same frame rate. For other blocks, the block parameter settings determine whether the block is single-rate or multirate. Only multirate blocks are subject to tasking latency. Note: Simulink may report an algebraic loop error if it detects a feedback loop composed entirely of multirate blocks. To break such an algebraic loop, insert a single-rate block with nonzero delay, such as a Unit Delay block. See the Simulink documentation for more information about “Algebraic Loops”. Model Rate Type When all ports of all blocks in a model operate at a single frame rate, the model is called single-rate. When the model contains blocks with differing frame rates, or at least one multirate block, the model is called multirate. Note that Simulink prevents a single-rate model from running in multitasking mode by generating an error. Block Sample Mode Many blocks can operate in either sample-based or frame-based modes. In source blocks, the mode is usually determined by the Samples per frame parameter. If, for the Samples per frame parameter, you enter 1, the block operates in sample-based mode. If you enter a value greater than 1, the block operates in frame-based mode. In nonsource blocks, the sample mode is determined by the input signal. See the block reference pages for additional information about specific blocks. 3-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency Predict Tasking Latency The specific amount of tasking latency created by a particular combination of block parameter and simulation settings is discussed in the “Latency” section of a block's reference page. In this topic, you use the Upsample block's reference page to predict the tasking latency of a model: 1 At the MATLAB command prompt, type ex_upsample_tut1. The Upsample Example T1 model opens. 2 From the Simulation menu, select Model Configuration Parameters. 3 In the Solver pane, from the Type list, select Fixed-step. From the Solver list, select discrete (no continuous states). 4 From the Tasking mode for periodic sample times list, select MultiTasking, and then click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-69 3 Data and Signal Management Most multirate blocks experience tasking latency only in the Simulink multitasking mode. 5 Double-click the Signal From Workspace block. The Source Block Parameters: Signal From Workspace dialog box opens. 6 Set the block parameters as follows, and then click OK: • Signal = 1:100 • Sample time = 1/4 • Samples per frame = 4 • Form output after final data value by = Setting to zero 7 Double-click the Upsample block. The Function Block Parameters: Upsample dialog box opens. 8 Set the block parameters as follows, and then click OK: • Upsample factor, L = 4 • Sample offset (0 to L-1) = 0 • Input processing = Columns as channels (frame based) • Rate options = Allow multirate processing • Initial condition = -1 The Rate options parameter makes the model multirate, since the input and output frame rates will not be equal. 9 Double-click the Digital Clock block. The Source Block Parameters: Digital Clock dialog box opens. 10 Set the Sample time parameter to 0.25, and then click OK. This matches the sample period of the Upsample block's output. 11 Double-click the Frame Conversion block. The Function Block Parameters: Frame Conversion dialog box opens. 12 Set the Sampling mode of output signal parameter to Sample based, and then click OK. 13 Run the model. The model should now look similar to the following figure. 3-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency The model prepends the current value of the Simulink timer, from the Digital Clock block, to each output frame. The Frame Conversion block converts the frame-based signal into a sample-based signal so that the output in the MATLAB Command Window is easily readable. In the example, the Signal From Workspace block generates a new frame containing four samples once every second (Tfo = π*4). The first few output frames are: (t=0) (t=1) (t=2) (t=3) (t=4) [ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16] [17 18 19 20] The Upsample block upsamples the input by a factor of 4, inserting three zeros between each input sample. The change in rates is confirmed by the Probe blocks in the model, which show a decrease in the frame period from Tfi = 1 to Tfo = 0.25. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-71 3 Data and Signal Management 14 At the MATLAB command prompt, type squeeze(dsp_examples_yout)'. The output from the simulation is displayed in a matrix format. The first few samples of the result, ans, are: “Latency and Initial Conditions” in the Upsample block's reference page indicates that when Simulink is in multitasking mode, the first sample of the block's framebased input appears in the output as sample MiL+D+1, where Mi is the input frame size, L is the Upsample factor, and D is the Sample offset. This formula predicts that the first input in this example should appear as output sample 17 (that is, 4*4+0+1). The first column of the output is the Simulink time provided by the Digital Clock block. The four values to the right of each time are the values in the output frame at that time. You can see that the first sample in each of the first four output frames inherits the value of the Upsample block's Initial conditions parameter. As a result of the tasking latency, the first input value appears as the first sample of the 5th output frame (at t=1). This is sample 17. Now try running the model in single-tasking mode. 15 From the Simulation menu, select Model Configuration Parameters. 16 In the Solver pane, from the Type list, select Fixed-step. From the Solver list, select Discrete (no continuous states). 17 From the Tasking mode for periodic sample times list, select SingleTasking. 18 Run the model. The model now runs in single-tasking mode. 3-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Delay and Latency 19 At the MATLAB command prompt, type squeeze(dsp_examples_yout)'. The first few samples of the result, ans, are: “Latency and Initial Conditions” in the Upsample block's reference page indicates that the block has zero latency for all multirate operations in the Simulink singletasking mode. The first column of the output is the Simulink time provided by the Digital Clock block. The four values to the right of each time are the values in the output frame at that time. The first input value appears as the first sample of the first output frame (at t=0). This is the expected behavior for the zero-latency condition. For the particular parameter settings used in this example, running upsample_tut1 in single-tasking mode eliminates the 17-sample delay that is present when you run the model in multitasking mode. You have now successfully used the Upsample block's reference page to predict the tasking latency of a model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-73 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 3-74 4 Filter Analysis, Design, and Implementation • “Design a Filter in Fdesign — Process Overview” on page 4-2 • “Design a Filter in the Filterbuilder GUI” on page 4-10 • “Use FDATool with DSP System Toolbox Software” on page 4-14 • “Digital Frequency Transformations” on page 4-77 • “Digital Filter Design Block” on page 4-111 • “Filter Realization Wizard” on page 4-121 • “Digital Filter Implementations” on page 4-133 • “Analog Filter Design Block” on page 4-143 • “Removing High-Frequency Noise from an ECG Signal” on page 4-145 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4 Filter Analysis, Design, and Implementation Design a Filter in Fdesign — Process Overview Process Flow Diagram and Filter Design Methodology • “Exploring the Process Flow Diagram” on page 4-2 • “Select a Response” on page 4-4 • “Select a Specification” on page 4-4 • “Select an Algorithm” on page 4-6 • “Customize the Algorithm” on page 4-7 • “Design the Filter” on page 4-8 • “Design Analysis” on page 4-9 • “Realize or Apply the Filter to Input Data” on page 4-9 Note: You must minimally have the Signal Processing Toolbox™ installed to use fdesign and design. Some of the features described below may be unavailable if your installation does not additionally include the DSP System Toolbox license. The DSP System Toolbox significantly expands the functionality available for the specification, design, and analysis of filters. You can verify the presence of both toolboxes by typing ver at the command prompt. Exploring the Process Flow Diagram The process flow diagram shown in the following figure lists the steps and shows the order of the filter design process. 4-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in Fdesign — Process Overview The first four steps of the filter design process relate to the filter Specifications Object, while the last two steps involve the filter Implementation Object. Both of these objects are discussed in more detail in the following sections. Step 5 - the design of the filter, is the transition step from the filter Specifications Object to the Implementation object. The www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-3 4 Filter Analysis, Design, and Implementation analysis and verification step is completely optional. It provides methods for the filter designer to ensure that the filter complies with all design criteria. Depending on the results of this verification, you can loop back to steps 3 and 4, to either choose a different algorithm, or to customize the current one. You may also wish to go back to steps 3 or 4 after you filter the input data with the designed filter (step 7), and find that you wish to tweak the filter or change it further. The diagram shows the help command for each step. Enter the help line at the MATLAB command prompt to receive instructions and further documentation links for the particular step. Not all of the steps have to be executed explicitly. For example, you could go from step 1 directly to step 5, and the interim three steps are done for you by the software. The following are the details for each of the steps shown above. Select a Response If you type: help fdesign/responses at the MATLAB command prompt, you see a list of all available filter responses. The responses marked with an asterisk require the DSP System Toolbox. You must select a response to initiate the filter. In this example, a bandpass filter Specifications Object is created by typing the following: d = fdesign.bandpass Select a Specification A specification is an array of design parameters for a given filter. The specification is a property of the Specifications Object. Note: A specification is not the same as the Specifications Object. A Specifications Object contains a specification as one of its properties. When you select a filter response, there are a number of different specifications available. Each one contains a different combination of design parameters. After you create a filter Specifications Object, you can query the available specifications for that response. Specifications marked with an asterisk require the DSP System Toolbox. 4-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in Fdesign — Process Overview >> d = fdesign.bandpass; % step 1 - choose the response >> set (d, 'specification') ans = 'Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2' 'N,F3dB1,F3dB2' 'N,F3dB1,F3dB2,Ap' 'N,F3dB1,F3dB2,Ast' 'N,F3dB1,F3dB2,Ast1,Ap,Ast2' 'N,F3dB1,F3dB2,BWp' 'N,F3dB1,F3dB2,BWst' 'N,Fc1,Fc2' 'N,Fp1,Fp2,Ap' 'N,Fp1,Fp2,Ast1,Ap,Ast2' 'N,Fst1,Fp1,Fp2,Fst2' 'N,Fst1,Fp1,Fp2,Fst2,Ap' 'N,Fst1,Fst2,Ast' 'Nb,Na,Fst1,Fp1,Fp2,Fst2' >> d=fdesign.arbmag; >> set(d,'specification') ans = 'N,F,A' 'N,B,F,A' The set command can be used to select one of the available specifications as follows: >> d = fdesign.lowpass; % step 1 >> % step 2: get a list of available specifications >> set (d, 'specification') ans = 'Fp,Fst,Ap,Ast' 'N,F3dB' 'N,F3dB,Ap' 'N,F3dB,Ap,Ast' 'N,F3dB,Ast' 'N,F3dB,Fst' 'N,Fc' 'N,Fc,Ap,Ast' 'N,Fp,Ap' 'N,Fp,Ap,Ast' www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-5 4 Filter Analysis, Design, and Implementation 'N,Fp,F3dB' 'N,Fp,Fst' 'N,Fp,Fst,Ap' 'N,Fp,Fst,Ast' 'N,Fst,Ap,Ast' 'N,Fst,Ast' 'Nb,Na,Fp,Fst' >> %step 2: set the required specification >> set (d, 'specification', 'N,Fc') If you do not perform this step explicitly, fdesign returns the default specification for the response you chose in “Select a Response” on page 4-4, and provides default values for all design parameters included in the specification. Select an Algorithm The availability of algorithms depends the chosen filter response, the design parameters, and the availability of the DSP System Toolbox. In other words, for the same lowpass filter, changing the specification string also changes the available algorithms. In the following example, for a lowpass filter and a specification of 'N, Fc', only one algorithm is available—window. >> %step 2: set the required specification >> set (d, 'specification', 'N,Fc') >> designmethods (d) %step3: get available algorithms Design Methods for class fdesign.lowpass (N,Fc): window However, for a specification of 'Fp,Fst,Ap,Ast', a number of algorithms are available. If the user has only the Signal Processing Toolbox installed, the following algorithms are available: >>set (d, 'specification', 'Fp,Fst,Ap,Ast') >>designmethods(d) Design Methods for class fdesign.lowpass (Fp,Fst,Ap,Ast): butter cheby1 4-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in Fdesign — Process Overview cheby2 ellip equiripple kaiserwin If the user additionally has the DSP System Toolbox installed, the number of available algorithms for this response and specification string increases: >>set(d,'specification','Fp,Fst,Ap,Ast') >>designmethods(d) Design Methods for class fdesign.lowpass (Fp,Fst,Ap,Ast): butter cheby1 cheby2 ellip equiripple ifir kaiserwin multistage The user chooses a particular algorithm and implements the filter with the design function. >>Hd=design(d,'butter'); The preceding code actually creates the filter, where Hd is the filter Implementation Object. This concept is discussed further in the next step. If you do not perform this step explicitly, design automatically selects the optimum algorithm for the chosen response and specification. Customize the Algorithm The customization options available for any given algorithm depend not only on the algorithm itself, selected in “Select an Algorithm” on page 4-6, but also on the specification selected in “Select a Specification” on page 4-4. To explore all the available options, type the following at the MATLAB command prompt: help (d, 'algorithm-name') where d is the Filter Specification Object, and algorithm-name is the name of the algorithm in single quotes, such as 'butter' or 'cheby1'. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-7 4 Filter Analysis, Design, and Implementation The application of these customization options takes place while “Design the Filter” on page 4-8, because these options are the properties of the filter Implementation Object, not the Specification Object. If you do not perform this step explicitly, the optimum algorithm structure is selected. Design the Filter This next task introduces a new object, the Filter Object, or dfilt. To create a filter, use the design command: >> % design filter w/o specifying the algorithm >> Hd = design(d); where Hd is the Filter Object and d is the Specifications Object. This code creates a filter without specifying the algorithm. When the algorithm is not specified, the software selects the best available one. To apply the algorithm chosen in “Select an Algorithm” on page 4-6, use the same design command, but specify the Butterworth algorithm as follows: >> Hd = design(d, 'butter'); where Hd is the new Filter Object, and d is the Specifications Object. To obtain help and see all the available options, type: >> help fdesign/design This help command describes not only the options for the design command itself, but also options that pertain to the method or the algorithm. If you are customizing the algorithm, you apply these options in this step. In the following example, you design a bandpass filter, and then modify the filter structure: >> Hd = design(d, 'butter', 'filterstructure', 'df2sos') f = FilterStructure: Arithmetic: sosMatrix: ScaleValues: PersistentMemory: 'Direct-Form II, Second-Order Sections' 'double' [7x6 double] [8x1 double] false The filter design step, just like the first task of choosing a response, must be performed explicitly. A Filter Object is created only when design is called. 4-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in Fdesign — Process Overview Design Analysis After the filter is designed you may wish to analyze it to determine if the filter satisfies the design criteria. Filter analysis is broken into three main sections: • Frequency domain analysis — Includes the magnitude response, group delay, and pole-zero plots. • Time domain analysis — Includes impulse and step response • Implementation analysis — Includes quantization noise and cost To display help for analysis of a discrete-time filter, type: >> help dfilt/analysis To display help for analysis of a multirate filter, type: >> help mfilt/functions To analyze your filter, you must explicitly perform this step. Realize or Apply the Filter to Input Data After the filter is designed and optimized, it can be used to filter actual input data. The basic filter command takes input data x, filters it through the Filter Object, and produces output y: >> y = filter (FilterObj, x) This step is never automatically performed for you. To filter your data, you must explicitly execute this step. To understand how the filtering commands work, type: >> help dfilt/filter Note: If you have Simulink, you have the option of exporting this filter to a Simulink block using the realizemdl command. To get help on this command, type: >> help realizemdl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-9 4 Filter Analysis, Design, and Implementation Design a Filter in the Filterbuilder GUI The Graphical Interface to Fdesign • “Introduction to Filterbuilder” on page 4-10 • “Filterbuilder Design Process” on page 4-10 • “Select a Response” on page 4-11 • “Select a Specification” on page 4-11 • “Select an Algorithm” on page 4-12 • “Customize the Algorithm” on page 4-12 • “Analyze the Design” on page 4-12 • “Realize or Apply the Filter to Input Data” on page 4-13 Introduction to Filterbuilder The filterbuilder function provides a graphical interface to the fdesign objectoriented filter design paradigm and is intended to reduce development time during the filter design process. filterbuilder uses a specification-centered approach to find the best filter for the desired response. Note: filterbuilder requires the Signal Processing Toolbox. The functionality of filterbuilder is greatly expanded by the DSP System Toolbox. Some of the features described or displayed below are only available if the DSP System Toolbox is installed. You may verify your installation by typing ver at the command prompt. Filterbuilder Design Process The design process when using filterbuilder is similar to the process outlined in the section titled “Process Flow Diagram and Filter Design Methodology” in the Getting Started guide. The idea is to choose the constraints and specifications of the filter, and to use those as a starting point in the design. Postponing the choice of algorithm for the filter allows the best design method to be determined automatically, based upon the desired performance criteria. The following are the details of each of the steps for designing a filter with filterbuilder. 4-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in the Filterbuilder GUI Select a Response When you open the filterbuilder tool by typing: filterbuilder at the MATLAB command prompt, the Response Selection dialog box appears, listing all possible filter responses available in the software. If you have the DSP System Toolbox software installed, you have access to the full complement of filter responses. Note: This step cannot be skipped because it is not automatically completed for you by the software. You must select a response to initiate the filter design process. After you choose a response, say bandpass, you start the design of the Specifications Object, and the Bandpass Design dialog box appears. This dialog box contains a Main pane, a Data Types pane and a Code Generation pane. The specifications of your filter are generally set in the Main pane of the dialog box. The Data Types pane provides settings for precision and data types, and the Code Generation pane contains options for various implementations of the completed filter design. For the initial design of your filter, you will mostly use the Main pane. The Bandpass Design dialog box contains all the parameters you need to determine the specifications of a bandpass filter. The parameters listed in the Main pane depend upon the type of filter you are designing. However, no matter what type of filter you have chosen in the Response Selection dialog box, the filter design dialog box contains the Main, Data Types, and Code Generation panes. Select a Specification To choose the specification for the bandpass filter, you can begin by selecting an Impulse Response, Order Mode, and Filter Type in the Filter Specifications frame of the Main Pane. You can further specify the response of your filter by setting frequency and magnitude specifications in the appropriate frames on the Main Pane. Note: Frequency, Magnitude, and Algorithm specifications are interdependent and may change based upon your Filter Specifications selections. When choosing specifications for your filter, select your Filter Specifications first and work your www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-11 4 Filter Analysis, Design, and Implementation way down the dialog box- this approach ensures that the best settings for dependent specifications display as available in the dialog box. Select an Algorithm The algorithms available for your filter depend upon the filter response and design parameters you have selected in the previous steps. For example, in the case of a bandpass filter, if the impulse response selected is IIR and the Order Mode field is set toMinimum, the design methods available are Butterworth, Chebyshev type I or II, or Elliptic, whereas if the Order Mode field is set to Specify, the design method available is IIR least p-norm. Customize the Algorithm By expanding the Design options section of the Algorithm frame, you can further customize the algorithm specified. The options available will depend upon the algorithm and settings that have already been selected in the dialog box. In the case of a bandpass IIR filter using the Butterworth method, design options such as Match Exactly are available. Analyze the Design To analyze the filter response, click on the View Filter Response button. The Filter Visualization Tool opens displaying the magnitude plot of the filter response. 4-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Design a Filter in the Filterbuilder GUI Realize or Apply the Filter to Input Data When you have achieved the desired filter response through design iterations and analysis using the Filter Visualization Tool, apply the filter to the input data. Again, this step is never automatically performed for you by the software. To filter your data, you must explicitly execute this step. In the Filter Visualization Tool, click OK and DSP System Toolbox software creates the filter object with the name specified in the Save variable as field and exports it to the MATLAB workspace. The filter is then ready to be used to filter actual input data. The basic filter command takes input data x, filters it through the Filter Object, and produces output y: >> y = filter (FilterObj, x) To understand how the filtering commands work, type: >> help dfilt/filter Tip If you have Simulink, you have the option of exporting this filter to a Simulink block using the realizemdl command. To get help on this command, type: >> help realizemdl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-13 4 Filter Analysis, Design, and Implementation Use FDATool with DSP System Toolbox Software In this section... “Design Advanced Filters in FDATool” on page 4-14 “Access the Quantization Features of FDATool” on page 4-18 “Quantize Filters in FDATool” on page 4-20 “Analyze Filters with a Noise-Based Method” on page 4-28 “Scale Second-Order Section Filters” on page 4-33 “Reorder the Sections of Second-Order Section Filters” on page 4-37 “View SOS Filter Sections” on page 4-42 “Import and Export Quantized Filters” on page 4-47 “Generate MATLAB Code” on page 4-52 “Import XILINX Coefficient (.COE) Files” on page 4-53 “Transform Filters Using FDATool” on page 4-53 “Design Multirate Filters in FDATool” on page 4-62 “Realize Filters as Simulink Subsystem Blocks” on page 4-74 Design Advanced Filters in FDATool • “Overview of FDATool Features” on page 4-14 • “Use FDATool with DSP System Toolbox Software” on page 4-15 • “Design a Notch Filter” on page 4-16 Overview of FDATool Features DSP System Toolbox software adds new dialog boxes and operating modes, and new menu selections, to the Filter Design and Analysis Tool (FDATool) provided by Signal Processing Toolbox software. From the additional dialog boxes, one titled Set Quantization Parameters and one titled Frequency Transformations, you can: • Design advanced filters that Signal Processing Toolbox software does not provide the design tools to develop. • View Simulink models of the filter structures available in the toolbox. • Quantize double-precision filters you design in this GUI using the design mode. 4-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software • Quantize double-precision filters you import into this GUI using the import mode. • Analyze quantized filters. • Scale second-order section filters. • Select the quantization settings for the properties of the quantized filter displayed by the tool: • Coefficients — select the quantization options applied to the filter coefficients • Input/output — control how the filter processes input and output data • Filter Internals — specify how the arithmetic for the filter behaves • Design multirate filters. • Transform both FIR and IIR filters from one response to another. After you import a filter into FDATool, the options on the quantization dialog box let you quantize the filter and investigate the effects of various quantization settings. Options in the frequency transformations dialog box let you change the frequency response of your filter, keeping various important features while changing the response shape. Use FDATool with DSP System Toolbox Software Adding DSP System Toolbox software to your tool suite adds a number of filter design techniques to FDATool. Use the new filter responses to develop filters that meet more complex requirements than those you can design in Signal Processing Toolbox software. While the designs in FDATool are available as command line functions, the graphical user interface of FDATool makes the design process more clear and easier to accomplish. As you select a response type, the options in the right panes in FDATool change to let you set the values that define your filter. You also see that the analysis area includes a diagram (called a design mask) that describes the options for the filter response you choose. By reviewing the mask you can see how the options are defined and how to use them. While this is usually straightforward for lowpass or highpass filter responses, setting the options for the arbitrary response types or the peaking/notching filters is more complicated. Having the masks leads you to your result more easily. Changing the filter design method changes the available response type options. Similarly, the response type you select may change the filter design methods you can choose. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-15 4 Filter Analysis, Design, and Implementation Design a Notch Filter Notch filters aim to remove one or a few frequencies from a broader spectrum. You must specify the frequencies to remove by setting the filter design options in FDATool appropriately: • Response Type • Design Method • Frequency Specifications • Magnitude Specifications Here is how you design a notch filter that removes concert A (440 Hz) from an input musical signal spectrum. 1 Select Notching from the Differentiator list in Response Type. 2 Select IIR in Filter Design Method and choose Single Notch from the list. 3 For the Frequency Specifications, set Units to Hz and Fs, the full scale frequency, to 1000. 4 Set the location of the center of the notch, in either normalized frequency or Hz. For the notch center at 440 Hz, enter 440. 5 To shape the notch, enter the bandwidth, bw, to be 40. 6 Leave the Magnitude Specification in dB (the default) and leave Apass as 1. 7 Click Design Filter. FDATool computes the filter coefficients and plots the filter magnitude response in the analysis area for you to review. When you design a single notch filter, you do not have the option of setting the filter order — the Filter Order options are disabled. Your filter should look about like this: 4-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software For more information about a design method, refer to the online Help system. For instance, to get further information about the Q setting for the notch filter in FDATool, enter doc iirnotch at the command line. This opens the Help browser and displays the reference page for function iirnotch. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-17 4 Filter Analysis, Design, and Implementation Designing other filters follows a similar procedure, adjusting for different design specification options as each design requires. Any one of the designs may be quantized in FDATool and analyzed with the available analyses on the Analysis menu. Access the Quantization Features of FDATool You use the quantization panel in FDATool to quantize filters. Quantization represents the fourth operating mode for FDATool, along with the filter design, filter transformation, and import modes. To switch to quantization mode, open FDATool from the MATLAB command prompt by entering fdatool When FDATool opens, click the Set Quantization Parameters button on the side bar. FDATool switches to quantization mode and you see the following panel at the bottom of FDATool, with the default double-precision option shown for Filter arithmetic. 4-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software The Filter arithmetic option lets you quantize filters and investigate the effects of changing quantization settings. To enable the quantization settings in FDATool, select Fixed-point from the Filter Arithmetic. The quantization options appear in the lower panel of FDATool. You see tabs that access various sets of options for quantizing your filter. You use the following tabs in the dialog box to perform tasks related to quantizing filters in FDATool: • Coefficients provides access the settings for defining the coefficient quantization. This is the default active panel when you switch FDATool to quantization mode without a quantized filter in the tool. When you import a fixed-point filter into FDATool, this is the active pane when you switch to quantization mode. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-19 4 Filter Analysis, Design, and Implementation • Input/Output switches FDATool to the options for quantizing the inputs and outputs for your filter. • Filter Internals lets you set a variety of options for the arithmetic your filter performs, such as how the filter handles the results of multiplication operations or how the filter uses the accumulator. • Apply — applies changes you make to the quantization parameters for your filter. Quantize Filters in FDATool • “Set Quantization Parameters” on page 4-20 • “Coefficients Options” on page 4-20 • “Input/Output Options” on page 4-22 • “Filter Internals Options” on page 4-24 • “Filter Internals Options for CIC Filters” on page 4-26 Set Quantization Parameters Quantized filters have properties that define how they quantize data you filter. Use the Set Quantization Parameters dialog box in FDATool to set the properties. Using options in the Set Quantization Parameters dialog box, FDATool lets you perform a number of tasks: • Create a quantized filter from a double-precision filter after either importing the filter from your workspace, or using FDATool to design the prototype filter. • Create a quantized filter that has the default structure (Direct form II transposed) or any structure you choose, and other property values you select. • Change the quantization property values for a quantized filter after you design the filter or import it from your workspace. When you click Set Quantization Parameters, and then change Filter arithmetic to Fixed-point, the quantized filter panel opens in FDATool, with the coefficient quantization options set to default values. Coefficients Options To let you set the properties for the filter coefficients that make up your quantized filter, FDATool lists options for numerator word length (and denominator word length 4-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software if you have an IIR filter). The following table lists each coefficients option and a short description of what the option setting does in the filter. Option Name When Used Description Numerator Word Length FIR filters only Sets the word length used to represent numerator coefficients in FIR filters. Numerator Frac. Length FIR/IIR Sets the fraction length used to interpret numerator coefficients in FIR filters. Numerator Range (+/-) FIR/IIR Lets you set the range the numerators represent. You use this instead of the Numerator Frac. Length option to set the precision. When you enter a value x, the resulting range is -x to x. Range must be a positive integer. Coefficient Word Length IIR filters only Sets the word length used to represent both numerator and denominator coefficients in IIR filters. You cannot set different word lengths for the numerator and denominator coefficients. Denominator Frac. Length IIR filters Sets the fraction length used to interpret denominator coefficients in IIR filters. Denominator Range (+/-) IIR filters Lets you set the range the denominator coefficients represent. You use this instead of the Denominator Frac. Length option to set the precision. When you enter a value x, the resulting range is -x to x. Range must be a positive integer. Best-precision fraction lengths All filters Directs FDATool to select the fraction lengths for numerator (and denominator where available) values to maximize the filter performance. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-21 4 Filter Analysis, Design, and Implementation Option Name When Used Description Selecting this option disables all of the fraction length options for the filter. Scale Values frac. length SOS IIR filters Sets the fraction length used to interpret the scale values in SOS filters. Scale Values range (+/-) SOS IIR filters Lets you set the range the SOS scale values represent. You use this with SOS filters to adjust the scaling used between filter sections. Setting this value disables the Scale Values frac. length option. When you enter a value x, the resulting range is -x to x. Range must be a positive integer. Use unsigned representation All filters Tells FDATool to interpret the coefficients as unsigned values. Scale the numerator coefficients to fully utilize the entire dynamic range All filters Directs FDATool to scale the numerator coefficients to effectively use the dynamic range defined by the numerator word length and fraction length format. Input/Output Options The options that specify how the quantized filter uses input and output values are listed in the table below. Option Name When Used Description Input Word Length All filters Sets the word length used to represent the input to a filter. Input fraction length All filters Sets the fraction length used to interpret input values to filter. Input range (+/-) All filters Lets you set the range the inputs represent. You use this instead of the Input fraction length option to set the precision. When you enter a value x, the 4-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Option Name When Used Description resulting range is -x to x. Range must be a positive integer. Output word length All filters Sets the word length used to represent the output from a filter. Avoid overflow All filters Directs the filter to set the fraction length for the input to prevent the output values from exceeding the available range as defined by the word length. Clearing this option lets you set Output fraction length. Output fraction length All filters Sets the fraction length used to represent output values from a filter. Output range (+/-) All filters Lets you set the range the outputs represent. You use this instead of the Output fraction length option to set the precision. When you enter a value x, the resulting range is -x to x. Range must be a positive integer. Stage input word length SOS filters only Sets the word length used to represent the input to an SOS filter section. Avoid overflow SOS filters only Directs the filter to use a fraction length for stage inputs that prevents overflows in the values. When you clear this option, you can set Stage input fraction length. Stage input fraction length SOS filters only Sets the fraction length used to represent input to a section of an SOS filter. Stage output word length SOS filters only Sets the word length used to represent the output from an SOS filter section. Avoid overflow SOS filters only Directs the filter to use a fraction length for stage outputs that prevents overflows in the values. When you clear this option, you can set Stage output fraction length. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-23 4 Filter Analysis, Design, and Implementation Option Name When Used Description Stage output fraction length SOS filters only Sets the fraction length used to represent the output from a section of an SOS filter. Filter Internals Options The options that specify how the quantized filter performs arithmetic operations are listed in the table below. Option Equivalent Filter Property (Using Wildcard *) Description Round towards RoundMode Sets the mode the filter uses to quantize numeric values when the values lie between representable values for the data format (word and fraction lengths). Choose from one of: • ceil - Round toward positive infinity. • convergent - Round to the closest representable integer. Ties round to the nearest even stored integer. This is the least biased of the methods available in this software. • fix/zero - Round toward zero. • floor - Round toward negative infinity. • nearest - Round toward nearest. Ties round toward positive infinity. • round - Round toward nearest. Ties round toward negative infinity for negative numbers, and toward positive infinity for positive numbers. Overflow Mode 4-24 OverflowMode Sets the mode used to respond to overflow conditions in fixed-point arithmetic. Choose from either saturate (limit the output to the largest positive or negative representable value) or wrap www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Option Equivalent Filter Property (Using Wildcard *) Description (set overflowing values to the nearest representable value using modular arithmetic. Filter Product (Multiply) Options Product Mode ProductMode Determines how the filter handles the output of product operations. Choose from full precision (FullPrecision), or whether to keep the most significant bit (KeepMSB) or least significant bit (KeepLSB) in the result when you need to shorten the word length. Specify all lets you set the fraction length applied to the results of product operations. Product word length *ProdWordLength Sets the word length applied to interpret the results of multiply operations. Num. fraction length NumProdFracLength Sets the fraction length used to interpret the results of product operations that involve numerator coefficients. Den. fraction length DenProdFracLength Sets the fraction length used to interpret the results of product operations that involve denominator coefficients. Accum. mode AccumMode Determines how the accumulator outputs stored values. Choose from full precision (FullPrecision), or whether to keep the most significant bits (KeepMSB) or least significant bits (KeepLSB) when output results need shorter word length than the accumulator supports. To let you set the word length and the precision (the fraction length) used by the output from the accumulator, set this to Specify all. Accum. word length *AccumWordLength Sets the word length used to store data in the accumulator/buffer. Filter Sum Options www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-25 4 Filter Analysis, Design, and Implementation Option Equivalent Filter Property (Using Wildcard *) Description Num. fraction length NumAccumFracLength Sets the fraction length used to interpret the numerator coefficients. Den. fraction length DenAccumFracLength Sets the fraction length the filter uses to interpret denominator coefficients. Cast signals before sum CastBeforeSum Specifies whether to cast numeric data to the appropriate accumulator format (as shown in the signal flow diagrams for each filter structure) before performing sum operations. State word length *StateWordLength Sets the word length used to represent the filter states. Applied to both numeratorand denominator-related states Avoid overflow None Prevent overflows in arithmetic calculations by setting the fraction length appropriately. State fraction length *StateFracLength Lets you set the fraction length applied to interpret the filter states. Applied to both numerator- and denominator-related states Filter State Options Note: When you apply changes to the values in the Filter Internals pane, the plots for the Magnitude response estimate and Round-off noise power spectrum analyses update to reflect those changes. Other types of analyses are not affected by changes to the values in the Filter Internals pane. Filter Internals Options for CIC Filters CIC filters use slightly different options for specifying the fixed-point arithmetic in the filter. The next table shows and describes the options. 4-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Quantize Double-Precision Filters When you are quantizing a double-precision filter by switching to fixed-point or singleprecision floating point arithmetic, follow these steps. 1 Click Set Quantization Parameters to display the Set Quantization Parameters pane in FDATool. 2 Select Single-precision floating point or Fixed-point from Filter arithmetic. When you select one of the optional arithmetic settings, FDATool quantizes the current filter according to the settings of the options in the Set Quantization Parameter panes, and changes the information displayed in the analysis area to show quantized filter data. 3 In the quantization panes, set the options for your filter. Set options for Coefficients, Input/Output, and Filter Internals. 4 Click Apply. FDATool quantizes your filter using your new settings. 5 Use the analysis features in FDATool to determine whether your new quantized filter meets your requirements. Change the Quantization Properties of Quantized Filters When you are changing the settings for the quantization of a quantized filter, or after you import a quantized filter from your MATLAB workspace, follow these steps to set the property values for the filter: 1 Verify that the current filter is quantized. 2 Click Set Quantization Parameters to display the Set Quantization Parameters panel. 3 Review and select property settings for the filter quantization: Coefficients, Input/ Output, and Filter Internals. Settings for options on these panes determine how your filter quantizes data during filtering operations. 4 Click Apply to update your current quantized filter to use the new quantization property settings from Step 3. 5 Use the analysis features in FDATool to determine whether your new quantized filter meets your requirements. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-27 4 Filter Analysis, Design, and Implementation Analyze Filters with a Noise-Based Method • “Analyze Filters with the Magnitude Response Estimate Method” on page 4-28 • “Compare the Estimated and Theoretical Magnitude Responses” on page 4-31 • “Select Quantized Filter Structures” on page 4-31 • “Convert the Structure of a Quantized Filter” on page 4-32 • “Convert Filters to Second-Order Sections Form” on page 4-32 Analyze Filters with the Magnitude Response Estimate Method After you design and quantize your filter, the Magnitude Response Estimate option on the Analysis menu lets you apply the noise loading method to your filter. When you select Analysis > Magnitude Response Estimate from the menu bar, FDATool immediately starts the Monte Carlo trials that form the basis for the method and runs the analysis, ending by displaying the results in the analysis area in FDATool. With the noise-based method, you estimate the complex frequency response for your filter as determined by applying a noise- like signal to the filter input. Magnitude Response Estimate uses the Monte Carlo trials to generate a noise signal that contains complete frequency content across the range 0 to Fs. The first time you run the analysis, magnitude response estimate uses default settings for the various conditions that define the process, such as the number of test points and the number of trials. Analysis Parameter Default Setting Description Number of Points 512 Number of equally spaced points around the upper half of the unit circle. Frequency Range 0 to Fs/2 Frequency range of the plot x-axis. Frequency Units Hz Units for specifying the frequency range. Sampling Frequency 48000 Inverse of the sampling period. Frequency Scale dB Units used for the y-axis display of the output. Normalized Frequency Off Use normalized frequency for the display. After your first analysis run ends, open the Analysis Parameters dialog box and adjust your settings appropriately, such as changing the number of trials or number of points. 4-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software To open the Analysis Parameters dialog box, use either of the next procedures when you have a quantized filter in FDATool: • Select Analysis > Analysis Parameters from the menu bar • Right-click in the filter analysis area and select Analysis Parameters from the context menu Whichever option you choose opens the dialog box. Notice that the settings for the options reflect the defaults. Noise Method Applied to a Filter To demonstrate the magnitude response estimate method, start by creating a quantized filter. For this example, use FDATool to design a sixth-order Butterworth IIR filter. To Use Noise-Based Analysis in FDATool 1 Enter fdatool at the MATLAB prompt to launch FDATool. 2 Under Response Type, select Highpass. 3 Select IIR in Design Method. Then select Butterworth. 4 To set the filter order to 6, select Specify order under Filter Order. Enter 6 in the text box. 5 Click Design Filter. In FDATool, the analysis area changes to display the magnitude response for your filter. 6 To generate the quantized version of your filter, using default quantizer settings, click on the side bar. FDATool switches to quantization mode and displays the quantization panel. 7 From Filter arithmetic, select fixed-point. Now the analysis areas shows the magnitude response for both filters — your original filter and the fixed-point arithmetic version. 8 Finally, to use noise-based estimation on your quantized filter, select Analysis > Magnitude Response Estimate from the menu bar. FDATool runs the trial, calculates the estimated magnitude response for the filter, and displays the result in the analysis area as shown in this figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-29 4 Filter Analysis, Design, and Implementation In the above figure you see the magnitude response as estimated by the analysis method. View the Noise Power Spectrum When you use the noise method to estimate the magnitude response of a filter, FDATool simulates and applies a spectrum of noise values to test your filter response. While the simulated noise is essentially white, you might want to see the actual spectrum that FDATool used to test your filter. From the Analysis menu bar option, select Round-off Noise Power Spectrum. In the analysis area in FDATool, you see the spectrum of the noise used to estimate the filter response. The details of the noise spectrum, such as the range and number of data points, appear in the Analysis Parameters dialog box. For more information, refer to McClellan, et al., Computer-Based Exercises for Signal Processing Using MATLAB 5, Prentice-Hall, 1998. See Project 5: Quantization Noise in Digital Filters, page 231. Change Your Noise Analysis Parameters In “Noise Method Applied to a Filter” on page 4-29, you used synthetic white noise to estimate the magnitude response for a fixed-point highpass Butterworth filter. Since you ran the estimate only once in FDATool, your noise analysis used the default analysis parameters settings shown in “Analyze Filters with the Magnitude Response Estimate Method” on page 4-28. 4-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software To change the settings, follow these steps after the first time you use the noise estimate on your quantized filter. 1 With the results from running the noise estimating method displayed in the FDATool analysis area, select Analysis > Analysis Parameters from the menu bar. To give you access to the analysis parameters, the Analysis Parameters dialog box opens (with default settings). 2 To use more points in the spectrum to estimate the magnitude response, change Number of Points to 1024 and click OK to run the analysis. FDATool closes the Analysis Parameters dialog box and reruns the noise estimate, returning the results in the analysis area. To rerun the test without closing the dialog box, press Enter after you type your new value into a setting, then click Apply. Now FDATool runs the test without closing the dialog box. When you want to try many different settings for the noise-based analysis, this is a useful shortcut. Compare the Estimated and Theoretical Magnitude Responses An important measure of the effectiveness of the noise method for estimating the magnitude response of a quantized filter is to compare the estimated response to the theoretical response. One way to do this comparison is to overlay the theoretical response on the estimated response. While you have the Magnitude Response Estimate displaying in FDATool, select Analysis > Overlay Analysis from the menu bar. Then select Magnitude Response to show both response curves plotted together in the analysis area. Select Quantized Filter Structures FDATool lets you change the structure of any quantized filter. Use the Convert structure option to change the structure of your filter to one that meets your needs. To learn about changing the structure of a filter in FDATool, refer to “Converting the Filter Structure” in your Signal Processing Toolbox documentation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-31 4 Filter Analysis, Design, and Implementation Convert the Structure of a Quantized Filter You use the Convert structure option to change the structure of filter. When the Source is Designed(Quantized) or Imported(Quantized), Convert structure lets you recast the filter to one of the following structures: • “Direct Form II Transposed Filter Structure” • “Direct Form I Transposed Filter Structure” • “Direct Form II Filter Structure” • “Direct Form I Filter Structure” • “Direct Form Finite Impulse Response (FIR) Filter Structure” • “Direct Form FIR Transposed Filter Structure” • “Lattice Autoregressive Moving Average (ARMA) Filter Structure” • dfilt.calattice • dfilt.calatticepc • “Direct Form Antisymmetric FIR Filter Structure (Any Order)” Starting from any quantized filter, you can convert to one of the following representation: • Direct form I • Direct form II • Direct form I transposed • Direct form II transposed • Lattice ARMA Additionally, FDATool lets you do the following conversions: • Minimum phase FIR filter to Lattice MA minimum phase • Maximum phase FIR filter to Lattice MA maximum phase • Allpass filters to Lattice allpass Refer to “FilterStructure” for details about each of these structures. Convert Filters to Second-Order Sections Form To learn about using FDATool to convert your quantized filter to use second-order sections, refer to “Converting to Second-Order Sections” in your Signal Processing 4-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Toolbox documentation. You might notice that filters you design in FDATool, rather than filters you imported, are implemented in SOS form. View Filter Structures in FDATool To open the demonstration, click Help > Show filter structures. After the Help browser opens, you see the reference page for the current filter. You find the filter structure signal flow diagram on this reference page, or you can navigate to reference pages for other filter. Scale Second-Order Section Filters • “Use the Reordering and Scaling Second-Order Sections Dialog Box” on page 4-33 • “Scale an SOS Filter” on page 4-35 Use the Reordering and Scaling Second-Order Sections Dialog Box FDATool provides the ability to scale SOS filters after you create them. Using options on the Reordering and Scaling Second-Order Sections dialog box, FDATool scales either or both the filter numerators and filter scale values according to your choices for the scaling options. Parameter Description and Valid Value Scale Apply any scaling options to the filter. Select this when you are reordering your SOS filter and you want to scale it at the same time. Or when you are scaling your filter, with or without reordering. Scaling is disabled by default. No Overflow — High SNR slider Lets you set whether scaling favors reducing arithmetic overflow in the filter or maximizing the signal-to-noise ratio (SNR) at the filter output. Moving the slider to the right increases the emphasis on SNR at the expense of possible overflows. The markings indicate the P-norm applied to achieve the desired result in SNR or overflow protection. For more information about the P-norm settings, refer to norm for details. Maximum Numerator Maximum allowed value for numerator coefficients after scaling. Numerator Constraint Specifies whether and how to constrain numerator coefficient values. Options are none, normalize, www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-33 4 Filter Analysis, Design, and Implementation Parameter Description and Valid Value power of 2, and unit. Choosing none lets the scaling use any scale value for the numerators by removing any constraints on the numerators, except that the coefficients will be clipped if they exceed the Maximum Numerator. With Normalize the maximum absolute value of the numerator is forced to equal the Maximum Numerator value (for all other constraints, the Maximum Numerator is only an upper limit, above which coefficients will be clipped). The power of 2 option forces scaling to use numerator values that are powers of 2, such as 2 or 0.5. With unit, the leading coefficient of each numerator is forced to a value of 1. Overflow Mode Sets the way the filter handles arithmetic overflow situations during scaling. Choose from either saturate (limit the output to the largest positive or negative representable value) or wrap (set overflowing values to the nearest representable value using modular arithmetic. Scale Value Constraint Specify whether to constrain the filter scale values, and how to constrain them. Valid options are unit, power of 2, and none. Choosing unit for the constraint disables the Max. Scale Value setting and forces scale values to equal 1. Power of 2 constrains the scale values to be powers of 2, such as 2 or 0.5, while none removes any constraint on the scale values, except that they cannot exceed the Max. Scale Value. Max. Scale Value Sets the maximum allowed scale values. SOS filter scaling applies the Max. Scale Value limit only when you set Scale Value Constraint to a value other than unit (the default setting). Setting a maximum scale value removes any other limits on the scale values. Revert to Original Filter Returns your filter to the original scaling. Being able to revert to your original filter makes it easier to assess the results of scaling your filter. Various combinations of settings let you scale filter numerators without changing the scale values, or adjust the filter scale values without changing the numerators. There is no scaling control for denominators. 4-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Scale an SOS Filter Start the process by designing a lowpass elliptical filter in FDATool. 1 Launch FDATool. 2 In Response Type, select Lowpass. 3 In Design Method, select IIR and Elliptic from the IIR design methods list. 4 Select Minimum Order for the filter. 5 Switch the frequency units by choosing Normalized(0 to 1) from the Units list. 6 To set the passband specifications, enter 0.45 for wpass and 0.55 for wstop. Finally, in Magnitude Specifications, set Astop to 60. 7 Click Design Filter to design the filter. After FDATool finishes designing the filter, you see the following plot and settings in the tool. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-35 4 Filter Analysis, Design, and Implementation You kept the Options setting for Match exactly as both, meaning the filter design matches the specification for the passband and the stopband. 8 To switch to scaling the filter, select Edit > Reorder and Scale Second-Order Sections from the menu bar. 9 To see the filter coefficients, return to FDATool and select Filter Coefficients from the Analysis menu. FDATool displays the coefficients and scale values in FDATool. With the coefficients displayed you can see the effects of scaling your filter directly in the scale values and filter coefficients. 4-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Now try scaling the filter in a few different ways. First scale the filter to maximize the SNR. 1 Return to the Reordering and Scaling Second-Order Sections dialog box and select None for Reordering in the left pane. This prevents FDATool from reordering the filter sections when you rescale the filter. 2 Move the No Overflow—High SNR slider from No Overflow to High SNR. 3 Click Apply to scale the filter and leave the dialog box open. After a few moments, FDATool updates the coefficients displayed so you see the new scaling. All of the scale factors are now 1, and the SOS matrix of coefficients shows that none of the numerator coefficients are 1 and the first denominator coefficient of each section is 1. 4 Click Revert to Original Filter to restore the filter to the original settings for scaling and coefficients. Reorder the Sections of Second-Order Section Filters Reorder Filters Using FDATool FDATool designs most discrete-time filters in second-order sections. Generally, SOS filters resist the effects of quantization changes when you create fixed-point filters. After you have a second-order section filter in FDATool, either one you designed in the tool, or one you imported, FDATool provides the capability to change the order of the sections that compose the filter. Any SOS filter in FDATool allows reordering of the sections. To reorder the sections of a filter, you access the Reorder and Scaling of Second-Order Sections dialog box in FDATool. With your SOS filter in FDATool, select Edit > Reorder and Scale from the menu bar. FDATool returns the reordering dialog box shown here with the default settings. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-37 4 Filter Analysis, Design, and Implementation Controls on the Reordering and Scaling of Second-Order Sections dialog box In this dialog box, the left-hand side contains options for reordering SOS filters. On the right you see the scaling options. These are independent — reordering your filter does not require scaling (note the Scale option) and scaling does not require that you reorder your filter (note the None option under Reordering). For more about scaling SOS filters, refer to “Scale Second-Order Section Filters” on page 4-33 and to scale in the reference section. Reordering SOS filters involves using the options in the Reordering and Scaling of Second-Order Sections dialog box. The following table lists each reorder option and provides a description of what the option does. 4-38 Control Option Description Auto Reorders the filter sections to minimize the output noise power of the filter. Note that different ordering applies to each specification type, such as lowpass or highpass. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Control Option Description Automatic ordering adapts to the specification type of your filter. None Does no reordering on your filter. Selecting None lets you scale your filter without applying reordering at the same time. When you access this dialog box with a current filter, this is the default setting — no reordering is applied. Least selective section Rearranges the filter sections so the least restrictive to most selective section (lowest Q) section is the first section and the most restrictive (highest Q) section is the last section. Most selective section to Rearranges the filter sections so the most restrictive (highest Q) section is the first section and the least least selective section restrictive (lowest Q) section is the last section. Custom reordering Lets you specify the section ordering to use by enabling the Numerator Order and Denominator Order options Numerator Order Specify new ordering for the sections of your SOS filter. Enter a vector of the indices of the sections in the order in which to rearrange them. For example, a filter with five sections has indices 1, 2, 3, 4, and 5. To switch the second and fourth sections, the vector would be [1,4,3,2,5]. Use Numerator Order Rearranges the denominators in the order assigned to the numerators. Specify Lets you specify the order of the denominators, rather than using the numerator order. Enter a vector of the indices of the sections to specify the order of the denominators to use. For example, a filter with five sections has indices 1, 2, 3, 4, and 5. To switch the second and fourth sections, the vector would be [1,4,3,2,5]. Use Numerator Order Reorders the scale values according to the order of the numerators. Specify Lets you specify the order of the scale values, rather than using the numerator order. Enter a vector of the indices of the sections to specify the order of the denominators to use. For example, a filter with five sections has indices 1, 2, 3, 4, and 5. To switch the second and fourth sections, the vector would be [1,4,3,2,5]. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-39 4 Filter Analysis, Design, and Implementation Control Option Description Revert to Original Filter Returns your filter to the original section ordering. Being able to revert to your original filter makes comparing the results of changing the order of the sections easier to assess. Reorder an SOS Filter With FDATool open a second-order filter as the current filter, you use the following process to access the reordering capability and reorder you filter. Start by launching FDATool from the command prompt. 1 Enter fdatool at the command prompt to launch FDATool. 2 Design a lowpass Butterworth filter with order 10 and the default frequency specifications by entering the following settings: • Under Response Type select Lowpass. • Under Design Method, select IIR and Butterworth from the list. • Specify the order equal to 10 in Specify order under Filter Order. • Keep the default Fs and Fc values in Frequency Specifications. 3 Click Design Filter. FDATool designs the Butterworth filter and returns your filter as a Direct-Form II filter implemented with second-order sections. You see the specifications in the Current Filter Information area. With the second-order filter in FDATool, reordering the filter uses the Reordering and Scaling of Second-Order Sections feature in FDATool (also available in Filter Visualization Tool, fvtool). 4 To reorder your filter, select Edit > Reorder and Scale Second-Order Sections from the FDATool menus. Now you are ready to reorder the sections of your filter. Note that FDATool performs the reordering on the current filter in the session. Use Least Selective to Most Selective Section Reordering To let FDATool reorder your filter so the least selective section is first and the most selective section is last, perform the following steps in the Reordering and Scaling of Second-Order Sections dialog box. 4-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software 1 In Reordering, select Least selective section to most selective section. 2 To prevent filter scaling at the same time, clear Scale in Scaling. 3 In FDATool, select View > SOS View Settings from the menu bar so you see the sections of your filter displayed in FDATool. 4 In the SOS View Settings dialog box, select Individual sections. Making this choice configures FDATool to show the magnitude response curves for each section of your filter in the analysis area. 5 Back in the Reordering and Scaling of Second-Order Sections dialog box, click Apply to reorder your filter according to the Qs of the filter sections, and keep the dialog box open. In response, FDATool presents the responses for each filter section (there should be five sections) in the analysis area. In the next two figures you can compare the ordering of the sections of your filter. In the first figure, your original filter sections appear. In the second figure, the sections have been rearranged from least selective to most selective. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-41 4 Filter Analysis, Design, and Implementation You see what reordering does, although the result is a bit subtle. Now try custom reordering the sections of your filter or using the most selective to least selective reordering option. View SOS Filter Sections • “Using the SOS View Dialog Box” on page 4-42 • “View the Sections of SOS Filters” on page 4-44 Using the SOS View Dialog Box Since you can design and reorder the sections of SOS filters, FDATool provides the ability to view the filter sections in the analysis area — SOS View. Once you have a second-order section filter as your current filter in FDATool, you turn on the SOS View option to see the filter sections individually, or cumulatively, or even only some of the sections. Enabling SOS View puts FDATool in a mode where all second-order section filters display sections until you disable the SOS View option. SOS View mode applies to any analysis you display in the analysis area. For example, if you configure FDATool to show the phase responses for filters, enabling SOS View means FDATool displays the phase response for each section of SOS filters. Controls on the SOS View Dialog Box 4-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software SOS View uses a few options to control how FDATool displays the sections, or which sections to display. When you select View > SOS View from the FDATool menu bar, you see this dialog box containing options to configure SOS View operation. By default, SOS View shows the overall response of SOS filters. Options in the SOS View dialog box let you change the display. This table lists all the options and describes the effects of each. Option Description Overall Filter This is the familiar display in FDATool. For a secondorder section filter you see only the overall response rather than the responses for the individual sections. This is the default configuration. Individual sections When you select this option, FDATool displays the response for each section as a curve. If your filter has five sections you see five response curves, one for each section, and they are independent. Compare to Cumulative sections. Cumulative sections When you select this option, FDATool displays the response for each section as the accumulated response of all prior sections in the filter. If your filter has five sections you see five response curves: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-43 4 Filter Analysis, Design, and Implementation Option Description • The first curve plots the response for the first filter section. • The second curve plots the response for the combined first and second sections. • The third curve plots the response for the first, second, and third sections combined. And so on until all filter sections appear in the display. The final curve represents the overall filter response. Compare to Cumulative sections and Overall Filter. User defined Here you define which sections to display, and in which order. Selecting this option enables the text box where you enter a cell array of the indices of the filter sections. Each index represents one section. Entering one index plots one response. Entering something like {1:2} plots the combined response of sections 1 and 2. If you have a filter with four sections, the entry {1:4} plots the combined response for all four sections, whereas {1,2,3,4} plots the response for each section. Note that after you enter the cell array, you need to click OK or Apply to update the FDATool analysis area to the new SOS View configuration. Use secondary-scaling points This directs FDATool to use the secondary scaling points in the sections to determine where to split the sections. This option applies only when the filter is a df2sos or df1tsos filter. For these structures, the secondary scaling points refer to the scaling locations between the recursive and the nonrecursive parts of the section (the "middle" of the section). By default, secondary-scaling points is not enabled. You use this with the Cumulative sections option only. View the Sections of SOS Filters After you design or import an SOS filter in to FDATool, the SOS view option lets you see the per section performance of your filter. Enabling SOS View from the View menu in 4-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software FDATool configures the tool to display the sections of SOS filters whenever the current filter is an SOS filter. These next steps demonstrate using SOS View to see your filter sections displayed in FDATool. 1 Launch FDATool. 2 Create a lowpass SOS filter using the Butterworth design method. Specify the filter order to be 6. Using a low order filter makes seeing the sections more clear. 3 Design your new filter by clicking Design Filter. FDATool design your filter and show you the magnitude response in the analysis area. In Current Filter Information you see the specifications for your filter. You should have a sixth-order Direct-Form II, Second-Order Sections filter with three sections. 4 To enable SOS View, select View > SOS View from the menu bar. By default the analysis area in FDATool shows the overall filter response, not the individual filter section responses. This dialog box lets you change the display configuration to see the sections. 5 To see the magnitude responses for each filter section, select Individual sections. 6 Click Apply to update FDATool to display the responses for each filter section. The analysis area changes to show you something like the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-45 4 Filter Analysis, Design, and Implementation If you switch FDATool to display filter phase responses (by selecting Analysis > Phase Response), you see the phase response for each filter section in the analysis area. 7 To define your own display of the sections, you use the User defined option and enter a vector of section indices to display. Now you see a display of the first section response, and the cumulative first, second, and third sections response: • Select User defined to enable the text entry box in the dialog box. • Enter the cell array {1,1:3} to specify that FDATool should display the response of the first section and the cumulative response of the first three sections of the filter. 8 To apply your new SOS View selection, click Apply or OK (which closes the SOS View dialog box). In the FDATool analysis area you see two curves — one for the response of the first filter section and one for the combined response of sections 1, 2, and 3. 4-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Import and Export Quantized Filters • “Overview and Structures” on page 4-47 • “Import Quantized Filters” on page 4-48 • “To Export Quantized Filters” on page 4-50 Overview and Structures When you import a quantized filter into FDATool, or export a quantized filter from FDATool to your workspace, the import and export functions use objects and you specify the filter as a variable. This contrasts with importing and exporting nonquantized filters, where you select the filter structure and enter the filter numerator and denominator for the filter transfer function. You have the option of exporting quantized filters to your MATLAB workspace, exporting them to text files, or exporting them to MAT-files. For general information about importing and exporting filters in FDATool, refer to “Importing a Filter Design”, and “Exporting a Filter Design”. FDATool imports quantized filters having the following structures: • Direct form I www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-47 4 Filter Analysis, Design, and Implementation • Direct form II • Direct form I transposed • Direct form II transposed • Direct form symmetric FIR • Direct form antisymmetric FIR • Lattice allpass • Lattice AR • Lattice MA minimum phase • Lattice MA maximum phase • Lattice ARMA • Lattice coupled-allpass • Lattice coupled-allpass power complementary Import Quantized Filters After you design or open a quantized filter in your MATLAB workspace, FDATool lets you import the filter for analysis. Follow these steps to import your filter in to FDATool: 1 Open FDATool. 2 Select File > Import Filter from Workspace from the menu bar, or choose the Import Filter from Workspace icon in the side panel: . In the lower region of FDATool, the Design Filter pane becomes Import Filter, and options appear for importing quantized filters, as shown. 4-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software 3 From the Filter Structure list, select Filter object. The options for importing filters change to include: • Discrete filter — Enter the variable name for the discrete-time, fixed-point filter in your workspace. • Frequency units — Select the frequency units from the Units list under Sampling Frequency, and specify the sampling frequency value in Fs if needed. Your sampling frequency must correspond to the units you select. For example, when you select Normalized (0 to 1), Fs defaults to one. But if you choose one of the frequency options, enter the sampling frequency in your selected units. If you have the sampling frequency defined in your workspace as a variable, enter the variable name for the sampling frequency. 4 Click Import to import the filter. FDATool checks your workspace for the specified filter. It imports the filter if it finds it, displaying the magnitude response for the filter in the analysis area. If it cannot find the filter it returns an FDATool Error dialog box. Note: If, during any FDATool session, you switch to quantization mode and create a fixed-point filter, FDATool remains in quantization mode. If you import a doubleprecision filter, FDATool automatically quantizes your imported filter applying the most recent quantization parameters. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-49 4 Filter Analysis, Design, and Implementation When you check the current filter information for your imported filter, it will indicate that the filter is Source: imported (quantized) even though you did not import a quantized filter. To Export Quantized Filters To save your filter design, FDATool lets you export the quantized filter to your MATLAB workspace (or you can save the current session in FDATool). When you choose to save the quantized filter by exporting it, you select one of these options: • Export to your MATLAB workspace • Export to a text file • Export to a MAT-file Export Coefficients, Objects, or System Objects to the Workspace You can save the filter as filter coefficients variables, dfilt filter object variables, or System object variables. To save the filter to the MATLAB workspace: 1 Select Export from the File menu. The Export dialog box appears. 2 Select Workspace from the Export To list. 3 From the Export As list, select one of the following options: • Select Coefficients to save the filter coefficients. • Select Objects to save the filter in a filter object. • Select System Objects to save the filter in a filter System object. The System Objects option does not appear in the drop-down list when the current filter structure is not supported by System objects. 4 Assign a variable name: • For coefficients, assign variable names using the Numerator and Denominator options under Variable Names. • For objects or System objects, assign the variable name in the Discrete Filter option. 4-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software If you have variables with the same names in your workspace and you want to overwrite them, select the Overwrite Variables box. 5 Click Export. Do not try to export the filter to a variable name that exists in your workspace without selecting Overwrite existing variables, in the previous step. If you do so, FDATool stops the export operation. The tool returns a warning that the variable you specified as the quantized filter name already exists in the workspace. • To continue to export the filter to the existing variable, click OK to dismiss the warning. • Then select the Overwrite existing variables check box and click Export. Getting Filter Coefficients After Exporting To extract the filter coefficients from your quantized filter after you export the filter to MATLAB, use the celldisp function in MATLAB. For example, create a quantized filter in FDATool, and export the filter as Hq. To extract the filter coefficients for Hq, use celldisp(Hq.referencecoefficients) which returns the cell array containing the filter reference coefficients, or celldisp(Hq.quantizedcoefficients to return the quantized coefficients. Export Filter Coefficients as a Text File To save your quantized filter as a text file, follow these steps: 1 Select Export from the File menu. 2 Select Text-file under Export to. 3 Click OK to export the filter and close the dialog box. Click Apply to export the filter without closing the Export dialog box. Clicking Apply lets you export your quantized filter to more than one name without leaving the Export dialog box. The Export Filter Coefficients to Text-file dialog box appears. This is the standard Microsoft Windows® save file dialog box. 4 Choose or enter a folder and filename for the text file, and click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-51 4 Filter Analysis, Design, and Implementation FDATool exports your quantized filter as a text file with the name you provided, and the MATLAB editor opens, displaying the file for editing. Export Filter Coefficients as a MAT-File To save your quantized filter as a MAT-file, follow these steps: 1 2 3 4 Select Export from the File menu. Select MAT-file under Export to. Assign a variable name for the filter. Click OK to export the filter and close the dialog box. Click Apply to export the filter without closing the Export dialog box. Clicking Apply lets you export your quantized filter to more than one name without leaving the Export dialog box. The Export Filter Coefficients to MAT-file dialog box appears. This dialog box is the standard Microsoft Windows save file dialog box. 5 Choose or enter a folder and filename for the text file, and click OK. FDATool exports your quantized filter as a MAT-file with the specified name. Generate MATLAB Code You can generate MATLAB code using the File > Generate MATLAB Code menu. This menu has three options: • Filter Design Function This option creates MATLAB code that generates the DFILT/MFILT object currently designed in FDATool. • Filter Design Function (with System Objects) This option is similar to the previous option with the difference that a System object is generated instead of a DFILT/MFILT object. The option is disabled when the current filter is not supported by system objects. • Data Filtering Function (with System Objects) This option generates MATLAB code that filters input data with the current filter design. The MATLAB code is ready to be converted to C/C++ code using the codegen command. This option is disabled when the current filter is not supported by system objects. 4-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Import XILINX Coefficient (.COE) Files Import XILINX .COE Files into FDATool You can import XILINX coefficients (.coe) files into FDATool to create quantized filters directly using the imported filter coefficients. To use the import file feature: 1 Select File > Import Filter From XILINX Coefficient (.COE) File in FDATool. 2 In the Import Filter From XILINX Coefficient (.COE) File dialog box, find and select the .coe file to import. 3 Click Open to dismiss the dialog box and start the import process. FDATool imports the coefficient file and creates a quantized, single-section, directform FIR filter. Transform Filters Using FDATool • “Filter Transformation Capabilities of FDATool” on page 4-53 • “Original Filter Type” on page 4-54 • “Frequency Point to Transform” on page 4-57 • “Transformed Filter Type” on page 4-58 • “Specify Desired Frequency Location” on page 4-59 Filter Transformation Capabilities of FDATool The toolbox provides functions for transforming filters between various forms. When you use FDATool with the toolbox installed, a side bar button and a menu bar option enable you to use the Transform Filter panel to transform filters as well as using the command line functions. From the selection on the FDATool menu bar — Transformations — you can transform lowpass FIR and IIR filters to a variety of passband shapes. You can convert your FIR filters from: • Lowpass to lowpass. • Lowpass to highpass. For IIR filters, you can convert from: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-53 4 Filter Analysis, Design, and Implementation • Lowpass to lowpass. • Lowpass to highpass. • Lowpass to bandpass. • Lowpass to bandstop. When you click the Transform Filter button, Filter panel opens in FDATool, as shown here. , on the side bar, the Transform Your options for Original filter type refer to the type of your current filter to transform. If you select lowpass, you can transform your lowpass filter to another lowpass filter or to a highpass filter, or to numerous other filter formats, real and complex. Note: When your original filter is an FIR filter, both the FIR and IIR transformed filter type options appear on the Transformed filter type list. Both options remain active because you can apply the IIR transforms to an FIR filter. If your source is as IIR filter, only the IIR transformed filter options show on the list. Original Filter Type Select the magnitude response of the filter you are transforming from the list. Your selection changes the types of filters you can transform to. For example: • When you select Lowpass with an IIR filter, your transformed filter type can be • Lowpass • Highpass 4-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) • When you select Lowpass with an FIR filter, your transformed filter type can be • Lowpass • Lowpass (FIR) • Highpass • Highpass (FIR) narrowband • Highpass (FIR) wideband • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) In the following table you see each available original filter type and all the types of filter to which you can transform your original. Original Filter Available Transformed Filter Types Lowpass FIR • Lowpass • Lowpass (FIR) • Highpass • Highpass (FIR) narrowband • Highpass (FIR) wideband • Bandpass • Bandstop • Multiband www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-55 4 Filter Analysis, Design, and Implementation Original Filter Available Transformed Filter Types • Bandpass (complex) • Bandstop (complex) • Multiband (complex) Lowpass IIR • Lowpass • Highpass • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) Highpass FIR • Lowpass • Lowpass (FIR) narrowband • Lowpass (FIR) wideband • Highpass (FIR) • Highpass • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) 4-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Original Filter Available Transformed Filter Types Highpass IIR • Lowpass • Highpass • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) Bandpass FIR • Bandpass • Bandpass (FIR) Bandpass IIR Bandpass Bandstop FIR • Bandstop • Bandstop (FIR) Bandstop IIR Bandstop Note also that the transform options change depending on whether your original filter is FIR or IIR. Starting from an FIR filter, you can transform to IIR or FIR forms. With an IIR original filter, you are limited to IIR target filters. After selecting your response type, use Frequency point to transform to specify the magnitude response point in your original filter to transfer to your target filter. Your target filter inherits the performance features of your original filter, such as passband ripple, while changing to the new response form. For more information about transforming filters, refer to “Frequency Transformations for Real Filters” on page 4-85 and “Frequency Transformations for Complex Filters” on page 4-99. Frequency Point to Transform The frequency point you enter in this field identifies a magnitude response value (in dB) on the magnitude response curve. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-57 4 Filter Analysis, Design, and Implementation When you enter frequency values in the Specify desired frequency location option, the frequency transformation tries to set the magnitude response of the transformed filter to the value identified by the frequency point you enter in this field. While you can enter any location, generally you should specify a filter passband or stopband edge, or a value in the passband or stopband. The Frequency point to transform sets the magnitude response at the values you enter in Specify desired frequency location. Specify a value that lies at either the edge of the stopband or the edge of the passband. If, for example, you are creating a bandpass filter from a highpass filter, the transformation algorithm sets the magnitude response of the transformed filter at the Specify desired frequency location to be the same as the response at the Frequency point to transform value. Thus you get a bandpass filter whose response at the low and high frequency locations is the same. Notice that the passband between them is undefined. In the next two figures you see the original highpass filter and the transformed bandpass filter. For more information about transforming filters, refer to “Digital Frequency Transformations” on page 4-77. Transformed Filter Type Select the magnitude response for the target filter from the list. The complete list of transformed filter types is: • Lowpass • Lowpass (FIR) • Highpass • Highpass (FIR) narrowband • Highpass (FIR) wideband • Bandpass • Bandstop • Multiband • Bandpass (complex) • Bandstop (complex) • Multiband (complex) 4-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Not all types of transformed filters are available for all filter types on the Original filter types list. You can transform bandpass filters only to bandpass filters. Or bandstop filters to bandstop filters. Or IIR filters to IIR filters. For more information about transforming filters, refer to “Frequency Transformations for Real Filters” on page 4-85 and “Frequency Transformations for Complex Filters” on page 4-99. Specify Desired Frequency Location The frequency point you enter in Frequency point to transform matched a magnitude response value. At each frequency you enter here, the transformation tries to make the magnitude response the same as the response identified by your Frequency point to transform value. While you can enter any location, generally you should specify a filter passband or stopband edge, or a value in the passband or stopband. For more information about transforming filters, refer to “Digital Frequency Transformations” on page 4-77. Transform Filters To transform the magnitude response of your filter, use the Transform Filter option on the side bar. 1 2 Design or import your filter into FDATool. Click Transform Filter, , on the side bar. FDATool opens the Transform Filter panel in FDATool. 3 From the Original filter type list, select the response form of the filter you are transforming. When you select the type, whether is lowpass, highpass, bandpass, or bandstop, FDATool recognizes whether your filter form is FIR or IIR. Using both your filter type selection and the filter form, FDATool adjusts the entries on the Transformed filter type list to show only those that apply to your original filter. 4 Enter the frequency point to transform value in Frequency point to transform. Notice that the value you enter must be in kHz; for example, enter 0.1 for 100 Hz or 1.5 for 1500 Hz. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-59 4 Filter Analysis, Design, and Implementation 5 From the Transformed filter type list, select the type of filter you want to transform to. Your filter type selection changes the options here. • When you pick a lowpass or highpass filter type, you enter one value in Specify desired frequency location. • When you pick a bandpass or bandstop filter type, you enter two values — one in Specify desired low frequency location and one in Specify desired high frequency location. Your values define the edges of the passband or stopband. • When you pick a multiband filter type, you enter values as elements in a vector in Specify a vector of desired frequency locations — one element for each desired location. Your values define the edges of the passbands and stopbands. After you click Transform Filter, FDATool transforms your filter, displays the magnitude response of your new filter, and updates the Current Filter Information to show you that your filter has been transformed. In the filter information, the Source is Transformed. For example, the figure shown here includes the magnitude response curves for two filters. The original filter is a lowpass filter with rolloff between 0.2 and 0.25. The transformed filter is a lowpass filter with rolloff region between 0.8 and 0.85. 4-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Magnitude Response 20 0 Magnitude (dB) −20 −40 −60 −80 −100 Filter #1: Original Lowpass filter response Filter #2: Transformed Lowpass Filter Response −120 0 0.1 0.2 0.3 0.4 0.5 0.6 Normalized Frequency (×π rad/sample) 0.7 0.8 0.9 1 • To demonstrate the effects of selecting Narrowband Highpass or Wideband Highpass, the next figure presents the magnitude response curves for a source lowpass filter after it is transformed to both narrow- and wideband highpass filters. For comparison, the response of the original filter appears as well. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-61 4 Filter Analysis, Design, and Implementation Magnitude Response 20 0 Magnitude (dB) −20 −40 −60 −80 −100 −120 Filter #1:Original Lowpass Filter Response Filter #2:Narrowband Highpass Filter Response Filter #3: Wideband Highpass Filter Response 0 0.1 0.2 0.3 0.4 0.5 0.6 Normalized Frequency (×π rad/sample) 0.7 0.8 0.9 1 For the narrowband case, the transformation algorithm essentially reverses the magnitude response, like reflecting the curve around the y-axis, then translating the curve to the right until the origin lies at 1 on the x-axis. After reflecting and translating, the passband at high frequencies is the reverse of the passband of the original filter at low frequencies with the same rolloff and ripple characteristics. Design Multirate Filters in FDATool • “Introduction” on page 4-63 • “Switch FDATool to Multirate Filter Design Mode” on page 4-63 • “Controls on the Multirate Design Panel” on page 4-64 • “Quantize Multirate Filters” on page 4-71 • “Export Individual Phase Coefficients of a Polyphase Filter to the Workspace” on page 4-73 4-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software Introduction Not only can you design multirate filters from the MATLAB command prompt, FDATool provides the same design capability in a graphical user interface tool. By starting FDATool and switching to the multirate filter design mode you have access to all of the multirate design capabilities in the toolbox — decimators, interpolators, and fractional rate changing filters, among others. Switch FDATool to Multirate Filter Design Mode The multirate filter design mode in FDATool lets you specify and design a wide range of multirate filters, including decimators and interpolators. With FDATool open, click Create a Multirate Filter, , on the side bar. You see FDATool switch to the design mode showing the multirate filter design options. Shown in the following figure is the default multirate design configuration that designs an interpolating filter with an interpolation factor of 2. The design uses the current FIR filter in FDATool. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-63 4 Filter Analysis, Design, and Implementation When the current filter in FDATool is not an FIR filter, the multirate filter design panel removes the Use current FIR filter option and selects the Use default Nyquist FIR filter option instead as the default setting. Controls on the Multirate Design Panel You see the options that allow you to design a variety of multirate filters. The Type option is your starting point. From this list you select the multirate filter to design. Based on your selection, other options change to provide the controls you need to specify your filter. Notice the separate sections of the design panel. On the left is the filter type area where you choose the type of multirate filter to design and set the filter performance specifications. In the center section FDATool provides choices that let you pick the filter design method to use. 4-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software The rightmost section offers options that control filter configuration when you select Cascaded-Integrator Comb (CIC) as the design method in the center section. Both the Decimator type and Interpolator type filters let you use the Cascaded-Integrator Comb (CIC) option to design multirate filters. Here are all the options available when you switch to multirate filter design mode. Each option listed includes a brief description of what the option does when you use it. Select and Configure Your Filter Option Description Type Specifies the type of multirate filter to design. Choose from Decimator, Interpolator, or Fractional-rate convertor. • When you choose Decimator, set Decimation Factor to specify the decimation to apply. • When you choose Interpolator, set Interpolation Factor to specify the interpolation amount applied. • When you choose Fractional-rate convertor, set both Interpolation Factor and Decimation Factor. FDATool uses both to determine the fractional rate change by dividing Interpolation Factor by Decimation Factor to determine the fractional rate change in the signal. You should select values for interpolation and decimation that are relatively prime. When your interpolation factor and decimation factor are not relatively prime, FDATool reduces the interpolation/decimation fractional rate to the lowest common denominator and issues a message in the status bar in FDATool. For example, if the interpolation factor is 6 and the decimation factor is 3, FDATool reduces 6/3 to 2/1 when you design the rate changer. But if the interpolation factor is 8 and the decimation factor is 3, FDATool designs the filter without change. Interpolation Factor Use the up-down control arrows to specify the amount of interpolation to apply to the signal. Factors range upwards from 2. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-65 4 Filter Analysis, Design, and Implementation Option Description Decimation Factor Use the up-down control arrows to specify the amount of decimation to apply to the signal. Factors range upwards from 2. Sampling Frequency No settings here. Just Units and Fs below. Units Specify whether Fs is specified in Hz, kHz, MHz, GHz, or Normalized (0 to 1) units. Fs Set the full scale sampling frequency in the frequency units you specified in Units. When you select Normalized for Units, you do not enter a value for Fs. Design Your Filter 4-66 Option Description Use current FIR filter Directs FDATool to use the current FIR filter to design the multirate filter. If the current filter is an IIR form, you cannot select this option. You cannot design multirate filters with IIR structures. Use a default Nyquist Filter Tells FDATool to use the default Nyquist design method when the current filter in FDATool is not an FIR filter. Cascaded IntegratorComb (CIC) Design CIC filters using the options provided in the righthand area of the multirate design panel. Hold Interpolator (Zero-order) When you design an interpolator, you can specify how the filter sets interpolated values between signal values. When you select this option, the interpolator applies the most recent signal value for each interpolated value until it processes the next signal value. This is similar to sampleand-hold techniques. Compare to the Linear Interpolator option. Linear Interpolator (First-order) When you design an interpolator, you can specify how the filter sets interpolated values between signal values. When you select this option, the interpolator applies linear interpolation between signal value to set the interpolated value until it processes the next signal value. Compare to the Linear Interpolator option. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software To see the difference between hold interpolation and linear interpolation, the following figure presents a sine wave signal s1 in three forms: • The top subplot in the figure presents signal s1 without interpolation. • The middle subplot shows signal s1 interpolated by a linear interpolator with an interpolation factor of 5. • The bottom subplot shows signal s1 interpolated by a hold interpolator with an interpolation factor of 5. You see in the bottom figure the sample and hold nature of hold interpolation, and the first-order linear interpolation applied by the linear interpolator. Uninterpolated Signal s1 1 0.5 0 −0.5 −1 1 2 3 4 5 6 7 8 9 10 40 45 50 40 45 50 First−Order Linear Interpolation By 5 of Signal s1 1 0.5 0 −0.5 −1 0 5 10 15 20 25 30 35 Zero−Order Hold Interpolation By 5 of Signal s1 1 0.5 0 −0.5 −1 0 5 10 15 20 25 Samples 30 35 We used FDATool to create interpolators similar to the following code for the figure: • Linear interpolator — hm=mfilt.linearinterp(5) • Hold interpolator — hm=mfilt.holdinterp(5) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-67 4 Filter Analysis, Design, and Implementation Options for Designing CIC Filters Description Differential Delay Sets the differential delay for the CIC filter. Usually a value of one or two is appropriate. Number of Sections Specifies the number of sections in a CIC decimator. The default number of sections is 2 and the range is any positive integer. Design a Fractional Rate Convertor To introduce the process you use to design a multirate filter in FDATool, this example uses the options to design a fractional rate convertor which uses 7/3 as the fractional rate. Begin the design by creating a default lowpass FIR filter in FDATool. You do not have to begin with this FIR filter, but the default filter works fine. 1 Launch FDATool. 2 Select the settings for a minimum-order lowpass FIR filter, using the Equiripple design method. 3 When FDATool displays the magnitude response for the filter, click in the side bar. FDATool switches to multirate filter design mode, showing the multirate design panel. 4 To design a fractional rate filter, select Fractional-rate convertor from the Type list. The Interpolation Factor and Decimation Factor options become available. 5 In Interpolation Factor, use the up arrow to set the interpolation factor to 7. 6 Using the up arrow in Decimation Factor, set 3 as the decimation factor. 7 Select Use a default Nyquist FIR filter. You could design the rate convertor with the current FIR filter as well. 8 Enter 24000 to set Fs. 9 Click Create Multirate Filter. After designing the filter, FDATool returns with the specifications for your new filter displayed in Current Filter Information, and shows the magnitude response of the filter. 4-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software You can test the filter by exporting it to your workspace and using it to filter a signal. For information about exporting filters, refer to “Import and Export Quantized Filters” on page 4-47. Design a CIC Decimator for 8 Bit Input/Output Data Another kind of filter you can design in FDATool is Cascaded-Integrator Comb (CIC) filters. FDATool provides the options needed to configure your CIC to meet your needs. 1 2 Launch FDATool and design the default FIR lowpass filter. Designing a filter at this time is an optional step. Switch FDATool to multirate design mode by clicking on the side bar. 3 For Type, select Decimator, and set Decimation Factor to 3. 4 To design the decimator using a CIC implementation, select Cascaded-Integrator Comb (CIC). This enables the CIC-related options on the right of the panel. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-69 4 Filter Analysis, Design, and Implementation 5 Set Differential Delay to 2. Generally, 1 or 2 are good values to use. 6 Enter 2 for the Number of Sections. 7 Click Create Multirate Filter. FDATool designs the filter, shows the magnitude response in the analysis area, and updates the current filter information to show that you designed a tenth-order cascaded-integrator comb decimator with two sections. Notice the source is Multirate Design, indicating you used the multirate design mode in FDATool to make the filter. FDATool should look like this now. Designing other multirate filters follows the same pattern. To design other multirate filters, do one of the following depending on the filter to design: 4-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software • To design an interpolator, select one of these options. • Use a default Nyquist FIR filter • Cascaded-Integrator Comb (CIC) • Hold Interpolator (Zero-order) • Linear Interpolator (First-order) • To design a decimator, select from these options. • Use a default Nyquist FIR filter • Cascaded-Integrator Comb (CIC) • To design a fractional-rate convertor, select Use a default Nyquist FIR filter. Quantize Multirate Filters After you design a multirate filter in FDATool, the quantization features enable you to convert your floating-point multirate filter to fixed-point arithmetic. Note: CIC filters are always fixed-point. With your multirate filter as the current filter in FDATool, you can quantize your filter and use the quantization options to specify the fixed-point arithmetic the filter uses. Quantize and Configure Multirate Filters Follow these steps to convert your multirate filter to fixed-point arithmetic and set the fixed-point options. 1 Design or import your multirate filter and make sure it is the current filter in FDATool. 2 Click the Set Quantization Parameters button on the side bar. 3 From the Filter Arithmetic list on the Filter Arithmetic pane, select Fixedpoint. If your filter is a CIC filter, the Fixed-point option is enabled by default and you do not set this option. 4 In the quantization panes, set the options for your filter. Set options for Coefficients, Input/Output, and Filter Internals. 5 Click Apply. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-71 4 Filter Analysis, Design, and Implementation When you current filter is a CIC filter, the options on the Input/Output and Filter Internals panes change to provide specific features for CIC filters. Input/Output The options that specify how your CIC filter uses input and output values are listed in the table below. Option Name Description Input Word Length Sets the word length used to represent the input to a filter. Input fraction length Sets the fraction length used to interpret input values to filter. Input range (+/-) Lets you set the range the inputs represent. You use this instead of the Input fraction length option to set the precision. When you enter a value x, the resulting range is x to x. Range must be a positive integer. Output word length Sets the word length used to represent the output from a filter. Avoid overflow Directs the filter to set the fraction length for the input to prevent the output values from exceeding the available range as defined by the word length. Clearing this option lets you set Output fraction length. Output fraction length Sets the fraction length used to represent output values from a filter. Output range (+/-) Lets you set the range the outputs represent. You use this instead of the Output fraction length option to set the precision. When you enter a value x, the resulting range is x to x. Range must be a positive integer. The available options change when you change the Filter precision setting. Moving from Full to Specify all adds increasing control by enabling more input and output word options. Filter Internals With a CIC filter as your current filter, the Filter precision option on the Filter Internals pane includes modes for controlling the filter word and fraction lengths. There are four usage modes for this (the same mode you select for the FilterInternals property in CIC filters at the MATLAB prompt). 4-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use FDATool with DSP System Toolbox Software • Full — All word and fraction lengths set to Bmax + 1, called Baccum by Harris in [2]. Full Precision is the default setting. • Minimum section word lengths — Set the section word lengths to minimum values that meet roundoff noise and output requirements as defined by Hogenauer in [3]. • Specify word lengths — Enables the Section word length option for you to enter word lengths for each section. Enter either a scalar to use the same value for every section, or a vector of values, one for each section. • Specify all — Enables the Section fraction length option in addition to Section word length. Now you can provide both the word and fraction lengths for each section, again using either a scalar or a vector of values. Export Individual Phase Coefficients of a Polyphase Filter to the Workspace After designing a polyphase filter in Filter Design Analysis Tool (FDATool), you can obtain the individual phase coefficients of the filter by: 1 Exporting the filter to an object in the MATLAB workspace. 2 Using the polyphase method to create a matrix of the filter's coefficients. Export the Polyphase Filter to an Object To export a polyphase filter to an object in the MATLAB workspace, complete the following steps. 1 In FDATool, open the File menu and select Export.... This opens the dialog box for exporting the filter coefficients. 2 In the Export dialog box, for Export To, select Workspace. 3 For Export As, select Object. 4 (Optional) For Variable Names, enter the name of the Multirate Filter object that will be created in the MATLAB workspace. 5 Click the Export button. The multirate filter object, Hm in this example, appears in the MATLAB workspace. Create a Matrix of Coefficients Using the polyphase Method To create a matrix of the filter's coefficients, enter p=polyphase(Hm) at the command line. The polyphase method creates a matrix, p, of filter coefficients from the filter www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-73 4 Filter Analysis, Design, and Implementation object, Hm. Each row of p consists of the coefficients of an individual phase subfilter. The first row contains to the coefficients of the first phase subfilter, the second row contains those of the second phase subfilter, and so on. Realize Filters as Simulink Subsystem Blocks • “Introduction” on page 4-74 • “About the Realize Model Panel in FDATool” on page 4-74 Introduction After you design or import a filter in FDATool, the realize model feature lets you create a Simulink subsystem block that implements your filter. The generated filter subsystem block uses either digital filter blocks from the DSP System Toolbox library, or the Delay, Gain, and Sum blocks in Simulink. If you do not have a Fixed-Point Designer™ license, FDATool still realizes your model using blocks in fixed-point mode from Simulink, but you cannot run any model that includes your filter subsystem block in Simulink. About the Realize Model Panel in FDATool To access to the Realize Model panel and the options for realizing your quantized filter as a Simulink subsystem block, switch FDATool to realize model mode by clicking the sidebar. The following panel shows the options for configuring how FDATool implements your filter as a Simulink block. 4-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان on Use FDATool with DSP System Toolbox Software For information on these parameters, see the descriptions on the “Filter Realization Wizard” block reference page. Realize a Filter Using FDATool After your quantized filter in FDATool is performing the way you want, with your desired phase and magnitude response, and with the right coefficients and form, follow these steps to realize your filter as a subsystem that you can use in a Simulink model. 1 2 Click Realize Model on the sidebar to change FDATool to realize model mode. From the Destination list under Model, select either: • Current model — to add the realized filter subsystem to your current model • New model — to open a new Simulink model window and add your filter subsystem to the new window 3 4 Provide a name for your new filter subsystem in the Name field. Decide whether to overwrite an existing block with this new one, and select or clear the Overwrite generated ‘Filter’ block check box. 5 Select the Build model using basic elements check box to implement your filter as a subsystem block that consists of Sum, Gain, and Delay blocks. 6 Select or clear the optimizations to apply. • Optimize for zero gains — removes zero gain blocks from the model realization • Optimize for unity gains — replaces unity gain blocks with direct connections to adjacent blocks • Optimize for negative gains — replaces negative gain blocks by a change of sign at the nearest sum block • Optimize delay chains — replaces cascaded delay blocks with a single delay block that produces the equivalent gain • Optimize for unity scale values — removes all scale value multiplications by 1 from the filter structure 7 Click Realize Model to realize your quantized filter as a subsystem block according to the settings you selected. If you double-click the filter block subsystem created by FDATool, you see the filter implementation in Simulink model form. Depending on the options you chose when you realized your filter, and the filter you started with, you might see one or more sections, or different architectures based on the form of your quantized filter. From this point on, the subsystem filter block acts like any other block that you use in Simulink models. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-75 4 Filter Analysis, Design, and Implementation Supported Filter Structures FDATool lets you realize discrete-time and multirate filters from the following forms: 4-76 Structure Description firdecim Decimators based on FIR filters firtdecim Decimators based on transposed FIR filters linearinterp Linear interpolators firinterp Interpolators based on FIR filters multirate polyphase Multirate filters holdinterp Interpolators that use the hold interpolation algorithm dfilt.allpass Discrete-time filters with allpass structure dfilt.cascadeallpass dfilt.cascadewdfallpass mfilt.iirdecim Decimators based on IIR filters mfilt.iirwdfdecim mfilt.iirinterp Interpolators based on IIR filters mfilt.iirwdfinterp dfilt.wdfallpass www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Digital Frequency Transformations In this section... “Details and Methodology” on page 4-77 “Frequency Transformations for Real Filters” on page 4-85 “Frequency Transformations for Complex Filters” on page 4-99 Details and Methodology • “Overview of Transformations” on page 4-77 • “Select Features Subject to Transformation” on page 4-81 • “Mapping from Prototype Filter to Target Filter” on page 4-83 • “Summary of Frequency Transformations” on page 4-84 Overview of Transformations Converting existing FIR or IIR filter designs to a modified IIR form is often done using allpass frequency transformations. Although the resulting designs can be considerably more expensive in terms of dimensionality than the prototype (original) filter, their ease of use in fixed or variable applications is a big advantage. The general idea of the frequency transformation is to take an existing prototype filter and produce another filter from it that retains some of the characteristics of the prototype, in the frequency domain. Transformation functions achieve this by replacing each delaying element of the prototype filter with an allpass filter carefully designed to have a prescribed phase characteristic for achieving the modifications requested by the designer. The basic form of mapping commonly used is HT ( z) = H o[ H A ( z)] The HA(z) is an Nth-order allpass mapping filter given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-77 4 Filter Analysis, Design, and Implementation N ∑ ai z −i N ( z) H A ( z) = S Ni = 0 = A DA ( z) ai z − N + i ∑ a0 = 1 i= 0 where Ho(z) — Transfer function of the prototype filter HA(z) — Transfer function of the allpass mapping filter HT(z) — Transfer function of the target filter Let's look at a simple example of the transformation given by HT ( z) = H o ( − z) The target filter has its poles and zeroes flipped across the origin of the real and imaginary axes. For the real filter prototype, it gives a mirror effect against 0.5, which means that lowpass Ho(z) gives rise to a real highpass HT(z). This is shown in the following figure for the prototype filter designed as a third-order halfband elliptic filter. 4-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Target filter 0 −10 −10 −20 −20 |H(ω)| in dB |H(ω)| in dB Prototype filter 0 −30 −40 −50 −60 −30 −40 −50 0 0.2 0.4 0.6 0.8 1 Normalized Frequency (×π rad/sample) −60 Prototype filter Pole−Zero plot 0 0.2 0.4 0.6 0.8 1 Normalized Frequency (×π rad/sample) Target filter Pole−Zero plot Example of a Simple Mirror Transformation The choice of an allpass filter to provide the frequency mapping is necessary to provide the frequency translation of the prototype filter frequency response to the target filter by changing the frequency position of the features from the prototype filter without affecting the overall shape of the filter response. The phase response of the mapping filter normalized to π can be interpreted as a translation function: H (wnew ) = w old The graphical interpretation of the frequency transformation is shown in the figure below. The complex multiband transformation takes a real lowpass filter and converts it into a number of passbands around the unit circle. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-79 4 Filter Analysis, Design, and Implementation Graphical Interpretation of the Mapping Process Most of the frequency transformations are based on the second-order allpass mapping filter: H A ( z) = ± 1 + a1 z−1 + a 2 z−2 a 2 + a1 z −1 + z −2 The two degrees of freedom provided by α1 and α2 choices are not fully used by the usual restrictive set of “flat-top” classical mappings like lowpass to bandpass. Instead, any two transfer function features can be migrated to (almost) any two other frequency locations if α1 and α2 are chosen so as to keep the poles of HA(z) strictly outside the unit circle (since HA(z) is substituted for z in the prototype transfer function). Moreover, as first pointed out by Constantinides, the selection of the outside sign influences whether the original feature at zero can be moved (the minus sign, a condition known as “DC mobility”) or whether the Nyquist frequency can be migrated (the “Nyquist mobility” case arising when the leading sign is positive). 4-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations All the transformations forming the package are explained in the next sections of the tutorial. They are separated into those operating on real filters and those generating or working with complex filters. The choice of transformation ranges from standard Constantinides first and second-order ones [1][2] up to the real multiband filter by Mullis and Franchitti [3], and the complex multiband filter and real/complex multipoint ones by Krukowski, Cain and Kale [4]. Select Features Subject to Transformation Choosing the appropriate frequency transformation for achieving the required effect and the correct features of the prototype filter is very important and needs careful consideration. It is not advisable to use a first-order transformation for controlling more than one feature. The mapping filter will not give enough flexibility. It is also not good to use higher order transformation just to change the cutoff frequency of the lowpass filter. The increase of the filter order would be too big, without considering the additional replica of the prototype filter that may be created in undesired places. Feature Selection for Real Lowpass to Bandpass Transformation To illustrate the idea, the second-order real multipoint transformation was applied three times to the same elliptic halfband filter in order to make it into a bandpass filter. In each of the three cases, two different features of the prototype filter were selected in order to obtain a bandpass filter with passband ranging from 0.25 to 0.75. The position of the DC feature was not important, but it would be advantageous if it were in the middle between the edges of the passband in the target filter. In the first case the selected www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-81 4 Filter Analysis, Design, and Implementation features were the left and the right band edges of the lowpass filter passband, in the second case they were the left band edge and the DC, in the third case they were DC and the right band edge. Magniture responses |H(ω)| in dB 0 −10 Left & right band−edges (solid) Left band−edge and DC (dashed) −20 DC and right band−edges (dotted) −30 −40 −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 Result of Choosing Different Features The results of all three approaches are completely different. For each of them only the selected features were positioned precisely where they were required. In the first case the DC is moved toward the left passband edge just like all the other features close to the left edge being squeezed there. In the second case the right passband edge was pushed way out of the expected target as the precise position of DC was required. In the third case the left passband edge was pulled toward the DC in order to position it at the correct frequency. The conclusion is that if only the DC can be anywhere in the passband, the edges of the passband should have been selected for the transformation. For most of the cases requiring the positioning of passbands and stopbands, designers should always choose the position of the edges of the prototype filter in order to make sure that they get the edges of the target filter in the correct places. Frequency responses for the three cases considered are shown in the figure. The prototype filter was a third-order elliptic lowpass filter with cutoff frequency at 0.5. 4-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations The MATLAB code used to generate the figure is given here. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); In the example the requirements are set to create a real bandpass filter with passband edges at 0.1 and 0.3 out of the real lowpass filter having the cutoff frequency at 0.5. This is attempted in three different ways. In the first approach both edges of the passband are selected, in the second approach the left edge of the passband and the DC are chosen, while in the third approach the DC and the right edge of the passband are taken: [num1,den1] = iirlp2xn(b, a, [-0.5, 0.5], [0.1, 0.3]); [num2,den2] = iirlp2xn(b, a, [-0.5, 0.0], [0.1, 0.2]); [num3,den3] = iirlp2xn(b, a, [ 0.0, 0.5], [0.2, 0.3]); Mapping from Prototype Filter to Target Filter In general the frequency mapping converts the prototype filter, Ho(z), to the target filter, HT(z), using the NAth-order allpass filter, HA(z). The general form of the allpass mapping filter is given in “Overview of Transformations” on page 4-77. The frequency mapping is a mathematical operation that replaces each delayer of the prototype filter with an allpass filter. There are two ways of performing such mapping. The choice of the approach is dependent on how prototype and target filters are represented. When the Nth-order prototype filter is given with pole-zero form N H o ( z) = ∑ (z − zi ) i =1 N ∑ (z − pi ) i =1 the mapping will replace each pole, pi, and each zero, zi, with a number of poles and zeros equal to the order of the allpass mapping filter: N H o ( z) = ∑ i =1 N ∑ i =1 N −1 N −1 k N−k S ∑ a k z − zi ⋅ ∑ a k z k =0 k= 0 N −1 N −1 S ∑ a k z k − pi ⋅ ∑ a k z N − k k =0 k= 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-83 4 Filter Analysis, Design, and Implementation The root finding needs to be used on the bracketed expressions in order to find the poles and zeros of the target filter. When the prototype filter is described in the numerator-denominator form: HT ( z) = b 0 z N + b1 z N −1 + … + b N a 0 z N + a1 z N −1 + … + a N z = H A ( z) Then the mapping process will require a number of convolutions in order to calculate the numerator and denominator of the target filter: b N ( z) N + b 2 N A ( z) N −1 DA ( z) + … + b N D A ( z) N HT ( z) = 1 A b1 N A ( z) N + b 2 N A ( z) N −1 DA ( z) + … + b N D A ( z) N For each coefficient αi and βi of the prototype filter the NAth-order polynomials must be convolved N times. Such approach may cause rounding errors for large prototype filters and/or high order mapping filters. In such a case the user should consider the alternative of doing the mapping using via poles and zeros. Summary of Frequency Transformations Advantages • Most frequency transformations are described by closed-form solutions or can be calculated from the set of linear equations. • They give predictable and familiar results. • Ripple heights from the prototype filter are preserved in the target filter. • They are architecturally appealing for variable and adaptive filters. Disadvantages • There are cases when using optimization methods to design the required filter gives better results. • High-order transformations increase the dimensionality of the target filter, which may give expensive final results. 4-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations • Starting from fresh designs helps avoid locked-in compromises. Frequency Transformations for Real Filters • “Overview” on page 4-85 • “Real Frequency Shift” on page 4-85 • “Real Lowpass to Real Lowpass” on page 4-87 • “Real Lowpass to Real Highpass” on page 4-89 • “Real Lowpass to Real Bandpass” on page 4-91 • “Real Lowpass to Real Bandstop” on page 4-93 • “Real Lowpass to Real Multiband” on page 4-95 • “Real Lowpass to Real Multipoint” on page 4-97 Overview This section discusses real frequency transformations that take the real lowpass prototype filter and convert it into a different real target filter. The target filter has its frequency response modified in respect to the frequency response of the prototype filter according to the characteristic of the applied frequency transformation. Real Frequency Shift Real frequency shift transformation uses a second-order allpass mapping filter. It performs an exact mapping of one selected feature of the frequency response into its new location, additionally moving both the Nyquist and DC features. This effectively moves the whole response of the lowpass filter by the distance specified by the selection of the feature from the prototype filter and the target filter. As a real transformation, it works in a similar way for positive and negative frequencies. −1 1−a z H A ( z) = z−1 ⋅ a − z−1 with α given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-85 4 Filter Analysis, Design, and Implementation p cos 2 (wold − 2wnew ) p for cos (wold − 2wnew ) < 1 p 2 cos wold 2 a = sin p (w − 2w ) new 2 ol d otherwise p w sin 2 old where ωold — Frequency location of the selected feature in the prototype filter ωnew — Position of the feature originally at ωold in the target filter The following example shows how this transformation can be used to move the response of the prototype lowpass filter in either direction. Please note that because the target filter must also be real, the response of the target filter will inherently be disturbed at frequencies close to Nyquist and close to DC. Here is the MATLAB code for generating the example in the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation moves the feature originally at 0.5 to 0.9: [num,den] = iirshift(b, a, 0.5, 0.9); 4-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 Example of Real Frequency Shift Mapping Real Lowpass to Real Lowpass Real lowpass filter to real lowpass filter transformation uses a first-order allpass mapping filter. It performs an exact mapping of one feature of the frequency response into the new location keeping DC and Nyquist features fixed. As a real transformation, it works in a similar way for positive and negative frequencies. It is important to mention that using first-order mapping ensures that the order of the filter after the transformation is the same as it was originally. 1 − a z −1 H A ( z) = − a − z −1 with α given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-87 4 Filter Analysis, Design, and Implementation p sin (wold − wnew ) 2 a = p sin (wold − wnew ) 2 where ωold — Frequency location of the selected feature in the prototype filter ωnew — Frequency location of the same feature in the target filter The example below shows how to modify the cutoff frequency of the prototype filter. The MATLAB code for this example is shown in the following figure. The prototype filter is a halfband elliptic, real, third-order filter: [b, a] = ellip(3, 0.1, 30, 0.409); The cutoff frequency moves from 0.5 to 0.75: [num,den] = iirlp2lp(b, a, 0.5, 0.75); 4-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.8 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) Example of Real Lowpass to Real Lowpass Mapping Real Lowpass to Real Highpass Real lowpass filter to real highpass filter transformation uses a first-order allpass mapping filter. It performs an exact mapping of one feature of the frequency response into the new location additionally swapping DC and Nyquist features. As a real transformation, it works in a similar way for positive and negative frequencies. Just like in the previous transformation because of using a first-order mapping, the order of the filter before and after the transformation is the same. 1 + a z −1 H A ( z) = − a + z−1 with α given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-89 4 Filter Analysis, Design, and Implementation p cos 2 (w old + wnew ) a = − p cos (wold − wnew ) 2 where ωold — Frequency location of the selected feature in the prototype filter ωnew — Frequency location of the same feature in the target filter The example below shows how to convert the lowpass filter into a highpass filter with arbitrarily chosen cutoff frequency. In the MATLAB code below, the lowpass filter is converted into a highpass with cutoff frequency shifted from 0.5 to 0.75. Results are shown in the figure. The prototype filter is a halfband elliptic, real, third-order filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example moves the cutoff frequency from 0.5 to 0.75: [num,den] = iirlp2hp(b, a, 0.5, 0.75); 4-90 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.8 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) Example of Real Lowpass to Real Highpass Mapping Real Lowpass to Real Bandpass Real lowpass filter to real bandpass filter transformation uses a second-order allpass mapping filter. It performs an exact mapping of two features of the frequency response into their new location additionally moving a DC feature and keeping the Nyquist feature fixed. As a real transformation, it works in a similar way for positive and negative frequencies. 1 − b (1 + a ) z−1 − a z−2 H A ( z) = − a − b (1 + a ) z −1 + z −2 with α and β given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-91 4 Filter Analysis, Design, and Implementation p sin ( 2w old − wnew,2 + wnew,1) 4 a = p sin ( 2w old + w new,2 − wnew,1) 4 p b = cos (wnew,1 + wnew,2 ) 2 where ωold — Frequency location of the selected feature in the prototype filter ωnew,1 — Position of the feature originally at (-ωold) in the target filter ωnew,2 — Position of the feature originally at (+ωold) in the target filter The example below shows how to move the response of the prototype lowpass filter in either direction. Please note that because the target filter must also be real, the response of the target filter will inherently be disturbed at frequencies close to Nyquist and close to DC. Here is the MATLAB code for generating the example in the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates the passband between 0.5 and 0.75: [num,den] = iirlp2bp(b, a, 0.5, [0.5, 0.75]); 4-92 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.8 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 0 0.1 0.2 ωt2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) Example of Real Lowpass to Real Bandpass Mapping Real Lowpass to Real Bandstop Real lowpass filter to real bandstop filter transformation uses a second-order allpass mapping filter. It performs an exact mapping of two features of the frequency response into their new location additionally moving a Nyquist feature and keeping the DC feature fixed. This effectively creates a stopband between the selected frequency locations in the target filter. As a real transformation, it works in a similar way for positive and negative frequencies. H A ( z) = 1 − b (1 + a ) z−1 + a z −2 a − b (1 + a ) z −1 + z −2 with α and β given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-93 4 Filter Analysis, Design, and Implementation p (2wold + wnew,2 − wnew,1 ) 4 a = p cos (2wold − wnew,2 + wnew,1 ) 4 p b = cos (wnew,1 + wnew,2 ) 2 cos where ωold — Frequency location of the selected feature in the prototype filter ωnew,1 — Position of the feature originally at (-ωold) in the target filter ωnew,2 — Position of the feature originally at (+ωold) in the target filter The following example shows how this transformation can be used to convert the prototype lowpass filter with cutoff frequency at 0.5 into a real bandstop filter with the same passband and stopband ripple structure and stopband positioned between 0.5 and 0.75. Here is the MATLAB code for generating the example in the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates a stopband from 0.5 to 0.75: [num,den] = iirlp2bs(b, a, 0.5, [0.5, 0.75]); 4-94 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) ωt2 0.8 Example of Real Lowpass to Real Bandstop Mapping Real Lowpass to Real Multiband This high-order transformation performs an exact mapping of one selected feature of the prototype filter frequency response into a number of new locations in the target filter. Its most common use is to convert a real lowpass with predefined passband and stopband ripples into a real multiband filter with N arbitrary band edges, where N is the order of the allpass mapping filter. N ∑ ai z−i H A ( z) = S Ni = 0 ai z− N +i ∑ a0 = 1 i= 0 The coefficients α are given by www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-95 4 Filter Analysis, Design, and Implementation a 0 = 1 k = 1,…, N p sin ( Nwnew + ( −1) kwold ) 2 a k = − S p sin (( N − 2k)wnew + ( −1) kw old ) 2 where ωold,k — Frequency location of the first feature in the prototype filter ωnew,k — Position of the feature originally at ωold,k in the target filter The mobility factor, S, specifies the mobility or either DC or Nyquist feature: 1 Nyquist S= DC −1 The example below shows how this transformation can be used to convert the prototype lowpass filter with cutoff frequency at 0.5 into a filter having a number of bands positioned at arbitrary edge frequencies 1/5, 2/5, 3/5 and 4/5. Parameter S was such that there is a passband at DC. Here is the MATLAB code for generating the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates three stopbands, from DC to 0.2, from 0.4 to 0.6 and from 0.8 to Nyquist: [num,den] = iirlp2mb(b, a, 0.5, [0.2, 0.4, 0.6, 0.8], `pass'); 4-96 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 0 0.1 0.2 ωt2 ωt3 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) ωt4 0.8 Example of Real Lowpass to Real Multiband Mapping Real Lowpass to Real Multipoint This high-order frequency transformation performs an exact mapping of a number of selected features of the prototype filter frequency response to their new locations in the target filter. The mapping filter is given by the general IIR polynomial form of the transfer function as given below. N ∑ ai z −i H A ( z) = S Ni = 0 ai z − N + i ∑ a0 = 1 i= 0 For the Nth-order multipoint frequency transformation the coefficients α are www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-97 4 Filter Analysis, Design, and Implementation N i N−i ∑ a N − i zold ,k ⋅ znew, k − S ⋅ znew,k = − zold ,k − S ⋅ znew, k i =1 jpw zold ,k = e old, k j pw znew, k = e new,k k = 1,…, N where ωold,k — Frequency location of the first feature in the prototype filter ωnew,k — Position of the feature originally at ωold,k in the target filter The mobility factor, S, specifies the mobility of either DC or Nyquist feature: 1 Nyquist S= DC −1 The example below shows how this transformation can be used to move features of the prototype lowpass filter originally at -0.5 and 0.5 to their new locations at 0.5 and 0.75, effectively changing a position of the filter passband. Here is the MATLAB code for generating the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates a passband from 0.5 to 0.75: [num,den] = iirlp2xn(b, a, [-0.5, 0.5], [0.5, 0.75], `pass'); 4-98 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo2 −50 −60 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0.9 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 0 0.1 0.2 ωt2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 Example of Real Lowpass to Real Multipoint Mapping Frequency Transformations for Complex Filters • “Overview” on page 4-99 • “Complex Frequency Shift” on page 4-100 • “Real Lowpass to Complex Bandpass” on page 4-101 • “Real Lowpass to Complex Bandstop” on page 4-103 • “Real Lowpass to Complex Multiband” on page 4-104 • “Real Lowpass to Complex Multipoint” on page 4-106 • “Complex Bandpass to Complex Bandpass” on page 4-108 Overview This section discusses complex frequency transformation that take the complex prototype filter and convert it into a different complex target filter. The target filter has its www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-99 4 Filter Analysis, Design, and Implementation frequency response modified in respect to the frequency response of the prototype filter according to the characteristic of the applied frequency transformation from: Complex Frequency Shift Complex frequency shift transformation is the simplest first-order transformation that performs an exact mapping of one selected feature of the frequency response into its new location. At the same time it rotates the whole response of the prototype lowpass filter by the distance specified by the selection of the feature from the prototype filter and the target filter. H A ( z) = a z−1 with α given by a = e j 2p (n new −n ol d ) where ωold — Frequency location of the selected feature in the prototype filter ωnew — Position of the feature originally at ωold in the target filter A special case of the complex frequency shift is a, so called, Hilbert Transformer. It can be designed by setting the parameter to |α|=1, that is 1 forward a = −1 inverse The example below shows how to apply this transformation to rotate the response of the prototype lowpass filter in either direction. Please note that because the transformation can be achieved by a simple phase shift operator, all features of the prototype filter will be moved by the same amount. Here is the MATLAB code for generating the example in the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation moves the feature originally at 0.5 to 0.3: [num,den] = iirshiftc(b, a, 0.5, 0.3); 4-100 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 0.8 1 0.6 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) Example of Complex Frequency Shift Mapping Real Lowpass to Complex Bandpass This first-order transformation performs an exact mapping of one selected feature of the prototype filter frequency response into two new locations in the target filter creating a passband between them. Both Nyquist and DC features can be moved with the rest of the frequency response. H A ( z) = b − a z−1 z−1 − ab with α and β are given by p sin ( 2w old − wnew,2 + wnew,1) 4 a = sin p (2wold + wnew,2 − wnew,1 ) b = e − jp (wnew −wo ld ) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-101 4 Filter Analysis, Design, and Implementation where ωold — Frequency location of the selected feature in the prototype filter ωnew,1 — Position of the feature originally at (-ωold) in the target filter ωnew,2 — Position of the feature originally at (+ωold) in the target filter The following example shows the use of such a transformation for converting a real halfband lowpass filter into a complex bandpass filter with band edges at 0.5 and 0.75. Here is the MATLAB code for generating the example in the figure. The prototype filter is a half band elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The transformation creates a passband from 0.5 to 0.75: [num,den] = iirlp2bpc(b, a, 0.5, [0.5 0.75]); Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 0.8 1 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 ωt2 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 Example of Real Lowpass to Complex Bandpass Mapping 4-102 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations Real Lowpass to Complex Bandstop This first-order transformation performs an exact mapping of one selected feature of the prototype filter frequency response into two new locations in the target filter creating a stopband between them. Both Nyquist and DC features can be moved with the rest of the frequency response. H A ( z) = b − a z−1 ab − z−1 with α and β are given by a = cos p (2wold + n new,2 − n new,1 ) cos p (2wold − n new,2 + n new,1 ) b = e − jp (wnew −wo ld ) where ωold — Frequency location of the selected feature in the prototype filter ωnew,1 — Position of the feature originally at (-ωold) in the target filter ωnew,2 — Position of the feature originally at (+ωold) in the target filter The example below shows the use of such a transformation for converting a real halfband lowpass filter into a complex bandstop filter with band edges at 0.5 and 0.75. Here is the MATLAB code for generating the example in the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The transformation creates a stopband from 0.5 to 0.75: [num,den] = iirlp2bsc(b, a, 0.5, [0.5 0.75]); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-103 4 Filter Analysis, Design, and Implementation Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) ωt2 0.6 0.8 1 Example of Real Lowpass to Complex Bandstop Mapping Real Lowpass to Complex Multiband This high-order transformation performs an exact mapping of one selected feature of the prototype filter frequency response into a number of new locations in the target filter. Its most common use is to convert a real lowpass with predefined passband and stopband ripples into a multiband filter with arbitrary band edges. The order of the mapping filter must be even, which corresponds to an even number of band edges in the target filter. The Nth-order complex allpass mapping filter is given by the following general transfer function form: N ∑ ai z− i H A ( z) = S N i = 0 ai ± z− N +i ∑ a0 = 1 4-104 i= 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations The coefficients α are calculated from the system of linear equations: N ℜ(ai ) ⋅ cos b1,k − cos b 2,k + ℑ(a i ) ⋅ sin b1, k + sin b 2, k = cos b 3,k i =1 N ℜ(a ) ⋅ sin b − sin b − ℑ(a ) ⋅ cos b + cos b = sin b 3, k i 1, k 2, k i 1 ,k 2, k i =1 b = −p n ⋅ ( −1) k + n new,k ( N − k) 1 ,k old b 2, k = −p ∆ C + n n ew, kk k b 3, k = −p n old ⋅ ( −1) + n new, k N k = 1… N ∑ ∑ where ωold — Frequency location of the selected feature in the prototype filter ωnew,i — Position of features originally at ±ωold in the target filter Parameter S is the additional rotation factor by the frequency distance ΔC, giving the additional flexibility of achieving the required mapping: S = e − jp∆C The example shows the use of such a transformation for converting a prototype real lowpass filter with the cutoff frequency at 0.5 into a multiband complex filter with band edges at 0.2, 0.4, 0.6 and 0.8, creating two passbands around the unit circle. Here is the MATLAB code for generating the figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-105 4 Filter Analysis, Design, and Implementation Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 −1 −0.8 −0.6 ωt2 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) ωt3 0.6 ωt4 0.8 1 Example of Real Lowpass to Complex Multiband Mapping The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates two complex passbands: [num,den] = iirlp2mbc(b, a, 0.5, [0.2, 0.4, 0.6, 0.8]); Real Lowpass to Complex Multipoint This high-order transformation performs an exact mapping of a number of selected features of the prototype filter frequency response to their new locations in the target filter. The Nth-order complex allpass mapping filter is given by the following general transfer function form. 4-106 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations N ∑ ai z− i H A ( z) = S N i = 0 ai ± z− N +i ∑ a0 = 1 i= 0 The coefficients α can be calculated from the system of linear equations: N ℜ(ai ) ⋅ cos b1,k − cos b 2,k + ℑ(a i ) ⋅ sin b1, k + sin b 2, k = cos b 3,k i =1 N ℜ(a ) ⋅ sin b − sin b − ℑ(a ) ⋅ cos b + cos b = sin b 3, k i 1, k 2, k i 1 ,k 2, k i =1 p b1,k = − w old ,k + wnew,k ( N − k) 2 p b 2, k = − 2∆C + wnew,k k 2 b = − p w old ,k + wnew,k N 3, k 2 k = 1… N ∑ ∑ where ωold,k — Frequency location of the first feature in the prototype filter ωnew,k — Position of the feature originally at ωold,k in the target filter Parameter S is the additional rotation factor by the frequency distance ΔC, giving the additional flexibility of achieving the required mapping: S = e − jp∆C The following example shows how this transformation can be used to move one selected feature of the prototype lowpass filter originally at -0.5 to two new frequencies -0.5 and www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-107 4 Filter Analysis, Design, and Implementation 0.1, and the second feature of the prototype filter from 0.5 to new locations at -0.25 and 0.3. This creates two nonsymmetric passbands around the unit circle, creating a complex filter. Here is the MATLAB code for generating the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates two nonsymmetric passbands: [num,den] = iirlp2xc(b,a,0.5*[-1,1,-1,1], [-0.5,-0.25,0.1,0.3]); Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 −50 −60 −1 −0.8 −0.6 ωo1 ωo2 ωo3 ωo4 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) 0.6 0.8 1 0.6 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 −50 −60 −1 ωt1 −0.8 −0.6 ωt2 ωt3 ωt4 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) Example of Real Lowpass to Complex Multipoint Mapping Complex Bandpass to Complex Bandpass This first-order transformation performs an exact mapping of two selected features of the prototype filter frequency response into two new locations in the target filter. Its most common use is to adjust the edges of the complex bandpass filter. 4-108 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Frequency Transformations H A ( z) = a (g − b z−1 ) z−1 − bg with α and β are given by p ((wold,2 − wold,1) − (wnew,2 − wnew,1 )) 4 a = p sin ((wold,2 − w old,,1 ) + (wnew,2 − wnew,1 )) 4 sin a =e g =e − jp (w old ,2 −wold,1 ) − jp (wnew,2 −wneew,1 ) where ωold,1 — Frequency location of the first feature in the prototype filter ωold,2 — Frequency location of the second feature in the prototype filter ωnew,1 — Position of the feature originally at ωold,1 in the target filter ωnew,2 — Position of the feature originally at ωold,2 in the target filter The following example shows how this transformation can be used to modify the position of the passband of the prototype filter, either real or complex. In the example below the prototype filter passband spanned from 0.5 to 0.75. It was converted to having a passband between -0.5 and 0.1. Here is the MATLAB code for generating the figure. The prototype filter is a halfband elliptic, real, third-order lowpass filter: [b, a] = ellip(3, 0.1, 30, 0.409); The example transformation creates a passband from 0.25 to 0.75: [num,den] = iirbpc2bpc(b, a, [0.25, 0.75], [-0.5, 0.1]); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-109 4 Filter Analysis, Design, and Implementation Prototype filter 0 |H(ω)|in dB −10 −20 −30 −40 ωo1 −50 −60 −1 −0.8 −0.6 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) ωo2 0.6 0.8 1 0.6 0.8 1 Target filter 0 |H(ω)| in dB −10 −20 −30 −40 ωt1 −50 −60 −1 −0.8 −0.6 ωt2 −0.4 −0.2 0 0.2 0.4 Normalized Frequency (×π rad/sample) Example of Complex Bandpass to Complex Bandpass Mapping 4-110 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Design Block Digital Filter Design Block In this section... “Overview of the Digital Filter Design Block” on page 4-111 “Select a Filter Design Block” on page 4-112 “Create a Lowpass Filter in Simulink” on page 4-113 “Create a Highpass Filter in Simulink” on page 4-114 “Filter High-Frequency Noise in Simulink” on page 4-116 Overview of the Digital Filter Design Block You can use the Digital Filter Design block to design and implement a digital filter. The filter you design can filter single-channel or multichannel signals. The Digital Filter Design block is ideal for simulating the numerical behavior of your filter on a floatingpoint system, such as a personal computer or DSP chip. You can use the Simulink Coder product to generate C code from your filter block. For more information on generating C code from models, see “Understanding C Code Generation” on page 10-2. Filter Design and Analysis You perform all filter design and analysis within the Filter Design and Analysis Tool (FDATool) GUI, which opens when you double-click the Digital Filter Design block. FDATool provides extensive filter design parameters and analysis tools such as pole-zero and impulse response plots. Filter Implementation Once you have designed your filter using FDATool, the block automatically realizes the filter using the filter structure you specify. You can then use the block to filter signals in your model. You can also fine-tune the filter by changing the filter specification parameters during a simulation. The outputs of the Digital Filter Design block numerically match the outputs of the DSP System Toolbox filter function and the MATLAB filter function. Saving, Exporting, and Importing Filters The Digital Filter Design block allows you to save the filters you design, export filters (to the MATLAB workspace, MAT-files, etc.), and import filters designed elsewhere. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-111 4 Filter Analysis, Design, and Implementation To learn how to save your filter designs, see “Saving and Opening Filter Design Sessions” in the Signal Processing Toolbox documentation. To learn how to import and export your filter designs, see “Import and Export Quantized Filters”. Note: You can use the Digital Filter Design block to design and implement a filter. To implement a pre-designed filter, use the Discrete FIR Filter or Biquad Filter blocks. Both methods implement a filter design in the same manner and have the same behavior during simulation and code generation. See the Digital Filter Design block reference page for more information. For information on choosing between the Digital Filter Design block and the Filter Realization Wizard, see “Select a Filter Design Block” on page 4-112. Select a Filter Design Block This section explains the similarities and differences between the Digital Filter Design and Filter Realization Wizard blocks. Similarities The Digital Filter Design block and Filter Realization Wizard are similar in the following ways: • Filter design and analysis options — Both blocks use the Filter Design and Analysis Tool (FDATool) GUI for filter design and analysis. • Output values — If the output of both blocks is double-precision floating point, singleprecision floating point, or fixed point, the output values of both blocks numerically match the output of the filter method of the dfilt object. Differences The Digital Filter Design block and Filter Realization Wizard handle the following things differently: • Supported filter structures — Both blocks support many of the same basic filter structures, but the Filter Realization Wizard supports more structures than the Digital Filter Design block. This is because the block can implement filters using Sum, Gain, and Delay blocks. See the Filter Realization Wizard and Digital Filter Design block reference pages for a list of all the structures they support. 4-112 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Design Block • Data type support — The Filter Realization Wizard block supports single- and double-precision floating-point computation for all filter structures and fixed-point computation for some filter structures. The Digital Filter Design block only supports single- and double-precision floating-point computation. • Block versus Wizard — The Digital Filter Design block is the filter itself, but the Filter Realization Wizard block just enables you to create new filters and put them in an existing model. Thus, the Filter Realization Wizard is not a block that processes data in your model, it is a wizard that generates filter blocks (or subsystems) which you can then use to process data in your model. When to Use Each Block The following are specific situations where only the Digital Filter Design block or the Filter Realization Wizard is appropriate. • Digital Filter Design • Use to simulate single- and double-precision floating-point filters. • Use to generate highly optimized ANSI® C code that implements floating-point filters for embedded systems. • Filter Realization Wizard • Use to simulate numerical behavior of fixed-point filters in a DSP chip, a fieldprogrammable gate array (FPGA), or an application-specific integrated circuit (ASIC). • Use to simulate single- and double-precision floating-point filters with structures that the Digital Filter Design block does not support. • Use to visualize the filter structure, as the block can build the filter from Sum, Gain, and Delay blocks. • Use to rapidly generate multiple filter blocks. See “Filter Realization Wizard” on page 4-121 and the Filter Realization Wizard block reference page for information. Create a Lowpass Filter in Simulink You can use the Digital Filter Design block to design and implement a digital FIR or IIR filter. In this topic, you use it to create an FIR lowpass filter: 1 Open Simulink and create a new model file. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-113 4 Filter Analysis, Design, and Implementation 2 From the DSP System Toolbox Filtering library, and then from the Filter Implementations library, click-and-drag a Digital Filter Design block into your model. 3 Double-click the Digital Filter Design block. The Filter Design and Analysis Tool (FDATool) GUI opens. 4 Set the parameters as follows, and then click OK: • Response Type = Lowpass • Design Method = FIR, Equiripple • Filter Order = Minimum order • Units = Normalized (0 to 1) • wpass = 0.2 • wstop = 0.5 5 Click Design Filter at the bottom of the GUI to design the filter. Your Digital Filter Design block now represents a filter with the parameters you specified. 6 From the Edit menu, select Convert Structure. The Convert Structure dialog box opens. 7 Select Direct-Form FIR Transposed and click OK. 8 Rename your block Digital Filter Design - Lowpass. The Digital Filter Design block now represents a lowpass filter with a Direct-Form FIR Transposed structure. The filter passes all frequencies up to 20% of the Nyquist frequency (half the sampling frequency), and stops frequencies greater than or equal to 50% of the Nyquist frequency as defined by the wpass and wstop parameters. In the next topic, “Create a Highpass Filter in Simulink” on page 4-114, you use a Digital Filter Design block to create a highpass filter. For more information about implementing a pre-designed filter, see “Digital Filter Implementations” on page 4-133. Create a Highpass Filter in Simulink In this topic, you create a highpass filter using the Digital Filter Design block: 1 4-114 If the model you created in “Create a Lowpass Filter in Simulink” on page 4-113 is not open on your desktop, you can open an equivalent model by typing www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Design Block ex_filter_ex4 at the MATLAB command prompt. 2 From the DSP System Toolbox Filtering library, and then from the Filter Implementations library, click-and-drag a second Digital Filter Design block into your model. 3 Double-click the Digital Filter Design block. The Filter Design and Analysis Tool (FDATool) GUI opens. 4 Set the parameters as follows: • Response Type = Highpass • Design Method = FIR, Equiripple • Filter Order = Minimum order • Units = Normalized (0 to 1) • wstop = 0.2 • wpass = 0.5 5 Click the Design Filter button at the bottom of the GUI to design the filter. Your Digital Filter Design block now represents a filter with the parameters you specified. 6 In the Edit menu, select Convert Structure. The Convert Structure dialog box opens. 7 Select Direct-Form FIR Transposed and click OK. 8 Rename your block Digital Filter Design - Highpass . The block now implements a highpass filter with a direct form FIR transpose structure. The filter passes all frequencies greater than or equal to 50% of the Nyquist frequency (half the sampling frequency), and stops frequencies less than or equal to 20% of the Nyquist frequency as defined by the wpass and wstop parameters. This highpass filter is the opposite of the lowpass filter described in “Create a Lowpass Filter in Simulink” on page 4-113. The highpass filter passes the frequencies stopped by the lowpass filter, and stops the frequencies passed by the lowpass filter. In the next topic, “Filter High-Frequency Noise in Simulink” on page 4-116, you use these Digital Filter Design blocks to create a model capable of removing high frequency noise from a signal. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-115 4 Filter Analysis, Design, and Implementation For more information about implementing a pre-designed filter, see “Digital Filter Implementations” on page 4-133. Filter High-Frequency Noise in Simulink In the previous topics, you used Digital Filter Design blocks to create FIR lowpass and highpass filters. In this topic, you use these blocks to build a model that removes high frequency noise from a signal. In this model, you use the highpass filter, which is excited using a uniform random signal, to create high-frequency noise. After you add this noise to a sine wave, you use the lowpass filter to filter out the high-frequency noise: 1 If the model you created in “Create a Highpass Filter in Simulink” on page 4-114 is not open on your desktop, you can open an equivalent model by typing ex_filter_ex5 at the MATLAB command prompt. 2 3 Click-and-drag the following blocks into your model. Block Library Quantity Add Simulink Math Operations library 1 Random Source Sources 1 Sine Wave Sources 1 Time Scope Sinks 1 Set the parameters for these blocks as indicated in the following table. Leave the parameters not listed in the table at their default settings. Parameter Settings for the Other Blocks Block Parameter Setting Add • Icon shape = rectangular • List of signs = ++ Random Source • Source type = = Uniform • Minimum = 0 • Maximum = 4 • Sample mode = Discrete 4-116 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Design Block Block Parameter Setting • Sample time = 1/1000 • Samples per frame = 50 Sine Wave • Frequency (Hz) = 75 • Sample time = 1/1000 • Samples per frame = 50 Time Scope • File > Number of Input Ports > 3 • File > Configuration ... • Open the Visuals:Time Domain Options dialog and set Time span = One frame period 4 Connect the blocks as shown in the following figure. You might need to resize some of the blocks to accomplish this task. 5 From the Simulation menu, select Model Configuration Parameters. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-117 4 Filter Analysis, Design, and Implementation The Configuration Parameters dialog box opens. 6 In the Solver pane, set the parameters as follows, and then click OK: • Start time = 0 • Stop time = 5 • Type = Fixed-step • Solver = Discrete (no continuous states) 7 In the model window, from the Simulation menu, choose Run. The model simulation begins and the scope displays the three input signals. 8 After simulation is complete, select View > Legend from the Time Scope menu. The legend appears in the Time Scope window. You can click-and-drag it anywhere on the scope display. To change the channel names, double-click inside the legend and replace the default channel names with the following: • Add = Noisy Sine Wave • Digital Filter Design – Lowpass = Filtered Noisy Sine Wave • Sine Wave = Original Sine Wave In the next step, you will set the color, style, and marker of each channel. 9 In the Time Scope window, select View > Line Properties, and set the following: Line Style Marker Color Noisy Sine Wave - None Black Filtered Noisy Sine Wave diamond Red Original Sine Wave None * Blue 10 The Time Scope display should now appear as follows: 4-118 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Design Block You can see that the lowpass filter filters out the high-frequency noise in the noisy sine wave. You have now used Digital Filter Design blocks to build a model that removes high frequency noise from a signal. For more information about these blocks, see the Digital Filter Design block reference page. For information on another block capable of designing www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-119 4 Filter Analysis, Design, and Implementation and implementing filters, see “Filter Realization Wizard” on page 4-121. To learn how to save your filter designs, see “Saving and Opening Filter Design Sessions” in the Signal Processing Toolbox documentation. To learn how to import and export your filter designs, see “Import and Export Quantized Filters” in the DSP System Toolbox documentation. 4-120 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Realization Wizard Filter Realization Wizard In this section... “Overview of the Filter Realization Wizard” on page 4-121 “Design and Implement a Fixed-Point Filter in Simulink” on page 4-121 “Set the Filter Structure and Number of Filter Sections” on page 4-130 “Optimize the Filter Structure” on page 4-131 Overview of the Filter Realization Wizard The Filter Realization Wizard is another DSP System Toolbox block that can be used to design and implement digital filters. You can use this tool to filter single-channel floating-point or fixed-point signals. Like the Digital Filter Design block, double-clicking a Filter Realization Wizard block opens FDATool. Unlike the Digital Filter Design block, the Filter Realization Wizard starts FDATool with the Realize Model panel selected. This panel is optimized for use with DSP System Toolbox software. For more information, see the Filter Realization Wizard block reference page. For information on choosing between the Digital Filter Design block and the Filter Realization Wizard, see “Select a Filter Design Block” on page 4-112. Design and Implement a Fixed-Point Filter in Simulink In this section, a tutorial guides you through creating a fixed-point filter with the Filter Realization Wizard. You will use the Filter Realization Wizard to remove noise from a signal. This tutorial has the following parts: • “Part 1 — Create a Signal with Added Noise” on page 4-121 • “Part 2 — Create a Fixed-Point Filter with the Filter Realization Wizard” on page 4-123 • “Part 3 — Build a Model to Filter a Signal” on page 4-127 • “Part 4 — Examine Filtering Results” on page 4-129 Part 1 — Create a Signal with Added Noise In this section of the tutorial, you will create a signal with added noise. Later in the tutorial, you will filter this signal with a fixed-point filter that you design with the Filter Realization Wizard. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-121 4 Filter Analysis, Design, and Implementation 1 Type load mtlb soundsc(mtlb,Fs) at the MATLAB command line. You should hear a voice say “MATLAB.” This is the signal to which you will add noise. 2 Create a noise signal by typing noise = cos(2*pi*3*Fs/8*(0:length(mtlb)-1)/Fs)'; at the command line. You can hear the noise signal by typing soundsc(noise,Fs) 3 Add the noise to the original signal by typing u = mtlb + noise; at the command line. 4 Scale the signal with noise by typing u = u/max(abs(u)); at the command line. You scale the signal to try to avoid overflows later on. You can hear the scaled signal with noise by typing soundsc(u,Fs) 5 View the scaled signal with noise by typing spectrogram(u,256,[],[],Fs);colorbar at the command line. The spectrogram appears as follows. 4-122 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Realization Wizard In the spectrogram, you can see the noise signal as a line at about 2800 Hz, which is equal to 3*Fs/8. Part 2 — Create a Fixed-Point Filter with the Filter Realization Wizard Next you will create a fixed-point filter using the Filter Realization Wizard. You will create a filter that reduces the effects of the noise on the signal. 1 Open a new Simulink model, and drag-and-drop a Filter Realization Wizard block from the Filtering / Filter Implementations library into the model. Note: You do not have to place a Filter Realization Wizard block in a model in order to use it. You can open the GUI from within a library. However, for purposes of this tutorial, we will keep the Filter Realization Wizard block in the model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-123 4 Filter Analysis, Design, and Implementation 2 Double-click the Filter Realization Wizard block in your model. The Realize Model panel of the Filter Design and Analysis Tool (FDATool) appears. 3 Click the Design Filter button ( ) on the bottom left of FDATool. This brings forward the Design filter panel of the tool. 4 Set the following fields in the Design filter panel: • Set Design Method to IIR -- Constrained Least Pth-norm • Set Fs to Fs • Set Fpass to 0.2*Fs • Set Fstop to 0.25*Fs • Set Max pole radius to 0.8 • Click the Design Filter button The Design filter panel should now appear as follows. 4-124 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Realization Wizard 5 Click the Set quantization parameters button on the bottom left of FDATool ( 6 ). This brings forward the Set quantization parameters panel of the tool. Set the following fields in the Set quantization parameters panel: • Select Fixed-point for the Filter arithmetic parameter. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-125 4 Filter Analysis, Design, and Implementation • Make sure the Best precision fraction lengths check box is selected on the Coefficients pane. The Set quantization parameters panel should appear as follows. 7 Click the Realize Model button on the left side of FDATool ( forward the Realize Model panel of the tool. 4-126 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان ). This brings Filter Realization Wizard 8 Select the Build model using basic elements check box, then click the Realize Model button on the bottom of FDATool. A subsystem block for the new filter appears in your model. Note: You do not have to keep the Filter Realization Wizard block in the same model as the generated Filter block. However, for this tutorial, we will keep the blocks in the same model. 9 Double-click the Filter subsystem block in your model to view the filter implementation. Part 3 — Build a Model to Filter a Signal In this section of the tutorial, you will filter noise from a signal in your Simulink model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-127 4 Filter Analysis, Design, and Implementation 1 Connect a Signal From Workspace block from the Sources library to the input port of your filter block. 2 Connect a To Workspace block from the Sinks library to the output port of your filter block. Your blocks should now be connected as follows. 3 Open the Signal From Workspace block dialog box and set the Signal parameter to u. Click OK to save your changes and close the dialog box. 4 Open the Model Configuration Parameters dialog box from the Simulation menu of the model. In the Solver pane of the dialog, set the following fields: • Stop time = length(u)-1 • Type = Fixed-step Click OK to save your changes and close the dialog box. 4-128 5 Run the model. 6 From the Display menu of the model, select Signals & Ports > Port Data Types. You can now see that the input to the Filter block is a signal of type double and the output of the Filter block has a data type of sfix16_En11. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Realization Wizard Part 4 — Examine Filtering Results Now you can listen to and look at the results of the fixed-point filter you designed and implemented. 1 Type soundsc(yout,Fs) at the command line to hear the output of the filter. You should hear a voice say “MATLAB.” The noise portion of the signal should be close to inaudible. 2 Type www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-129 4 Filter Analysis, Design, and Implementation figure spectrogram(yout,256,[],[],Fs);colorbar at the command line. From the colorbars at the side of the input and output spectrograms, you can see that the noise has been reduced by about 40 dB. Set the Filter Structure and Number of Filter Sections The Current Filter Information region of FDATool shows the structure and the number of second-order sections in your filter. Change the filter structure and number of filter sections of your filter as follows: • Select Convert Structure from the Edit menu to open the Convert Structure dialog box. For details, see “Converting to a New Structure” in the Signal Processing Toolbox documentation. • Select Convert to Second-order Sections from the Edit menu to open the Convert to SOS dialog box. For details, see “Converting to Second-Order Sections” in the Signal Processing Toolbox documentation. 4-130 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Realization Wizard Note: You might not be able to directly access some of the supported structures through the Convert Structure dialog of FDATool. However, you can access all of the structures by creating a dfilt filter object with the desired structure, and then importing the filter into FDATool. To learn more about the Import Filter panel, see “Importing a Filter Design” in the Signal Processing Toolbox documentation. Optimize the Filter Structure The Filter Realization Wizard can implement a digital filter using either digital filter blocks from the DSP System Toolbox library or by creating a “subsystem” block that implements the filter using Sum, Gain, and Delay blocks. The following procedure shows you how to optimize the filter implementation: 1 Open the Realize Model pane of FDATool by clicking the Realize Model button in the lower-left corner of FDATool. 2 Select the desired optimizations in the Optimization region of the Realize Model pane. See the following descriptions and illustrations of each optimization option. • Optimize for zero gains — Remove zero-gain paths. • Optimize for unity gains — Substitute gains equal to one with a wire (short circuit). • Optimize for negative gains — Substitute gains equal to -1 with a wire (short circuit), and change the corresponding sums to subtractions. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-131 4 Filter Analysis, Design, and Implementation • Optimize delay chains — Substitute any delay chain made up of n unit delays with a single delay by n. • Optimize for unity scale values — Remove all scale value multiplications by 1 from the filter structure. The following diagram illustrates the results of each of these optimizations. 4-132 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Implementations Digital Filter Implementations In this section... “Using Digital Filter Blocks” on page 4-133 “Implement a Lowpass Filter in Simulink” on page 4-133 “Implement a Highpass Filter in Simulink” on page 4-134 “Filter High-Frequency Noise in Simulink” on page 4-135 “Specify Static Filters” on page 4-140 “Specify Time-Varying Filters” on page 4-140 “Specify the SOS Matrix (Biquadratic Filter Coefficients)” on page 4-141 Using Digital Filter Blocks DSP System Toolbox provides several blocks implementing digital filters, such as Discrete FIR Filter and Biquad Filter. Use these blocks if you have already performed the design and analysis and know your desired filter coefficients. You can use these blocks to filter single-channel and multichannel signals, and to simulate floating-point and fixed-point filters. Then, you can use the Simulink Coder product to generate highly optimized C code from your filters. To implement a filter, you must provide the following basic information about the filter: • The desired filter structure • The filter coefficients Note: Use the Digital Filter Design block to design and implement a filter. Use the Discrete FIR Filter and Biquad Filter blocks to implement a pre-designed filter. Both methods implement a filter in the same manner and have the same behavior during simulation and code generation. Implement a Lowpass Filter in Simulink Use the Discrete FIR Filter block to implement a lowpass filter: 1 Define the lowpass filter coefficients in the MATLAB workspace by typing www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-133 4 Filter Analysis, Design, and Implementation lopassNum = [-0.0021 -0.0108 -0.0274 -0.0409 -0.0266 0.0374 0.1435 0.2465 0.2896 0.2465 0.1435 0.0374 -0.0266 -0.0409 -0.0274 -0.0108 -0.0021]; 2 Open Simulink and create a new model file. 3 From the DSP System Toolbox Filtering>Filter Implementations library, click-anddrag a Discrete FIR Filter block into your model. 4 Double-click the Discrete FIR Filter block. Set the block parameters as follows, and then click OK: • Coefficient source = Dialog parameters • Filter structure = Direct form transposed • Coefficients = lopassNum • Input processing = Columns as channels (frame based) • Initial states = 0 Note that you can provide the filter coefficients in several ways: • Type in a variable name from the MATLAB workspace, such as lopassNum. • Type in filter design commands from Signal Processing Toolbox software or DSP System Toolbox software, such as fir1(5, 0.2, 'low'). • Type in a vector of the filter coefficient values. 5 Rename your block Digital Filter - Lowpass. The Discrete FIR Filter block in your model now represents a lowpass filter. In the next topic, “Implement a Highpass Filter in Simulink” on page 4-134, you use a Discrete FIR Filter block to implement a highpass filter. For more information about the Discrete FIR Filter block, see the Discrete FIR Filter block reference page. For more information about designing and implementing a new filter, see “Digital Filter Design Block” on page 4-111. Implement a Highpass Filter in Simulink In this topic, you implement a highpass filter using the Discrete FIR Filter block: 1 4-134 If the model you created in “Implement a Lowpass Filter in Simulink” on page 4-133 is not open on your desktop, you can open an equivalent model by typing www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Implementations ex_filter_ex1 at the MATLAB command prompt. 2 Define the highpass filter coefficients in the MATLAB workspace by typing hipassNum = [-0.0051 0.0181 -0.0069 -0.0283 -0.0061 ... 0.0549 0.0579 -0.0826 -0.2992 0.5946 -0.2992 -0.0826 ... 0.0579 0.0549 -0.0061 -0.0283 -0.0069 0.0181 -0.0051]; 3 From the DSP System Toolbox Filtering library, and then from the Filter Implementations library, click-and-drag a Discrete FIR Filter block into your model. 4 Double-click the Discrete FIR Filter block. Set the block parameters as follows, and then click OK: • Coefficient source = Dialog parameters • Filter structure = Direct form transposed • Coefficients = hipassNum • Input processing = Columns as channels (frame based) • Initial states = 0 You can provide the filter coefficients in several ways: • Type in a variable name from the MATLAB workspace, such as hipassNum. • Type in filter design commands from Signal Processing Toolbox software or DSP System Toolbox software, such as fir1(5, 0.2, 'low'). • Type in a vector of the filter coefficient values. 5 Rename your block Digital Filter - Highpass. You have now successfully implemented a highpass filter. In the next topic, “Filter HighFrequency Noise in Simulink” on page 4-135, you use these Discrete FIR Filter blocks to create a model capable of removing high frequency noise from a signal. For more information about designing and implementing a new filter, see “Digital Filter Design Block” on page 4-111. Filter High-Frequency Noise in Simulink In the previous topics, you used Discrete FIR Filter blocks to implement lowpass and highpass filters. In this topic, you use these blocks to build a model that removes high frequency noise from a signal. In this model, you use the highpass filter, which is excited www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-135 4 Filter Analysis, Design, and Implementation using a uniform random signal, to create high-frequency noise. After you add this noise to a sine wave, you use the lowpass filter to filter out the high-frequency noise: 1 If the model you created in “Implement a Highpass Filter in Simulink” on page 4-134 is not open on your desktop, you can open an equivalent model by typing ex_filter_ex2 at the MATLAB command prompt. 2 If you have not already done so, define the lowpass and highpass filter coefficients in the MATLAB workspace by typing lopassNum = [-0.0021 -0.0108 -0.0274 -0.0409 -0.0266 ... 0.0374 0.1435 0.2465 0.2896 0.2465 0.1435 0.0374 ... -0.0266 -0.0409 -0.0274 -0.0108 -0.0021]; hipassNum = [-0.0051 0.0181 -0.0069 -0.0283 -0.0061 ... 0.0549 0.0579 -0.0826 -0.2992 0.5946 -0.2992 -0.0826 ... 0.0579 0.0549 -0.0061 -0.0283 -0.0069 0.0181 -0.0051]; 3 4 Click-and-drag the following blocks into your model file. Block Library Quantity Add Simulink / Math Operations library 1 Random Source Sources 1 Sine Wave Sources 1 Time Scope Sinks 1 Set the parameters for the rest of the blocks as indicated in the following table. For any parameters not listed in the table, leave them at their default settings. Block Parameter Setting Add • Icon shape = rectangular • List of signs = ++ Random Source • Source type = Uniform • Minimum = 0 • Maximum = 4 • Sample mode = Discrete 4-136 • Sample time = 1/1000 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Implementations Block Parameter Setting • Samples per frame = 50 Sine Wave • Frequency (Hz) = 75 • Sample time = 1/1000 • Samples per frame = 50 Time Scope • File > Number of Input Ports > 3 • File > Configuration ... • Open the Visuals:Time Domain Options dialog and set Time span = One frame period 5 Connect the blocks as shown in the following figure. You may need to resize some of your blocks to accomplish this task. 6 From the Simulation menu, select Model Configuration Parameters. The Configuration Parameters dialog box opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-137 4 Filter Analysis, Design, and Implementation 7 In the Solver pane, set the parameters as follows, and then click OK: • Start time = 0 • Stop time = 5 • Type = Fixed-step • Solver = discrete (no continuous states) 8 In the model window, from the Simulation menu, choose Run. The model simulation begins and the Scope displays the three input signals. 9 After simulation is complete, select View > Legend from the Time Scope menu. The legend appears in the Time Scope window. You can click-and-drag it anywhere on the scope display. To change the channel names, double-click inside the legend and replace the current numbered channel names with the following: • Add = Noisy Sine Wave • Digital Filter – Lowpass = Filtered Noisy Sine Wave • Sine Wave = Original Sine Wave In the next step, you will set the color, style, and marker of each channel. 10 In the Time Scope window, select View > Line Properties, and set the following: Line Style Marker Color Noisy Sine Wave - None Black Filtered Noisy Sine Wave diamond Red Original Sine Wave None * Blue 11 The Time Scope display should now appear as follows: You can see that the lowpass filter filters out the high-frequency noise in the noisy sine wave. 4-138 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Implementations You have now used Discrete FIR Filter blocks to build a model that removes high frequency noise from a signal. For more information about designing and implementing a new filter, see “Digital Filter Design Block” on page 4-111. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-139 4 Filter Analysis, Design, and Implementation Specify Static Filters You can specify a static filter using the Discrete FIR Filter or Biquad Filter block. To do so, set the Coefficient source parameter to Dialog parameters. For the Discrete FIR Filter, set the Coefficients parameter to a row vector of numerator coefficients. If you set Filter structure to Lattice MA, the Coefficients parameter represents reflection coefficients. For the Biquad Filter, set the SOS matrix (Mx6) to an M-by-6 matrix, where M is the number of sections in the second-order section filter. Each row of the SOS matrix contains the numerator and denominator coefficients of the corresponding section in the filter. Set Scale values to a scalar or vector of M+1 scale values used between SOS stages. Tuning the Filter Coefficient Values During Simulation To change the static filter coefficients during simulation, double-click the block, type in the new filter coefficients, and click OK. You cannot change the filter order, so you cannot change the number of elements in the matrix of filter coefficients. Specify Time-Varying Filters Time-varying filters are filters whose coefficients change with time. You can specify a time-varying filter that changes once per frame. You can filter multiple channels with each filter. However, you cannot apply different filters to each channel; all channels use the same filter. To specify a time-varying filter using a Biquad Filter block or a Discrete FIR Filter block: 1 Set the Coefficient source parameter to Input port(s), which enables extra block input ports for the time-varying filter coefficients. • The Discrete FIR Filter block has a Num port for the numerator coefficients. • The Biquad Filter block has Num and Den ports rather than a single port for the SOS matrix. Separate ports enable you to use different fraction lengths for numerator and denominator coefficients. The scale values port, g, is optional. You can disable the g port by setting Scale values mode to Assume all are unity and optimize. 2 4-140 Provide matrices of filter coefficients to the block input ports. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Digital Filter Implementations • For Discrete FIR Filter block, the number of filter taps, N, cannot vary over time. The input coefficients must be in a 1-by-N vector. • For Biquad Filter block, the number of filter sections, N, cannot vary over time. The numerator coefficients input, Num, must be a 3-by-N matrix. The denominator input coefficients, Den, must be a 2-by-N matrix. The scale values input, g, must be a 1-by-(N+1) vector. Specify the SOS Matrix (Biquadratic Filter Coefficients) Use the Biquad Filter block to specify a static biquadratic IIR filter (also known as a second-order section or SOS filter). Set the following parameters: • Filter structure — Direct form I, or Direct form I transposed, or Direct form II, or Direct form II transposed • SOS matrix (Mx6) M-by-6 SOS matrix The SOS matrix is an M-by-6 matrix, where M is the number of sections in the second-order section filter. Each row of the SOS matrix contains the numerator and denominator coefficients (bik and aik) of the corresponding section in the filter. • Scale values Scalar or vector of M+1 scale values to be used between SOS stages If you enter a scalar, the value is used as the gain value before the first section of the second-order filter. The rest of the gain values are set to 1. If you enter a vector of M+1 values, each value is used for a separate section of the filter. For example, the first element is the first gain value, the second element is the second gain value, and so on. You can use the ss2sos and tf2sos functions from Signal Processing Toolbox software to convert a state-space or transfer function description of your filter into the secondorder section description used by this block. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-141 4 Filter Analysis, Design, and Implementation È b01 Íb Í 02 Í M Í Îb0 M b11 b12 M b1 M b21 b22 M b2M a01 a02 M a0 M a11 a12 M a1M a21 ˘ a22 ˙˙ M ˙ ˙ a2M ˚ The block normalizes each row by a1i to ensure a value of 1 for the zero-delay denominator coefficients. 4-142 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Analog Filter Design Block Analog Filter Design Block The Analog Filter Design block designs and implements analog IIR filters with standard band configurations. All of the analog filter designs let you specify a filter order. The other available parameters depend on the filter type and band configuration, as shown in the following table. Configuration Butterworth Chebyshev I Chebyshev II Elliptic Lowpass Ωp Ωp, Rp Ωs, Rs Ωp, Rp, Rs Highpass Ωp Ωp, Rp Ωs, Rs Ωp, Rp, Rs Bandpass Ωp1, Ωp2 Ωp1, Ωp2, Rp Ωs1, Ωs2, Rs Ωp1, Ωp2, Rp, Rs Bandstop Ωp1, Ωp2 Ωp1, Ωp2, Rp Ωs1, Ωs2, Rs Ωp1, Ωp2, Rp, Rs The table parameters are • Ωp — passband edge frequency • Ωp1 — lower passband edge frequency • Ωp2 — upper cutoff frequency • Ωs — stopband edge frequency • Ωs1 — lower stopband edge frequency • Ωs2 — upper stopband edge frequency • Rp — passband ripple in decibels • Rs — stopband attenuation in decibels For all of the analog filter designs, frequency parameters are in units of radians per second. The Analog Filter Design block uses a state-space filter representation, and applies the filter using the State-Space block in the Simulink Continuous library. All of the design methods use Signal Processing Toolbox functions to design the filter: • The Butterworth design uses the toolbox function butter. • The Chebyshev type I design uses the toolbox function cheby1. • The Chebyshev type II design uses the toolbox function cheby2. • The elliptic design uses the toolbox function ellip. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-143 4 Filter Analysis, Design, and Implementation The Analog Filter Design block is built on the filter design capabilities of Signal Processing Toolbox software. Note: The Analog Filter Design block does not work with the Simulink discrete solver, which is enabled when the Solver list is set to Discrete (no continuous states) in the Solver pane of the Model Configuration Parameters dialog box. Select one of the continuous solvers (such as ode4) instead. 4-144 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Removing High-Frequency Noise from an ECG Signal Removing High-Frequency Noise from an ECG Signal This examples shows you how to filter an ECG signal that has high-freqquency noise, and remove the noise by low-pass filtering. % Create one period of ECG signal x = ecg(500).'; y = sgolayfilt(x,0,5); Fs = 1000; [M,N] = size(y); % Initialize scopes TS = dsp.TimeScope('SampleRate',Fs,... 'TimeSpan',1.5,... 'YLimits',[-1 1],... 'ShowGrid',true,... 'NumInputPorts',2,... 'LayoutDimensions',[2 1],... 'Title','Noisy and Filtered Signals'); % Design lowpass filter Fpass = 200; Fstop = 400; Dpass = 0.05; Dstop = 0.0001; F = [0 Fpass Fstop Fs/2]/(Fs/2); A = [1 1 0 0]; D = [Dpass Dstop]; b = firgr('minorder', F, A, D); LP = dsp.FIRFilter('Numerator',b); % Design Highpass Filter Fstop = 200; Fpass = 400; Dstop = 0.0001; Dpass = 0.05; F = [0 Fstop Fpass Fs/2]/(Fs/2); % Frequency vector A = [0 0 1 1]; % Amplitude vector D = [Dstop Dpass]; % Deviation (ripple) vector b = firgr('minord', F, A, D); HP = dsp.FIRFilter('Numerator', b); % Stream tic; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-145 4 Filter Analysis, Design, and Implementation while toc < 30 x = .1 * randn(M,N); highFreqNoise = step(HP,x); noisySignal = y + highFreqNoise; filteredSignal = step(LP,noisySignal); step(TS,noisySignal,filteredSignal); end % Finalize release(TS) 4-146 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Removing High-Frequency Noise from an ECG Signal www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-147 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 4-148 5 Adaptive Filters Learn how to design and implement adaptive filters. • “Overview of Adaptive Filters and Applications” on page 5-2 • “Adaptive Filters in DSP System Toolbox Software” on page 5-9 • “LMS Adaptive Filters” on page 5-13 • “RLS Adaptive Filters” on page 5-32 • “Signal Enhancement Using LMS and Normalized LMS” on page 5-37 • “Adaptive Filters in Simulink” on page 5-46 • “Selected Bibliography” on page 5-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5 Adaptive Filters Overview of Adaptive Filters and Applications In this section... “Introduction to Adaptive Filtering” on page 5-2 “Adaptive Filtering Methodology” on page 5-2 “Choosing an Adaptive Filter” on page 5-4 “System Identification” on page 5-5 “Inverse System Identification” on page 5-6 “Noise or Interference Cancellation” on page 5-7 “Prediction” on page 5-7 Introduction to Adaptive Filtering Adaptive filtering involves the changing of filter parameters (coefficients) over time, to adapt to changing signal characteristics. Over the past three decades, digital signal processors have made great advances in increasing speed and complexity, and reducing power consumption. As a result, real-time adaptive filtering algorithms are quickly becoming practical and essential for the future of communications, both wired and wireless. For more detailed information about adaptive filters and adaptive filter theory, refer to the books listed in the “Selected Bibliography” on page 5-60. Adaptive Filtering Methodology This section presents a brief description of how adaptive filters work and some of the applications where they can be useful. Adaptive filters self learn. As the signal into the filter continues, the adaptive filter coefficients adjust themselves to achieve the desired result, such as identifying an unknown filter or canceling noise in the input signal. In the figure below, the shaded box represents the adaptive filter, comprising the adaptive filter and the adaptive recursive least squares (RLS) algorithm. 5-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Overview of Adaptive Filters and Applications Desired Signal d(k) Input Signal x(k) + Output Signal y(k) Adaptive FIR or IIR Digital Filter _ SUM Error Signal e(k) text RLS Adaptive Algorithm Block Diagram That Defines the Inputs and Output of a Generic RLS Adaptive Filter The next figure provides the general adaptive filter setup with inputs and outputs. Desired Signal d(k) Input Signal x(k) + Output Signal y(k) Adaptive FIR or IIR Digital Filter _ SUM Error Signal e(k) text Adapting Algorithm Block Diagram Defining General Adaptive Filter Algorithm Inputs and Outputs DSP System Toolbox software includes adaptive filters of a broad range of forms, all of which can be worthwhile for specific needs. Some of the common ones are: • Adaptive filters based on least mean squares (LMS) techniques, such as adaptfilt.lms, adaptfilt.filtxlms, and adaptfilt.nlms • Adaptive filters based on recursive least squares (RLS) techniques. For example, adaptfilt.rls and adaptfilt.swrls • Adaptive filters based on sign-data (adaptfilt.sd), sign-error (adaptfilt.se), and sign-sign (adaptfilt.ss) techniques • Adaptive filters based on lattice filters. For example, adaptfilt.gal and adaptfilt.lsl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-3 5 Adaptive Filters • Adaptive filters that operate in the frequency domain, such as adaptfilt.fdaf and adaptfilt.pbufdaf. • Adaptive filters that operate in the transform domain. Two of these are the adaptfilt.tdafdft and adaptfilt.tdafdct filters An adaptive filter designs itself based on the characteristics of the input signal to the filter and a signal that represents the desired behavior of the filter on its input. Designing the filter does not require any other frequency response information or specification. To define the self-learning process the filter uses, you select the adaptive algorithm used to reduce the error between the output signal y(k) and the desired signal d(k). When the LMS performance criterion for e(k) has achieved its minimum value through the iterations of the adapting algorithm, the adaptive filter is finished and its coefficients have converged to a solution. Now the output from the adaptive filter matches closely the desired signal d(k). When you change the input data characteristics, sometimes called the filter environment, the filter adapts to the new environment by generating a new set of coefficients for the new data. Notice that when e(k) goes to zero and remains there you achieve perfect adaptation, the ideal result but not likely in the real world. The adaptive filter functions in this toolbox implement the shaded portion of the figures, replacing the adaptive algorithm with an appropriate technique. To use one of the functions, you provide the input signal or signals and the initial values for the filter. “Adaptive Filters in DSP System Toolbox Software” on page 5-9 offers details about the algorithms available and the inputs required to use them in MATLAB. Choosing an Adaptive Filter Selecting the adaptive filter that best meets your needs requires careful consideration. An exhaustive discussion of the criteria for selecting your approach is beyond the scope of this User's Guide. However, a few guidelines can help you make your choice. Two main considerations frame the decision — how you plan to use the filter and the filter algorithm to use. When you begin to develop an adaptive filter for your needs, most likely the primary concern is whether using an adaptive filter is a cost-competitive approach to solving your filtering needs. Generally many areas determine the suitability of adaptive filters (these 5-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Overview of Adaptive Filters and Applications areas are common to most filtering and signal processing applications). Four such areas are • Filter consistency — Does your filter performance degrade when the filter coefficients change slightly as a result of quantization, or you switch to fixed-point arithmetic? Will excessive noise in the signal hurt the performance of your filter? • Filter performance — Does your adaptive filter provide sufficient identification accuracy or fidelity, or does the filter provide sufficient signal discrimination or noise cancellation to meet your requirements? • Tools — Do tools exist that make your filter development process easier? Better tools can make it practical to use more complex adaptive algorithms. • DSP requirements — Can your filter perform its job within the constraints of your application? Does your processor have sufficient memory, throughput, and time to use your proposed adaptive filtering approach? Can you trade memory for throughput: use more memory to reduce the throughput requirements or use a faster signal processor? Of the preceding considerations, characterizing filter consistency or robustness may be the most difficult. The simulations in DSP System Toolbox software offers a good first step in developing and studying these issues. LMS algorithm filters provide both a relatively straightforward filters to implement and sufficiently powerful tool for evaluating whether adaptive filtering can be useful for your problem. Additionally, starting with an LMS approach can form a solid baseline against which you can study and compare the more complex adaptive filters available in the toolbox. Finally, your development process should, at some time, test your algorithm and adaptive filter with real data. For truly testing the value of your work there is no substitute for actual data. System Identification One common adaptive filter application is to use adaptive filters to identify an unknown system, such as the response of an unknown communications channel or the frequency response of an auditorium, to pick fairly divergent applications. Other applications include echo cancellation and channel identification. In the figure, the unknown system is placed in parallel with the adaptive filter. This layout represents just one of many possible structures. The shaded area contains the adaptive filter system. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-5 5 Adaptive Filters Unknown System d(k) + y(k) x(k) Adaptive Filter text e(k) _ SUM Using an Adaptive Filter to Identify an Unknown System Clearly, when e(k) is very small, the adaptive filter response is close to the response of the unknown system. In this case the same input feeds both the adaptive filter and the unknown. If, for example, the unknown system is a modem, the input often represents white noise, and is a part of the sound you hear from your modem when you log in to your Internet service provider. Inverse System Identification By placing the unknown system in series with your adaptive filter, your filter adapts to become the inverse of the unknown system as e(k) becomes very small. As shown in the figure the process requires a delay inserted in the desired signal d(k) path to keep the data at the summation synchronized. Adding the delay keeps the system causal. Determining an Inverse Response to an Unknown System Including the delay to account for the delay caused by the unknown system prevents this condition. 5-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Overview of Adaptive Filters and Applications Plain old telephone systems (POTS) commonly use inverse system identification to compensate for the copper transmission medium. When you send data or voice over telephone lines, the copper wires behave like a filter, having a response that rolls off at higher frequencies (or data rates) and having other anomalies as well. Adding an adaptive filter that has a response that is the inverse of the wire response, and configuring the filter to adapt in real time, lets the filter compensate for the rolloff and anomalies, increasing the available frequency output range and data rate for the telephone system. Noise or Interference Cancellation In noise cancellation, adaptive filters let you remove noise from a signal in real time. Here, the desired signal, the one to clean up, combines noise and desired information. To remove the noise, feed a signal n'(k) to the adaptive filter that represents noise that is correlated to the noise to remove from the desired signal. s(k) + n(k) d(k) + n'(k) y(k) x(k) Adaptive Filter e(k) _ SUM Using an Adaptive Filter to Remove Noise from an Unknown System So long as the input noise to the filter remains correlated to the unwanted noise accompanying the desired signal, the adaptive filter adjusts its coefficients to reduce the value of the difference between y(k) and d(k), removing the noise and resulting in a clean signal in e(k). Notice that in this application, the error signal actually converges to the input data signal, rather than converging to zero. Prediction Predicting signals requires that you make some key assumptions. Assume that the signal is either steady or slowly varying over time, and periodic over time as well. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-7 5 Adaptive Filters d(k) + x(k) s(k) Delay y(k) Adaptive Filter e(k) _ SUM Predicting Future Values of a Periodic Signal Accepting these assumptions, the adaptive filter must predict the future values of the desired signal based on past values. When s(k) is periodic and the filter is long enough to remember previous values, this structure with the delay in the input signal, can perform the prediction. You might use this structure to remove a periodic signal from stochastic noise signals. Finally, notice that most systems of interest contain elements of more than one of the four adaptive filter structures. Carefully reviewing the real structure may be required to determine what the adaptive filter is adapting to. Also, for clarity in the figures, the analog-to-digital (A/D) and digital-to-analog (D/A) components do not appear. Since the adaptive filters are assumed to be digital in nature, and many of the problems produce analog data, converting the input signals to and from the analog domain is probably necessary. 5-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in DSP System Toolbox Software Adaptive Filters in DSP System Toolbox Software In this section... “Overview of Adaptive Filtering in DSP System Toolbox Software” on page 5-9 “Algorithms” on page 5-9 “Using Adaptive Filter Objects” on page 5-12 Overview of Adaptive Filtering in DSP System Toolbox Software DSP System Toolbox software contains many objects for constructing and applying adaptive filters to data. As you see in the tables in the next section, the objects use various algorithms to determine the weights for the filter coefficients of the adapting filter. While the algorithms differ in their detail implementations, the LMS and RLS share a common operational approach — minimizing the error between the filter output and the desired signal. Algorithms For adaptive filter (adaptfilt) objects, the algorithm string determines which adaptive filter algorithm your adaptfilt object implements. Each available algorithm entry appears in one of the tables along with a brief description of the algorithm. Click on the algorithm in the first column to get more information about the associated adaptive filter technique. • LMS based adaptive filters • RLS based adaptive filters • Affine projection adaptive filters • Adaptive filters in the frequency domain • Lattice based adaptive filters Least Mean Squares (LMS) Based FIR Adaptive Filters Adaptive Filter Method Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.adjlms Adjoint LMS FIR adaptive filter algorithm adaptfilt.blms Block LMS FIR adaptive filter algorithm www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-9 5 Adaptive Filters Adaptive Filter Method Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.blmsfft FFT-based Block LMS FIR adaptive filter algorithm adaptfilt.dlms Delayed LMS FIR adaptive filter algorithm adaptfilt.filtxlms Filtered-x LMS FIR adaptive filter algorithm adaptfilt.lms LMS FIR adaptive filter algorithm adaptfilt.nlms Normalized LMS FIR adaptive filter algorithm adaptfilt.sd Sign-data LMS FIR adaptive filter algorithm adaptfilt.se Sign-error LMS FIR adaptive filter algorithm adaptfilt.ss Sign-sign LMS FIR adaptive filter algorithm For further information about an adapting algorithm, refer to the reference page for the algorithm. Recursive Least Squares (RLS) Based FIR Adaptive Filters Adaptive Filter Method Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.ftf Fast transversal least-squares adaptation algorithm adaptfilt.qrdrls QR-decomposition RLS adaptation algorithm adaptfilt.hrls Householder RLS adaptation algorithm adaptfilt.hswrls Householder SWRLS adaptation algorithm adaptfilt.rls Recursive-least squares (RLS) adaptation algorithm adaptfilt.swrls Sliding window (SW) RLS adaptation algorithm adaptfilt.swftf Sliding window FTF adaptation algorithm For more complete information about an adapting algorithm, refer to the reference page for the algorithm. Affine Projection (AP) FIR Adaptive Filters 5-10 Adaptive Filter Method Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.ap Affine projection algorithm that uses direct matrix inversion www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in DSP System Toolbox Software Adaptive Filter Method Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.apru Affine projection algorithm that uses recursive matrix updating adaptfilt.bap Block affine projection adaptation algorithm To find more information about an adapting algorithm, refer to the reference page for the algorithm. FIR Adaptive Filters in the Frequency Domain (FD) Adaptive Filter Method Description of the Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.fdaf Frequency domain adaptation algorithm adaptfilt.pbfdaf Partition block version of the FDAF algorithm adaptfilt.pbufdaf Partition block unconstrained version of the FDAF algorithm adaptfilt.tdafdct Transform domain adaptation algorithm using DCT adaptfilt.tdafdft Transform domain adaptation algorithm using DFT adaptfilt.ufdaf Unconstrained FDAF algorithm for adaptation For more information about an adapting algorithm, refer to the reference page for the algorithm. Lattice-Based (L) FIR Adaptive Filters Adaptive Filter Method Description of the Adapting Algorithm Used to Generate Filter Coefficients During Adaptation adaptfilt.gal Gradient adaptive lattice filter adaptation algorithm adaptfilt.lsl Least squares lattice adaptation algorithm adaptfilt.qrdlsl QR decomposition RLS adaptation algorithm For more information about an adapting algorithm, refer to the reference page for the algorithm. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-11 5 Adaptive Filters Presenting a detailed derivation of the Wiener-Hopf equation and determining solutions to it is beyond the scope of this User's Guide. Full descriptions of the theory appear in the adaptive filter references provided in the “Selected Bibliography” on page 5-60. Using Adaptive Filter Objects After you construct an adaptive filter object, how do you apply it to your data or system? Like quantizer objects, adaptive filter objects have a filter method that you use to apply the adaptfilt object to data. In the following sections, various examples of using LMS and RLS adaptive filters show you how filter works with the objects to apply them to data. • “LMS Adaptive Filters” on page 5-13 • “RLS Adaptive Filters” on page 5-32 5-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters LMS Adaptive Filters In this section... “LMS Methods for adaptfilt Objects” on page 5-13 “System Identification Using adaptfilt.lms” on page 5-15 “System Identification Using adaptfilt.nlms” on page 5-18 “Noise Cancellation Using adaptfilt.sd” on page 5-20 “Noise Cancellation Using adaptfilt.se” on page 5-23 “Noise Cancellation Using adaptfilt.ss” on page 5-27 LMS Methods for adaptfilt Objects This section provides introductory examples using some of the least mean squares (LMS) adaptive filter functions in the toolbox. The toolbox provides many adaptive filter design functions that use the LMS algorithms to search for the optimal solution to the adaptive filter, including • adaptfilt.lms — Implement the LMS algorithm to solve the Wiener-Hopf equation and find the filter coefficients for an adaptive filter. • adaptfilt.nlms — Implement the normalized variation of the LMS algorithm to solve the Wiener-Hopf equation and determine the filter coefficients of an adaptive filter. • adaptfilt.sd — Implement the sign-data variation of the LMS algorithm to solve the Wiener-Hopf equation and determine the filter coefficients of an adaptive filter. The correction to the filter weights at each iteration depends on the sign of the input x(k). • adaptfilt.se — Implement the sign-error variation of the LMS algorithm to solve the Wiener-Hopf equation and determine the filter coefficients of an adaptive filter. The correction applied to the current filter weights for each successive iteration depends on the sign of the error, e(k). • adaptfilt.ss — Implement the sign-sign variation of the LMS algorithm to solve the Wiener-Hopf equation and determine the filter coefficients of an adaptive filter. The correction applied to the current filter weights for each successive iteration depends on both the sign of x(k) and the sign of e(k). www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-13 5 Adaptive Filters To demonstrate the differences and similarities among the various LMS algorithms supplied in the toolbox, the LMS and NLMS adaptive filter examples use the same filter for the unknown system. The unknown filter is the constrained lowpass filter from firgr and fircband examples. [b,err,res]=firgr(12,[0 0.4 0.5 1], [1 1 0 0], [1 0.2],... {'w' 'c'}); From the figure you see that the filter is indeed lowpass and constrained to 0.2 ripple in the stopband. With this as the baseline, the adaptive LMS filter examples use the adaptive LMS algorithms and their initialization functions to identify this filter in a system identification role. To review the general model for system ID mode, look at “System Identification” on page 5-5 for the layout. For the sign variations of the LMS algorithm, the examples use noise cancellation as the demonstration application, as opposed to the system identification application used in the LMS examples. 5-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters System Identification Using adaptfilt.lms To use the adaptive filter functions in the toolbox you need to provide three things: • The adaptive LMS function to use. This example uses the LMS adaptive filter function adaptfilt.lms. • An unknown system or process to adapt to. In this example, the filter designed by firgr is the unknown system. • Appropriate input data to exercise the adaptation process. In terms of the generic LMS model, these are the desired signal d(k) and the input signal x(k). Start by defining an input signal x. x = 0.1*randn(1,250); The input is broadband noise. For the unknown system filter, use firgr to create a twelfth-order lowpass filter: [b,err,res] = fircband(12,[0 0.4 0.5 1],[1 1 0 0],[1 0.2],{'w','c'}); Although you do not need them here, include the err and res output arguments. Now filter the signal through the unknown system to get the desired signal. d = filter(b,1,x); With the unknown filter designed and the desired signal in place you construct and apply the adaptive LMS filter object to identify the unknown. Preparing the adaptive filter object requires that you provide starting values for estimates of the filter coefficients and the LMS step size. You could start with estimated coefficients of some set of nonzero values; this example uses zeros for the 12 initial filter weights. For the step size, 0.8 is a reasonable value — a good compromise between being large enough to converge well within the 250 iterations (250 input sample points) and small enough to create an accurate estimate of the unknown filter. mu = 0.8; ha = adaptfilt.lms(13,mu); Finally, using the adaptfilt object ha, desired signal, d, and the input to the filter, x, run the adaptive filter to determine the unknown system and plot the results, comparing the actual coefficients from firgr to the coefficients found by adaptfilt.lms. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-15 5 Adaptive Filters [y,e] = filter(ha,x,d); stem([b.' ha.coefficients.']) title('System Identification by Adaptive LMS Algorithm') legend('Actual Filter Weights', 'Estimated Filter Weights',... 'Location', 'NorthEast') In the stem plot the actual and estimated filter weights are the same. As an experiment, try changing the step size to 0.2. Repeating the example with mu = 0.2 results in the following stem plot. The estimated weights fail to approximate the actual weights closely. 5-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters Since this may be because you did not iterate over the LMS algorithm enough times, try using 1000 samples. With 1000 samples, the stem plot, shown in the next figure, looks much better, albeit at the expense of much more computation. Clearly you should take care to select the step size with both the computation required and the fidelity of the estimated filter in mind. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-17 5 Adaptive Filters System Identification Using adaptfilt.nlms To improve the convergence performance of the LMS algorithm, the normalized variant (NLMS) uses an adaptive step size based on the signal power. As the input signal power changes, the algorithm calculates the input power and adjusts the step size to maintain an appropriate value. Thus the step size changes with time. As a result, the normalized algorithm converges more quickly with fewer samples in many cases. For input signals that change slowly over time, the normalized LMS can represent a more efficient LMS approach. In the adaptfilt.nlms example, you used firgr to create the filter that you would identify. So you can compare the results, you use the same filter, and replace adaptfilt.lms with adaptfilt.nlms, to use the normalized LMS algorithm variation. You should see better convergence with similar fidelity. First, generate the input signal and the unknown filter. x = 0.1*randn(1,500); [b,err,res] = fircband(12,[0 0.4 0.5 1], [1 1 0 0], [1 0.2],... {'w' 'c'}); d = filter(b,1,x); Again d represents the desired signal d(x) as you defined it earlier and b contains the filter coefficients for your unknown filter. mu = 0.8; ha = adaptfilt.nlms(13,mu); You use the preceding code to initialize the normalized LMS algorithm. For more information about the optional input arguments, refer to adaptfilt.nlms in the reference section of this User's Guide. Running the system identification process is a matter of using adaptfilt.nlms with the desired signal, the input signal, and the initial filter coefficients and conditions specified in s as input arguments. Then plot the results to compare the adapted filter to the actual filter. [y,e] = filter(ha,x,d); stem([b.' ha.coefficients.']) title('System Identification by Normalized LMS Algorithm') legend('Actual Filter Weights', 'Estimated Filter Weights',... 5-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters 'Location', 'NorthEast') As shown in the following stem plot (a convenient way to compare the estimated and actual filter coefficients), the two are nearly identical. If you compare the convergence performance of the regular LMS algorithm to the normalized LMS variant, you see the normalized version adapts in far fewer iterations to a result almost as good as the nonnormalized version. plot(e); title('Comparing the LMS and NLMS Conversion Performance'); legend('NLMS Derived Filter Weights', ... 'LMS Derived Filter Weights', 'Location', 'NorthEast'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-19 5 Adaptive Filters Noise Cancellation Using adaptfilt.sd When the amount of computation required to derive an adaptive filter drives your development process, the sign-data variant of the LMS (SDLMS) algorithm may be a very good choice as demonstrated in this example. Fortunately, the current state of digital signal processor (DSP) design has relaxed the need to minimize the operations count by making DSPs whose multiply and shift operations are as fast as add operations. Thus some of the impetus for the sign-data algorithm (and the sign-error and sign-sign variations) has been lost to DSP technology improvements. In the standard and normalized variations of the LMS adaptive filter, coefficients for the adapting filter arise from the mean square error between the desired signal and the output signal from the unknown system. Using the sign-data algorithm changes the mean square error calculation by using the sign of the input data to change the filter coefficients. When the error is positive, the new coefficients are the previous coefficients plus the error multiplied by the step size µ. If the error is negative, the new coefficients are again the previous coefficients minus the error multiplied by µ — note the sign change. When the input is zero, the new coefficients are the same as the previous set. 5-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters In vector form, the sign-data LMS algorithm is w( k + 1) = w( k) + m e( k)sgn [ x( k) ] , 1, x( k) > 0 sgn [ x( k)] = 0, x( k) = 0 −1, x( k) < 0 with vector w containing the weights applied to the filter coefficients and vector x containing the input data. e(k) (equal to desired signal - filtered signal) is the error at time k and is the quantity the SDLMS algorithm seeks to minimize. µ (mu) is the step size. As you specify mu smaller, the correction to the filter weights gets smaller for each sample and the SDLMS error falls more slowly. Larger mu changes the weights more for each step so the error falls more rapidly, but the resulting error does not approach the ideal solution as closely. To ensure good convergence rate and stability, select mu within the following practical bounds 0<m< 1 N { InputSignalPower} where N is the number of samples in the signal. Also, define mu as a power of two for efficient computing. Note How you set the initial conditions of the sign-data algorithm profoundly influences the effectiveness of the adaptation. Because the algorithm essentially quantizes the input signal, the algorithm can become unstable easily. A series of large input values, coupled with the quantization process may result in the error growing beyond all bounds. You restrain the tendency of the sign-data algorithm to get out of control by choosing a small step size (µ<< 1) and setting the initial conditions for the algorithm to nonzero positive and negative values. In this noise cancellation example, adaptfilt.sd requires two input data sets: • Data containing a signal corrupted by noise. In Using an Adaptive Filter to Remove Noise from an Unknown System, this is d(k), the desired signal. The noise cancellation process removes the noise, leaving the signal. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-21 5 Adaptive Filters • Data containing random noise (x(k) in Using an Adaptive Filter to Remove Noise from an Unknown System) that is correlated with the noise that corrupts the signal data. Without the correlation between the noise data, the adapting algorithm cannot remove the noise from the signal. For the signal, use a sine wave. Note that signal is a column vector of 1000 elements. signal = sin(2*pi*0.055*[0:1000-1]'); Now, add correlated white noise to signal. To ensure that the noise is correlated, pass the noise through a lowpass FIR filter, and then add the filtered noise to the signal. noise=randn(1,1000); nfilt=fir1(11,0.4); % Eleventh order lowpass filter fnoise=filter(nfilt,1,noise); % Correlated noise data d=signal.'+fnoise; fnoise is the correlated noise and d is now the desired input to the sign-data algorithm. To prepare the adaptfilt object for processing, set the input conditions coeffs and mu for the object. As noted earlier in this section, the values you set for coeffs and mu determine whether the adaptive filter can remove the noise from the signal path. In “System Identification Using adaptfilt.lms” on page 5-15, you constructed a default filter that sets the filter coefficients to zeros. In most cases that approach does not work for the sign-data algorithm. The closer you set your initial filter coefficients to the expected values, the more likely it is that the algorithm remains well behaved and converges to a filter solution that removes the noise effectively. For this example, start with the coefficients in the filter you used to filter the noise (nfilt), and modify them slightly so the algorithm has to adapt. coeffs = nfilt.' -0.01; % Set the filter initial conditions. mu = 0.05; % Set the step size for algorithm updating. With the required input arguments for adaptfilt.sd prepared, construct the adaptfilt object, run the adaptation, and view the results. ha = adaptfilt.sd(12,mu) set(ha,'coefficients',coeffs); [y,e] = filter(ha,noise,d); plot(0:199,signal(1:200),0:199,e(1:200)); title('Noise Cancellation by the Sign-Data Algorithm'); 5-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters legend('Actual Signal', 'Result of Noise Cancellation',... 'Location', 'NorthEast'); When adaptfilt.sd runs, it uses far fewer multiply operations than either of the LMS algorithms. Also, performing the sign-data adaptation requires only bit shifting multiplies when the step size is a power of two. Although the performance of the sign-data algorithm as shown in the next figure is quite good, the sign-data algorithm is much less stable than the standard LMS variations. In this noise cancellation example, the signal after processing is a very good match to the input signal, but the algorithm could very easily grow without bound rather than achieve good performance. Changing coeffs, mu, or even the lowpass filter you used to create the correlated noise can cause noise cancellation to fail and the algorithm to become useless. Noise Cancellation Using adaptfilt.se In some cases, the sign-error variant of the LMS algorithm (SELMS) may be a very good choice for an adaptive filter application. In the standard and normalized variations of the LMS adaptive filter, the coefficients for the adapting filter arise from calculating the mean square error between the desired www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-23 5 Adaptive Filters signal and the output signal from the unknown system, and applying the result to the current filter coefficients. Using the sign-error algorithm replaces the mean square error calculation by using the sign of the error to modify the filter coefficients. When the error is positive, the new coefficients are the previous coefficients plus the error multiplied by the step size µ. If the error is negative, the new coefficients are again the previous coefficients minus the error multiplied by µ — note the sign change. When the input is zero, the new coefficients are the same as the previous set. In vector form, the sign-error LMS algorithm is w( k + 1) = w( k) + m sgn [ e( k)][ x(k) ] , 1, e( k) > 0 sgn [ e(k) ] = 0, e( k) = 0 −1, e(k) < 0 with vector w containing the weights applied to the filter coefficients and vector x containing the input data. e(k) (equal to desired signal - filtered signal) is the error at time k and is the quantity the SELMS algorithm seeks to minimize. µ (mu) is the step size. As you specify mu smaller, the correction to the filter weights gets smaller for each sample and the SELMS error falls more slowly. Larger mu changes the weights more for each step so the error falls more rapidly, but the resulting error does not approach the ideal solution as closely. To ensure good convergence rate and stability, select mu within the following practical bounds 0<m< 1 N { InputSignalPower} where N is the number of samples in the signal. Also, define mu as a power of two for efficient computation. Note How you set the initial conditions of the sign-data algorithm profoundly influences the effectiveness of the adaptation. Because the algorithm essentially quantizes the error signal, the algorithm can become unstable easily. A series of large error values, coupled with the quantization process may result in the error growing beyond all bounds. You restrain the tendency of the sign-error algorithm to 5-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters get out of control by choosing a small step size (µ<< 1) and setting the initial conditions for the algorithm to nonzero positive and negative values. In this noise cancellation example, adaptfilt.se requires two input data sets: • Data containing a signal corrupted by noise. In Using an Adaptive Filter to Remove Noise from an Unknown System, this is d(k), the desired signal. The noise cancellation process removes the noise, leaving the signal. • Data containing random noise (x(k) in Using an Adaptive Filter to Remove Noise from an Unknown System) that is correlated with the noise that corrupts the signal data. Without the correlation between the noise data, the adapting algorithm cannot remove the noise from the signal. For the signal, use a sine wave. Note that signal is a column vector of 1000 elements. signal = sin(2*pi*0.055*[0:1000-1]'); Now, add correlated white noise to signal. To ensure that the noise is correlated, pass the noise through a lowpass FIR filter, then add the filtered noise to the signal. noise=randn(1,1000); nfilt=fir1(11,0.4); % Eleventh order lowpass filter. fnoise=filter(nfilt,1,noise); % Correlated noise data. d=signal.'+fnoise; fnoise is the correlated noise and d is now the desired input to the sign-data algorithm. To prepare the adaptfilt object for processing, set the input conditions coeffs and mu for the object. As noted earlier in this section, the values you set for coeffs and mu determine whether the adaptive filter can remove the noise from the signal path. In “System Identification Using adaptfilt.lms” on page 5-15, you constructed a default filter that sets the filter coefficients to zeros. Setting the coefficients to zero often does not work for the sign-error algorithm. The closer you set your initial filter coefficients to the expected values, the more likely it is that the algorithm remains well behaved and converges to a filter solution that removes the noise effectively. For this example, you start with the coefficients in the filter you used to filter the noise (nfilt), and modify them slightly so the algorithm has to adapt. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-25 5 Adaptive Filters coeffs = nfilt.' -0.01; % Set the filter initial conditions. mu = 0.05; % Set step size for algorithm update. With the required input arguments for adaptfilt.se prepared, run the adaptation and view the results. ha = adaptfilt.se(12,mu) set(ha,'coefficients',coeffs); set(ha,'persistentmemory',true); % Prevent filter reset. [y,e] = filter(ha,noise,d); plot(0:199,signal(1:200),0:199,e(1:200)); title('Noise Cancellation Performance by the Sign-Error LMS Algorithm'); legend('Actual Signal','Error After Noise Reduction',... 'Location','NorthEast') Notice that you have to set the property PersistentMemory to true when you manually change the settings of object ha. If PersistentMemory is left to false, the default, when you try to apply ha with the method filter, the filtering process starts by resetting the object properties to their initial conditions at construction. To preserve the customized coefficients in this example, you set PersistentMemory to true so the coefficients do not get reset automatically back to zero. When adaptfilt.se runs, it uses far fewer multiply operations than either of the LMS algorithms. Also, performing the sign-error adaptation requires only bit shifting multiplies when the step size is a power of two. Although the performance of the sign-data algorithm as shown in the next figure is quite good, the sign-data algorithm is much less stable than the standard LMS variations. In this noise cancellation example, the signal after processing is a very good match to the input signal, but the algorithm could very easily become unstable rather than achieve good performance. Changing coeffs, mu, or even the lowpass filter you used to create the correlated noise can cause noise cancellation to fail and the algorithm to become useless. 5-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters Noise Cancellation Using adaptfilt.ss One more example of a variation of the LMS algorithm in the toolbox is the sign-sign variant (SSLMS). The rationale for this version matches those for the sign-data and sign-error algorithms presented in preceding sections. For more details, refer to “Noise Cancellation Using adaptfilt.sd” on page 5-20. The sign-sign algorithm (SSLMS) replaces the mean square error calculation with using the sign of the input data to change the filter coefficients. When the error is positive, the new coefficients are the previous coefficients plus the error multiplied by the step size µ. If the error is negative, the new coefficients are again the previous coefficients minus the error multiplied by µ — note the sign change. When the input is zero, the new coefficients are the same as the previous set. In essence, the algorithm quantizes both the error and the input by applying the sign operator to them. In vector form, the sign-sign LMS algorithm is www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-27 5 Adaptive Filters w( k + 1) = w( k) + m sgn [ e( k)] sgn [ x( k) ] , 1, z(k) > 0 sgn [ z( k) ] = 0, z( k) = 0 − 1, z( k) < 0 where z( k) = [ e(k) ] sgn [ x( k)] Vector w contains the weights applied to the filter coefficients and vector x contains the input data. e(k) ( = desired signal - filtered signal) is the error at time k and is the quantity the SSLMS algorithm seeks to minimize. µ(mu) is the step size. As you specify mu smaller, the correction to the filter weights gets smaller for each sample and the SSLMS error falls more slowly. Larger mu changes the weights more for each step so the error falls more rapidly, but the resulting error does not approach the ideal solution as closely. To ensure good convergence rate and stability, select mu within the following practical bounds 0<m< 1 N { InputSignalPower} where N is the number of samples in the signal. Also, define mu as a power of two for efficient computation. Note How you set the initial conditions of the sign-sign algorithm profoundly influences the effectiveness of the adaptation. Because the algorithm essentially quantizes the input signal and the error signal, the algorithm can become unstable easily. A series of large error values, coupled with the quantization process may result in the error growing beyond all bounds. You restrain the tendency of the sign-sign algorithm to get out of control by choosing a small step size (µ<< 1) and setting the initial conditions for the algorithm to nonzero positive and negative values. In this noise cancellation example, adaptfilt.ss requires two input data sets: • Data containing a signal corrupted by noise. In Using an Adaptive Filter to Remove Noise from an Unknown System, this is d(k), the desired signal. The noise 5-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters cancellation process removes the noise, leaving the cleaned signal as the content of the error signal. • Data containing random noise (x(k) in Using an Adaptive Filter to Remove Noise from an Unknown System) that is correlated with the noise that corrupts the signal data, called. Without the correlation between the noise data, the adapting algorithm cannot remove the noise from the signal. For the signal, use a sine wave. Note that signal is a column vector of 1000 elements. signal = sin(2*pi*0.055*[0:1000-1]'); Now, add correlated white noise to signal. To ensure that the noise is correlated, pass the noise through a lowpass FIR filter, then add the filtered noise to the signal. noise=randn(1,1000); nfilt=fir1(11,0.4); % Eleventh order lowpass filter fnoise=filter(nfilt,1,noise); % Correlated noise data d=signal.'+fnoise; fnoise is the correlated noise and d is now the desired input to the sign-data algorithm. To prepare the adaptfilt object for processing, set the input conditions coeffs and mu for the object. As noted earlier in this section, the values you set for coeffs and mu determine whether the adaptive filter can remove the noise from the signal path. In “System Identification Using adaptfilt.lms” on page 5-15, you constructed a default filter that sets the filter coefficients to zeros. Usually that approach does not work for the sign-sign algorithm. The closer you set your initial filter coefficients to the expected values, the more likely it is that the algorithm remains well behaved and converges to a filter solution that removes the noise effectively. For this example, you start with the coefficients in the filter you used to filter the noise (nfilt), and modify them slightly so the algorithm has to adapt. coeffs = nfilt.' -0.01; % Set the filter initial conditions. mu = 0.05; % Set the step size for algorithm updating. With the required input arguments for adaptfilt.ss prepared, run the adaptation and view the results. ha = adaptfilt.ss(12,mu) set(ha,'coefficients',coeffs); set(ha,'persistentmemory',true); % Prevent filter reset. [y,e] = filter(ha,noise,d); plot(0:199,signal(1:200),0:199,e(1:200)); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-29 5 Adaptive Filters title('Noise Cancellation Performance of the Sign-Sign LMS Algorithm'); legend('Actual Signal', 'Error After Noise Reduction', ... 'Location', 'NorthEast'); Notice that you have to set the property PersistentMemory to true when you manually change the settings of object ha. If PersistentMemory is left to false, when you try to apply ha with the method filter the filtering process starts by resetting the object properties to their initial conditions at construction. To preserve the customized coefficients in this example, you set PersistentMemory to true so the coefficients do not get reset automatically back to zero. When adaptfilt.ss runs, it uses far fewer multiply operations than either of the LMS algorithms. Also, performing the sign-sign adaptation requires only bit shifting multiplies when the step size is a power of two. Although the performance of the sign-sign algorithm as shown in the next figure is quite good, the sign-sign algorithm is much less stable than the standard LMS variations. In this noise cancellation example, the signal after processing is a very good match to the input signal, but the algorithm could very easily become unstable rather than achieve good performance. Changing coeffs, mu, or even the lowpass filter you used to create the correlated noise can cause noise cancellation to fail and the algorithm to become useless. 5-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان LMS Adaptive Filters As an aside, the sign-sign LMS algorithm is part of the international CCITT standard for 32 Kb/s ADPCM telephony. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-31 5 Adaptive Filters RLS Adaptive Filters In this section... “Compare RLS and LMS Adaptive Filter Algorithms” on page 5-32 “Inverse System Identification Using adaptfilt.rls” on page 5-33 Compare RLS and LMS Adaptive Filter Algorithms This section provides an introductory example that uses the RLS adaptive filter function adaptfilt.rls. If LMS algorithms represent the simplest and most easily applied adaptive algorithms, the recursive least squares (RLS) algorithms represents increased complexity, computational cost, and fidelity. In performance, RLS approaches the Kalman filter in adaptive filtering applications, at somewhat reduced required throughput in the signal processor. Compared to the LMS algorithm, the RLS approach offers faster convergence and smaller error with respect to the unknown system, at the expense of requiring more computations. In contrast to the least mean squares algorithm, from which it can be derived, the RLS adaptive algorithm minimizes the total squared error between the desired signal and the output from the unknown system. Note that the signal paths and identifications are the same whether the filter uses RLS or LMS. The difference lies in the adapting portion. Within limits, you can use any of the adaptive filter algorithms to solve an adaptive filter problem by replacing the adaptive portion of the application with a new algorithm. Examples of the sign variants of the LMS algorithms demonstrated this feature to demonstrate the differences between the sign-data, sign-error, and sign-sign variations of the LMS algorithm. One interesting input option that applies to RLS algorithms is not present in the LMS processes — a forgetting factor, λ, that determines how the algorithm treats past data input to the algorithm. 5-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان RLS Adaptive Filters When the LMS algorithm looks at the error to minimize, it considers only the current error value. In the RLS method, the error considered is the total error from the beginning to the current data point. Said another way, the RLS algorithm has infinite memory — all error data is given the same consideration in the total error. In cases where the error value might come from a spurious input data point or points, the forgetting factor lets the RLS algorithm reduce the value of older error data by multiplying the old data by the forgetting factor. Since 0 ≤λ< 1, applying the factor is equivalent to weighting the older error. When λ = 1, all previous error is considered of equal weight in the total error. As λ approaches zero, the past errors play a smaller role in the total. For example, when λ = 0.9, the RLS algorithm multiplies an error value from 50 samples in the past by an attenuation factor of 0.950 = 5.15 x 10-3, considerably deemphasizing the influence of the past error on the current total error. Inverse System Identification Using adaptfilt.rls Rather than use a system identification application to demonstrate the RLS adaptive algorithm, or a noise cancellation model, this example use the inverse system identification model shown in here. Unknown System d(k) + y(k) x(k) Adaptive Filter text e(k) _ SUM Cascading the adaptive filter with the unknown filter causes the adaptive filter to converge to a solution that is the inverse of the unknown system. If the transfer function of the unknown is H(z) and the adaptive filter transfer function is G(z), the error measured between the desired signal and the signal from the cascaded system reaches its minimum when the product of H(z) and G(z) is 1, G(z)*H(z) = 1. For www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-33 5 Adaptive Filters this relation to be true, G(z) must equal 1/H(z), the inverse of the transfer function of the unknown system. To demonstrate that this is true, create a signal to input to the cascaded filter pair. x = randn(1,3000); In the cascaded filters case, the unknown filter results in a delay in the signal arriving at the summation point after both filters. To prevent the adaptive filter from trying to adapt to a signal it has not yet seen (equivalent to predicting the future), delay the desired signal by 32 samples, the order of the unknown system. Generally, you do not know the order of the system you are trying to identify. In that case, delay the desired signal by the number of samples equal to half the order of the adaptive filter. Delaying the input requires prepending 12 zero-values samples to x. delay = zeros(1,12); d = [delay x(1:2988)]; % Concatenate the delay and the signal. You have to keep the desired signal vector d the same length as x, hence adjust the signal element count to allow for the delay samples. Although not generally true, for this example you know the order of the unknown filter, so you add a delay equal to the order of the unknown filter. For the unknown system, use a lowpass, 12th-order FIR filter. ufilt = fir1(12,0.55,'low'); Filtering x provides the input data signal for the adaptive algorithm function. xdata = filter(ufilt,1,x); To set the input argument values for the adaptfilt.rls object, use the constructor adaptfilt.rls, providing the needed arguments l, lambda, and invcov. For more information about the input conditions to prepare the RLS algorithm object, refer to adaptfilt.rls in the reference section of this user's guide. p0 = 2*eye(13); lambda = 0.99; ha = adaptfilt.rls(13,lambda,p0); Most of the process to this point is the same as the preceding examples. However, since this example seeks to develop an inverse solution, you need to be careful about which signal carries the data and which is the desired signal. 5-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان RLS Adaptive Filters Earlier examples of adaptive filters use the filtered noise as the desired signal. In this case, the filtered noise (xdata) carries the unknown system information. With Gaussian distribution and variance of 1, the unfiltered noise d is the desired signal. The code to run this adaptive filter example is [y,e] = filter(ha,xdata,d); where y returns the coefficients of the adapted filter and e contains the error signal as the filter adapts to find the inverse of the unknown system. You can review the returned elements of the adapted filter in the properties of ha. The next figure presents the results of the adaptation. In the figure, the magnitude response curves for the unknown and adapted filters show. As a reminder, the unknown filter was a lowpass filter with cutoff at 0.55, on the normalized frequency scale from 0 to 1. Comparing the Inverse Filter to the Unknown System Magnitude (dB) 50 0 −50 −100 Inverse Filter Unknown System −150 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0 Phase (degrees) −200 −400 −600 −800 −1000 −1200 Viewed alone (refer to the following figure), the inverse system looks like a fair compensator for the unknown lowpass filter — a high pass filter with linear phase. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-35 5 Adaptive Filters Inverse Filter Resulting from RLS Adaptation 40 Magnitude (dB) 30 20 10 0 −10 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 Normalized Frequency (×π rad/sample) 0.8 0.9 1 0 Phase (degrees) −200 −400 −600 −800 −1000 −1200 5-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Enhancement Using LMS and Normalized LMS Signal Enhancement Using LMS and Normalized LMS In this section... “Create the Signals for Adaptation” on page 5-37 “Construct Two Adaptive Filters” on page 5-38 “Choose the Step Size” on page 5-38 “Set the Adapting Filter Step Size” on page 5-39 “Filter with the Adaptive Filters” on page 5-40 “Compute the Optimal Solution” on page 5-40 “Plot the Results” on page 5-40 “Compare the Final Coefficients” on page 5-42 “Reset the Filter Before Filtering” on page 5-43 “Investigate Convergence Through Learning Curves” on page 5-43 “Compute the Learning Curves” on page 5-44 “Compute the Theoretical Learning Curves” on page 5-45 This example illustrates one way to use a few of the adaptive filter algorithms provided in the toolbox. In this example, a signal enhancement application is used as an illustration. While there are about 30 different adaptive filtering algorithms included with the toolbox, this example demonstrates two algorithms — least means square (LMS), using adaptfilt.lms, and normalized LMS, using adaptfilt.nlms, for adaptation. Create the Signals for Adaptation The goal is to use an adaptive filter to extract a desired signal from a noise-corrupted signal by filtering out the noise. The desired signal (the output from the process) is a sinusoid with 1000 samples. n = (1:1000)'; s = sin(0.075*pi*n); To perform adaptation requires two signals: • a reference signal • a noisy signal that contains both the desired signal and an added noise component. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-37 5 Adaptive Filters Generate the Noise Signal To create a noise signal, assume that the noise v1 is autoregressive, meaning that the value of the noise at time t depends only on its previous values and on a random disturbance. v = 0.8*randn(1000,1); % Random noise part. ar = [1,1/2]; % Autoregression coefficients. v1 = filter(1,ar,v); % Noise signal. Applies a 1-D digital % filter. Corrupt the Desired Signal to Create a Noisy Signal To generate the noisy signal that contains both the desired signal and the noise, add the noise signal v1 to the desired signal s. The noise-corrupted sinusoid x is x = s + v1; where s is the desired signal and the noise is v1. Adaptive filter processing seeks to recover s from x by removing v1. To complete the signals needed to perform adaptive filtering, the adaptation process requires a reference signal. Create a Reference Signal Define a moving average signal v2 that is correlated with v1. This v2 is the reference signal for the examples. ma = [1, -0.8, 0.4 , -0.2]; v2 = filter(ma,1,v); Construct Two Adaptive Filters Two similar adaptive filters — LMS and NLMS — form the basis of this example, both sixth order. Set the order as a variable in MATLAB and create the filters. L = 7; hlms = adaptfilt.lms(7); hnlms = adaptfilt.nlms(7); Choose the Step Size LMS-like algorithms have a step size that determines the amount of correction applied as the filter adapts from one iteration to the next. Choosing the appropriate step size is not always easy, usually requiring experience in adaptive filter design. 5-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Enhancement Using LMS and Normalized LMS • A step size that is too small increases the time for the filter to converge on a set of coefficients. This becomes an issue of speed and accuracy. • One that is too large may cause the adapting filter to diverge, never reaching convergence. In this case, the issue is stability — the resulting filter might not be stable. As a rule of thumb, smaller step sizes improve the accuracy of the convergence of the filter to match the characteristics of the unknown, at the expense of the time it takes to adapt. The toolbox includes an algorithm — maxstep — to determine the maximum step size suitable for each LMS adaptive filter algorithm that still ensures that the filter converges to a solution. Often, the notation for the step size is µ. >> [mumaxlms,mumaxmselms] = maxstep(hlms,x) [mumaxnlms,mumaxmsenlms] = maxstep(hnlms); Warning: Step size is not in the range 0 < mu < mumaxmse/2: Erratic behavior might result. > In adaptfilt.lms.maxstep at 32 mumaxlms = 0.2096 mumaxmselms = 0.1261 Set the Adapting Filter Step Size The first output of maxstep is the value needed for the mean of the coefficients to converge while the second is the value needed for the mean squared coefficients to converge. Choosing a large step size often causes large variations from the convergence values, so choose smaller step sizes generally. hlms.StepSize = mumaxmselms/30; % This can also be set graphically: inspect(hlms) hnlms.StepSize = mumaxmsenlms/20; % This can also be set graphically: inspect(hnlms) If you know the step size to use, you can set the step size value with the step input argument when you create your filter. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-39 5 Adaptive Filters hlms = adaptfilt.lms(N,step); Adds the step input argument. Filter with the Adaptive Filters Now you have set up the parameters of the adaptive filters and you are ready to filter the noisy signal. The reference signal, v2, is the input to the adaptive filters. x is the desired signal in this configuration. Through adaptation, y, the output of the filters, tries to emulate x as closely as possible. Since v2 is correlated only with the noise component v1 of x, it can only really emulate v1. The error signal (the desired x), minus the actual output y, constitutes an estimate of the part of x that is not correlated with v2 — s, the signal to extract from x. [ylms,elms] = filter(hlms,v2,x); [ynlms,enlms] = filter(hnlms,v2,x); Compute the Optimal Solution For comparison, compute the optimal FIR Wiener filter. bw = firwiener(L-1,v2,x); % Optimal FIR Wiener filter yw = filter(bw,1,v2); % Estimate of x using Wiener filter ew = x - yw; % Estimate of actual sinusoid Plot the Results Plot the resulting denoised sinusoid for each filter — the Wiener filter, the LMS adaptive filter, and the NLMS adaptive filter — to compare the performance of the various techniques. plot(n(900:end),[ew(900:end), elms(900:end),enlms(900:end)]); legend('Wiener filter denoised sinusoid',... 'LMS denoised sinusoid', 'NLMS denoised sinusoid'); xlabel('Time index (n)'); ylabel('Amplitude'); 5-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Enhancement Using LMS and Normalized LMS As a reference point, include the noisy signal as a dotted line in the plot. hold on plot(n(900:end),x(900:end),'k:') xlabel('Time index (n)'); ylabel('Amplitude'); hold off www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-41 5 Adaptive Filters Compare the Final Coefficients Finally, compare the Wiener filter coefficients with the coefficients of the adaptive filters. While adapting, the adaptive filters try to converge to the Wiener coefficients. [bw.' hlms.Coefficients.' hnlms.Coefficients.'] ans = 1.0317 0.3555 0.1500 0.0848 0.1624 0.1079 0.0492 5-42 0.8879 0.1359 0.0036 0.0023 0.0810 0.0184 -0.0001 1.0712 0.4070 0.1539 0.0549 0.1098 0.0521 0.0041 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Enhancement Using LMS and Normalized LMS Reset the Filter Before Filtering Adaptive filters have a PersistentMemory property that you can use to reproduce experiments exactly. By default, the PersistentMemory is false. The states and the coefficients of the filter are reset before filtering and the filter does not remember the results from previous times you use the filter. For instance, the following successive calls produce the same output when PersistentMemory is false. [ylms,elms] = filter(hlms,v2,x); [ylms2,elms2] = filter(hlms,v2,x); To keep the history of the filter when filtering a new set of data, enable persistent memory for the filter by setting the PersistentMemory property to true. In this configuration, the filter uses the final states and coefficients from the previous run as the initial conditions for the next run and set of data. [ylms,elms] = filter(hlms,v2,x); hlms.PersistentMemory = true; [ylms2,elms2] = filter(hlms,v2,x); % No longer the same Setting the property value to true is useful when you are filtering large amounts of data that you partition into smaller sets and then feed into the filter using a for-loop construction. Investigate Convergence Through Learning Curves To analyze the convergence of the adaptive filters, look at the learning curves. The toolbox provides methods to generate the learning curves, but you need more than one iteration of the experiment to obtain significant results. This demonstration uses 25 sample realizations of the noisy sinusoids. n = (1:5000)'; s = sin(0.075*pi*n); nr = 25; v = 0.8*randn(5000,nr); v1 = filter(1,ar,v); x = repmat(s,1,nr) + v1; v2 = filter(ma,1,v); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-43 5 Adaptive Filters Compute the Learning Curves Now compute the mean-square error. To speed things up, compute the error every 10 samples. First, reset the adaptive filters to avoid using the coefficients it has already computed and the states it has stored. reset(hlms); reset(hnlms); M = 10; % Decimation factor mselms = msesim(hlms,v2,x,M); msenlms = msesim(hnlms,v2,x,M); plot(1:M:n(end),[mselms,msenlms]) legend('LMS learning curve','NLMS learning curve') xlabel('Time index (n)'); ylabel('MSE'); In the next plot you see the calculated learning curves for the LMS and NLMS adaptive filters. 5-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Signal Enhancement Using LMS and Normalized LMS Compute the Theoretical Learning Curves For the LMS and NLMS algorithms, functions in the toolbox help you compute the theoretical learning curves, along with the minimum mean-square error (MMSE) the excess mean-square error (EMSE) and the mean value of the coefficients. MATLAB may take some time to calculate the curves. The figure shown after the code plots the predicted and actual LMS curves. reset(hlms); [mmselms,emselms,meanwlms,pmselms] = msepred(hlms,v2,x,M); plot(1:M:n(end),[mmselms*ones(500,1),emselms*ones(500,1),... pmselms,mselms]) legend('MMSE','EMSE','predicted LMS learning curve',... 'LMS learning curve') xlabel('Time index (n)'); ylabel('MSE'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-45 5 Adaptive Filters Adaptive Filters in Simulink In this section... “Create an Acoustic Environment in Simulink” on page 5-46 “LMS Filter Configuration for Adaptive Noise Cancellation” on page 5-48 “Modify Adaptive Filter Parameters During Model Simulation” on page 5-54 “Adaptive Filtering Examples” on page 5-59 Create an Acoustic Environment in Simulink Adaptive filters are filters whose coefficients or weights change over time to adapt to the statistics of a signal. They are used in a variety of fields including communications, controls, radar, sonar, seismology, and biomedical engineering. In this topic, you learn how to create an acoustic environment that simulates both white noise and colored noise added to an input signal. You later use this environment to build a model capable of adaptive noise cancellation using adaptive filtering: 1 At the MATLAB command line, type dspanc. The DSP System Toolbox Acoustic Noise Cancellation example opens. 5-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink 2 Copy and paste the subsystem called Acoustic Environment into a new model. 3 Double-click the Acoustic Environment subsystem. Gaussian noise is used to create the signal sent to the Exterior Mic output port. If the input to the Filter port changes from 0 to 1, the Digital Filter block changes from a lowpass filter to a bandpass filter. The filtered noise output from the Digital Filter www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-47 5 Adaptive Filters block is added to signal coming from a .wav file to produce the signal sent to the Pilot's Mic output port. You have now created an acoustic environment. In the following topics, you use this acoustic environment to produce a model capable of adaptive noise cancellation. LMS Filter Configuration for Adaptive Noise Cancellation In the previous topic, “Create an Acoustic Environment in Simulink” on page 5-46, you created a system that produced two output signals. The signal output at the Exterior Mic port is composed of white noise. The signal output at the Pilot's Mic port is composed of colored noise added to a signal from a .wav file. In this topic, you create an adaptive filter to remove the noise from the Pilot's Mic signal. This topic assumes that you are working on a Windows operating system: 1 If the model you created in “Create an Acoustic Environment in Simulink” on page 5-46 is not open on your desktop, you can open an equivalent model by typing ex_adapt1_audio at the MATLAB command prompt. 2 From the DSP System Toolbox Filtering library, and then from the Adaptive Filters library, click-and-drag an LMS Filter block into the model that contains the Acoustic Environment subsystem. 3 Double-click the LMS Filter block. Set the block parameters as follows, and then click OK: • Algorithm = Normalized LMS • Filter length = 40 • Step size (mu) = 0.002 • Leakage factor (0 to 1) = 1 The block uses the normalized LMS algorithm to calculate the forty filter coefficients. Setting the Leakage factor (0 to 1) parameter to 1 means that the current filter coefficient values depend on the filter's initial conditions and all of the previous input values. 4 5-48 Click-and-drag the following blocks into your model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink 5 Block Library Quantity Constant Simulink/Sources 2 Manual Switch Simulink/Signal Routing 1 Terminator Simulink/Sinks 1 Downsample Signal Operations 1 To Audio Device Sinks 1 Waterfall Scope Sinks 1 Connect the blocks so that your model resembles the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-49 5 Adaptive Filters 5-50 6 Double-click the Constant block. Set the Constant value parameter to 0 and then click OK. 7 Double-click the Downsample block. Set the Downsample factor, K parameter to 32. Click OK. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink The filter weights are being updated so often that there is very little change from one update to the next. To see a more noticeable change, you need to downsample the output from the Wts port. 8 Double-click the Waterfall Scope block. The Waterfall scope window opens. 9 Click the Scope parameters button. The Parameters window opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-51 5 Adaptive Filters 10 Click the Axes tab. Set the parameters as follows: • Y Min = -0.188 • Y Max = 0.179 11 Click the Data history tab. Set the parameters as follows: • History traces = 50 • Data logging = All visible 12 Close the Parameters window leaving all other parameters at their default values. You might need to adjust the axes in the Waterfall scope window in order to view the plots. 13 Click the Fit to view button in the Waterfall scope window. Then, click-and-drag the axes until they resemble the following figure. 5-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink 14 In the model window, from the Simulation menu, select Model Configuration Parameters. In the Select pane, click Solver. Set the parameters as follows, and then click OK: • Stop time = inf • Type = Fixed-step • Solver = Discrete (no continuous states) 15 Run the simulation and view the results in the Waterfall scope window. You can also listen to the simulation using the speakers attached to your computer. 16 Experiment with changing the Manual Switch so that the input to the Acoustic Environment subsystem is either 0 or 1. When the value is 0, the Gaussian noise in the signal is being filtered by a lowpass filter. When the value is 1, the noise is being filtered by a bandpass filter. The adaptive filter can remove the noise in both cases. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-53 5 Adaptive Filters You have now created a model capable of adaptive noise cancellation. The adaptive filter in your model is able to filter out both low frequency noise and noise within a frequency range. In the next topic, “Modify Adaptive Filter Parameters During Model Simulation” on page 5-54, you modify the LMS Filter block and change its parameters during simulation. Modify Adaptive Filter Parameters During Model Simulation In the previous topic, “LMS Filter Configuration for Adaptive Noise Cancellation” on page 5-48, you created an adaptive filter and used it to remove the noise generated by the Acoustic Environment subsystem. In this topic, you modify the adaptive filter and adjust its parameters during simulation. This topic assumes that you are working on a Windows operating system: 1 If the model you created in “Create an Acoustic Environment in Simulink” on page 5-46 is not open on your desktop, you can open an equivalent model by typing ex_adapt2_audio at the MATLAB command prompt. 2 Double-click the LMS filter block. Set the block parameters as follows, and then click OK: • Specify step size via = Input port • Initial value of filter weights = 0 • Select the Adapt port check box. • Reset port = Non-zero sample The Block Parameters: LMS Filter dialog box should now look similar to the following figure. 5-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink Step-size, Adapt, and Reset ports appear on the LMS Filter block. 3 Click-and-drag the following blocks into your model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-55 5 Adaptive Filters 4 5-56 Block Library Quantity Constant Simulink/Sources 6 Manual Switch Simulink/Signal Routing 3 Connect the blocks as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-57 5 Adaptive Filters 5 Double-click the Constant2 block. Set the block parameters as follows, and then click OK: • Constant value = 0.002 • Select the Interpret vector parameters as 1-D check box. • Sample time (-1 for inherited) = inf • Output data type mode = Inherit via back propagation 6 Double-click the Constant3 block. Set the block parameters as follows, and then click OK: • Constant value = 0.04 • Select the Interpret vector parameters as 1-D check box. • Sample time (-1 for inherited) = inf • Output data type mode = Inherit via back propagation 7 Double-click the Constant4 block. Set the Constant value parameter to 0 and then click OK. 8 Double-click the Constant6 block. Set the Constant value parameter to 0 and then click OK. 9 In the model window, from the Display menu, point to Signals & Ports, and select Wide Nonscalar Lines and Signal Dimensions. 10 Double-click Manual Switch2 so that the input to the Adapt port is 1. 11 Run the simulation and view the results in the Waterfall scope window. You can also listen to the simulation using the speakers attached to your computer. 12 Double-click the Manual Switch block so that the input to the Acoustic Environment subsystem is 1. Then, double-click Manual Switch2 so that the input to the Adapt port to 0. The filter weights displayed in the Waterfall scope window remain constant. When the input to the Adapt port is 0, the filter weights are not updated. 13 Double-click Manual Switch2 so that the input to the Adapt port is 1. The LMS Filter block updates the coefficients. 14 Connect the Manual Switch1 block to the Constant block that represents 0.002. Then, change the input to the Acoustic Environment subsystem. Repeat this procedure with the Constant block that represents 0.04. 5-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters in Simulink You can see that the system reaches steady state faster when the step size is larger. 15 Double-click the Manual Switch3 block so that the input to the Reset port is 1. The block resets the filter weights to their initial values. In the Block Parameters: LMS Filter dialog box, from the Reset port list, you chose Non-zero sample. This means that any nonzero input to the Reset port triggers a reset operation. You have now experimented with adaptive noise cancellation using the LMS Filter block. You adjusted the parameters of your adaptive filter and viewed the effects of your changes while the model was running. For more information about adaptive filters, see the following block reference pages: • LMS Filter • RLS Filter • Block LMS Filter • Fast Block LMS Filter Adaptive Filtering Examples DSP System Toolbox software provides a collection of adaptive filtering examples that illustrate typical applications of the adaptive filtering blocks, listed in the following table. Adaptive Filtering Examples Commands for Opening Examples in MATLAB LMS Adaptive Equalization lmsadeq LMS Adaptive Time-Delay Estimation lmsadtde Nonstationary Channel Estimation dspchanest RLS Adaptive Noise Cancellation rlsdemo www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 5-59 5 Adaptive Filters Selected Bibliography [1] Hayes, Monson H., Statistical Digital Signal Processing and Modeling, John Wiley & Sons, 1996, 493–552. [2] Haykin, Simon, Adaptive Filter Theory, Prentice-Hall, Inc., 1996 5-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 Multirate and Multistage Filters Learn how to analyze, design, and implement multirate and multistage filters in MATLAB and Simulink. • “Multirate Filters” on page 6-2 • “Multistage Filters” on page 6-6 • “Example Case for Multirate/Multistage Filters” on page 6-7 • “Filter Banks” on page 6-11 • “Multirate Filtering in Simulink” on page 6-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6 Multirate and Multistage Filters Multirate Filters In this section... “Why Are Multirate Filters Needed?” on page 6-2 “Overview of Multirate Filters” on page 6-2 Why Are Multirate Filters Needed? Multirate filters can bring efficiency to a particular filter implementation. In general, multirate filters are filters in which different parts of the filter operate at different rates. The most obvious application of such a filter is when the input sample rate and output sample rate need to differ (decimation or interpolation) — however, multirate filters are also often used in designs where this is not the case. For example you may have a system where the input sample rate and output sample rate are the same, but internally there is decimation and interpolation occurring in a series of filters, such that the final output of the system has the same sample rate as the input. Such a design may exhibit lower cost than could be achieved with a single-rate filter for various reasons. For more information about the relative cost benefit of using multirate filters, refer to [2] Harris, Fredric J., Multirate Signal Processing for Communication Systems, Prentice Hall PTR, 2004. Overview of Multirate Filters A filter that reduces the input rate is called a decimator. A filter that increases the input rate is called an interpolator. To visualize this process, examine the following figure, which illustrates the processes of interpolation and decimation in the time domain. 6-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Multirate Filters If you start with the top signal, sampled at a frequency Fs, then the bottom signal is sampled at Fs/2 frequency. In this case, the decimation factor, or M, is 2. The following figure illustrates effect of decimation in the frequency domain. In the first graphic in the figure you can see a signal that is critically sampled, i.e. the sample rate is equal to two times the highest frequency component of the sampled www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-3 6 Multirate and Multistage Filters signal. As such the period of the signal in the frequency domain is no greater than the bandwidth of the sampling frequency. When reduce the sampling frequency (decimation), aliasing can occur, where the magnitudes at the frequencies near the edges of the original period become indistinguishable, and the information about these values becomes lost. To work around this problem, the signal can be filtered before the decimation process, avoiding overlap of the signal spectra at Fs/2. An analogous approach must be taken to avoid imaging when performing interpolation on a sampled signal. For more information about the effects of decimation and interpolation on a sampled signal, refer to any one of the references in the “Bibliography” section of the DSP System Toolbox User Guide. The following list summarizes some guidelines and general requirements regarding decimation and interpolation: • By the Nyquist Theorem, for band-limited signals, the sampling frequency must be at least twice the bandwidth of the signal. For example, if you have a lowpass filter with the highest frequency of 10 MHz, and a sampling frequency of 60 MHz, the highest frequency that can be handled by the system without aliasing is 60/2=30, which is greater than 10. You could safely set M=2 in this case, since (60/2)/2=15, which is still greater than 10. • If you wish to decimate a signal which does not meet the frequency criteria, you can either: • Interpolate first, and then decimate 6-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Multirate Filters • When decimating, you should apply the filter first, then perform the decimation. When interpolating a signal, you should interpolate first, then filter the signal. • Typically in decimation of a signal a filter is applied first, thereby allowing decimation without aliasing, as shown in the following figure: • Conversely, a filter is typically applied after interpolation to avoid imaging: • M must be an integer. Although, if you wish to obtain an M of 4/5, you could interpolate by 4, and then decimate by 5, provided that frequency restrictions are met. This type of multirate filter will be referred to as a sample rate converter in the documentation that follows. Multirate filters are most often used in stages. This technique is introduced in the following section. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-5 6 Multirate and Multistage Filters Multistage Filters In this section... “Why Are Multistage Filters Needed?” on page 6-6 “Optimal Multistage Filters in DSP System Toolbox” on page 6-6 Why Are Multistage Filters Needed? Typically used with multirate filters, multistage filters can bring efficiency to a particular filter implementation. Multistage filters are composed of several filters. These different parts of the mulitstage filter, called stages, are connected in a cascade or in parallel. However such a design can conserve resources in many cases. There are many different uses for a multistage filter. One of these is a filter requirement that includes a very narrow transition width. For example, you need to design a lowpass filter where the difference between the pass frequency and the stop frequency is .01 (normalized). For such a requirement it is possible to design a single filter, but it will be very long (containing many coefficients) and very costly (having many multiplications and additions per input sample). Thus, this single filter may be so costly and require so much memory, that it may be impractical to implement in certain applications where there are strict hardware requirements. In such cases, a multistage filter is a great solution. Another application of a multistage filter is for a mulitrate system, where there is a decimator or an interpolator with a large factor. In these cases, it is usually wise to break up the filter into several multirate stages, each comprising a multiple of the total decimation/interpolation factor. Optimal Multistage Filters in DSP System Toolbox As described in the previous section, within a multirate filter each interconnected filter is called a stage. While it is possible to design a multistage filter manually, it is also possible to perform automatic optimization of a multistage filter automatically. When designing a filter manually it can be difficult to guess how many stages would provide an optimal design, optimize each stage, and then optimize all the stages together. DSP System Toolbox software enables you to create a Specifications Object, and then design a filter using multistage as an option. The rest of the work is done automatically. Not only does DSP System Toolbox software determine the optimal number of stages, but it also optimizes the total filter solution. 6-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Example Case for Multirate/Multistage Filters Example Case for Multirate/Multistage Filters In this section... “Example Overview” on page 6-7 “Single-Rate/Single-Stage Equiripple Design” on page 6-7 “Reduce Computational Cost Using Mulitrate/Multistage Design” on page 6-8 “Compare the Responses” on page 6-8 “Further Performance Comparison” on page 6-9 Example Overview This example shows the efficiency gains that are possible when using multirate and multistage filters for certain applications. In this case a distinct advantage is achieved over regular linear-phase equiripple design when a narrow transition-band width is required. A more detailed treatment of the key points made here can be found in the example entitled Efficient Narrow Transition-Band FIR Filter Design. Single-Rate/Single-Stage Equiripple Design Consider the following design specifications for a lowpass filter (where the ripples are given in linear units): Fpass Fstop Rpass Rstop = = = = 0.13; 0.14; 0.001; 0.0005; % % % % Passband Stopband Passband Stopband edge edge ripple, 0.0174 dB peak to peak ripple, 66.0206 dB minimum attenuation Hf = fdesign.lowpass(Fpass,Fstop,Rpass,Rstop,'linear'); A regular linear-phase equiripple design using these specifications can be designed by evaluating the following: Hd = design(Hf,'equiripple'); When you determine the cost of this design, you can see that 695 multipliers are required. cost(Hd) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-7 6 Multirate and Multistage Filters Reduce Computational Cost Using Mulitrate/Multistage Design The number of multipliers required by a filter using a single state, single rate equiripple design is 694. This number can be reduced using multirate/multistage techniques. In any single-rate design, the number of multiplications required by each input sample is equal to the number of non-zero multipliers in the implementation. However, by using a multirate/multistage design, decimation and interpolation can be combined to lessen the computation required. For decimators, the average number of multiplications required per input sample is given by the number of multipliers divided by the decimation factor. Hd_multi = design(Hf,'multistage'); You can then view the cost of the filter created using this design step, and you can see that a significant cost advantage has been achieved. cost(Hd_multi) Compare the Responses You can compare the responses of the equiripple design and this multirate/multistage design using fvtool: hfvt = fvtool(Hd,Hd_multi); legend(hfvt,'Equiripple design', 'Multirate/multistage design') 6-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Example Case for Multirate/Multistage Filters Notice that the stopband attenuation for the multistage design is about twice that of the other designs. This is because the decimators must attenuate out-of-band components by 66 dB in order to avoid aliasing that would violate the specifications. Similarly, the interpolators must attenuate images by 66 dB. You can also see that the passband gain for this design is no longer 0 dB, because each interpolator has a nominal gain (in linear units) equal to its interpolation factor, and the total interpolation factor for the three interpolators is 6. Further Performance Comparison You can check the performance of the multirate/multistage design by plotting the power spectral densities of the input and the various outputs, and you can see that the sinusoid at 0 .4 p is attenuated comparably by both the equiripple design and the multirate/ multistage design. n x y y_multi = = = = 0:1799; sin(0.1*pi*n') + 2*sin(0.15*pi*n'); filter(Hd,x); filter(Hd_multi,x); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-9 6 Multirate and Multistage Filters [Pxx,w] = periodogram(x); Pyy = periodogram(y); Pyy_multi = periodogram(y_multi); plot(w/pi,10*log10([Pxx,Pyy,Pyy_multi])); xlabel('Normalized Frequency (x\pi rad/sample)'); ylabel('Power density (dB/rad/sample)'); legend('Input signal PSD','Equiripple output PSD',... 'Multirate/multistage output PSD') axis([0 1 -50 30]) grid on 6-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Banks Filter Banks Multirate filters alter the sample rate of the input signal during the filtering process. Such filters are useful in both rate conversion and filter bank applications. The Dyadic Analysis Filter Bank block decomposes a broadband signal into a collection of subbands with smaller bandwidths and slower sample rates. The Dyadic Synthesis Filter Bank block reconstructs a signal decomposed by the Dyadic Analysis Filter Bank block. To use a dyadic synthesis filter bank to perfectly reconstruct the output of a dyadic analysis filter bank, the number of levels and tree structures of both filter banks must be the same. In addition, the filters in the synthesis filter bank must be designed to perfectly reconstruct the outputs of the analysis filter bank. Otherwise, the reconstruction will not be perfect. Dyadic Analysis Filter Banks Dyadic analysis filter banks are constructed from the following basic unit. The unit can be cascaded to construct dyadic analysis filter banks with either a symmetric or asymmetric tree structure. Each unit consists of a lowpass (LP) and highpass (HP) FIR filter pair, followed by a decimation by a factor of 2. The filters are halfband filters with a cutoff frequency of Fs / 4, a quarter of the input sampling frequency. Each filter passes the frequency band that the other filter stops. The unit decomposes its input into adjacent high-frequency and low-frequency subbands. Compared to the input, each subband has half the bandwidth (due to the half-band filters) and half the sample rate (due to the decimation by 2). Note The following figures illustrate the concept of a filter bank, but not how the block implements a filter bank; the block uses a more efficient polyphase implementation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-11 6 Multirate and Multistage Filters n-Level Asymmetric Dyadic Analysis Filter Bank Use the above figure and the following figure to compare the two tree structures of the dyadic analysis filter bank. Note that the asymmetric structure decomposes only the lowfrequency output from each level, while the symmetric structure decomposes the highand low-frequency subbands output from each level. 6-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Banks n-Level Symmetric Dyadic Analysis Filter Bank The following table summarizes the key characteristics of the symmetric and asymmetric dyadic analysis filter bank. Notable Characteristics of Asymmetric and Symmetric Dyadic Analysis Filter Banks Characteristic N-Level Symmetric Low- and HighAll the low-frequency Frequency Subband and high-frequency subbands in a level are Decomposition decomposed in the next level. N-Level Asymmetric Each level's low-frequency subband is decomposed in the next level, and each level's high-frequency band is an output of the filter bank. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-13 6 Multirate and Multistage Filters Characteristic Number of Output Subbands N-Level Symmetric n 2 N-Level Asymmetric n+1 Bandwidth and For an input with For an input with bandwidth BW and N samples, yk has the bandwidth BWk, and Nk samples, Number of Samples bandwidth BW in Output Subbands and N samples, where all outputs have bandwidth BW / 2n and ÏÔ BW / 2k (1 £ k £ n) n BW = Ì k N / 2 samples. n (k = n + 1) ÓÔ BW / 2 k ÔÏ N / 2 (1 £ k £ n) Nk = Ì n ( k = n + 1) ÓÔ N / 2 The bandwidth of, and number of samples in each subband (except the last) is half those of the previous subband. The last two subbands have the same bandwidth and number of samples since they originate from the same level in the filter bank. Output Sample Period All output subbands Sample period of kth output have a sample period of 2n(Tsi) ÏÔ 2k ( T ) (1 £ k £ n) si =Ì n ÔÓ2 (Tsi ) (k = n + 1) Due to the decimations by 2, the sample period of each subband (except the last) is twice that of the previous subband. The last two subbands have the same sample period since they originate from the same level in the filter bank. Total Number of Output Samples 6-14 The total number of samples in all of the output subbands is equal to the number of samples in the input (due to the of decimations by 2 at each level). www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Banks Characteristic N-Level Symmetric N-Level Asymmetric Wavelet Applications In wavelet applications, the highpass and lowpass wavelet-based filters are designed so that the aliasing introduced by the decimations are exactly canceled in reconstruction. Dyadic Synthesis Filter Banks Dyadic synthesis filter banks are constructed from the following basic unit. The unit can be cascaded to construct dyadic synthesis filter banks with either a asymmetric or symmetric tree structure as illustrated in the figures entitled n-Level Asymmetric Dyadic Synthesis Filter Bank and n-Level Symmetric Dyadic Synthesis Filter Bank. Each unit consists of a lowpass (LP) and highpass (HP) FIR filter pair, preceded by an interpolation by a factor of 2. The filters are halfband filters with a cutoff frequency of Fs / 4, a quarter of the input sampling frequency. Each filter passes the frequency band that the other filter stops. The unit takes in adjacent high-frequency and low-frequency subbands, and reconstructs them into a wide-band signal. Compared to each subband input, the output has twice the bandwidth and twice the sample rate. Note The following figures illustrate the concept of a filter bank, but not how the block implements a filter bank; the block uses a more efficient polyphase implementation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-15 6 Multirate and Multistage Filters n-Level Asymmetric Dyadic Synthesis Filter Bank Use the above figure and the following figure to compare the two tree structures of the dyadic synthesis filter bank. Note that in the asymmetric structure, the low-frequency subband input to each level is the output of the previous level, while the high-frequency subband input to each level is an input to the filter bank. In the symmetric structure, both the low- and high-frequency subband inputs to each level are outputs from the previous level. 6-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filter Banks n-Level Symmetric Dyadic Synthesis Filter Bank The following table summarizes the key characteristics of symmetric and asymmetric dyadic synthesis filter banks. Notable Characteristics of Asymmetric and Symmetric Dyadic Synthesis Filter Banks Characteristic N-Level Symmetric N-Level Asymmetric Input Paths Through the Filter Bank Both the high-frequency and lowfrequency input subbands to each level (except the first) are the outputs of the previous level. The inputs to the first level are the inputs to the filter bank. The low-frequency subband input to each level (except the first) is the output of the previous level. The lowfrequency subband input to the first level, and the high-frequency subband input to each level, are inputs to the filter bank. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-17 6 Multirate and Multistage Filters Characteristic N-Level Symmetric N-Level Asymmetric Number of Input Subbands 2 n+1 Bandwidth and Number of Samples in Input Subbands All inputs subbands have bandwidth BW / 2n and N / 2n samples, where the output has bandwidth BW and N samples. For an output with bandwidth BW and N samples, the kth input subband has the following bandwidth and number of samples. n ÏÔ BW / 2k BWk = Ì n ÓÔ BW / 2 (1 £ k £ n) (k = n + 1) ÏÔ N / 2 k (1 £ k £ n) Nk = Ì n ( k = n + 1) ÓÔ N / 2 Input Sample Periods All input subbands have a sample period of 2n(Tso), where the output sample period is Tso. Sample period of kth input subband ÏÔ 2k ( T ) (1 £ k £ n) so =Ì n ÓÔ2 (Tso ) ( k = n + 1 ) where the output sample period is Tso. Total Number of Input Samples The number of samples in the output is always equal to the total number of samples in all of the input subbands. Wavelet Applications In wavelet applications, the highpass and lowpass wavelet-based filters are carefully selected so that the aliasing introduced by the decimation in the dyadic analysis filter bank is exactly canceled in the reconstruction of the signal in the dyadic synthesis filter bank. For more information, see “Dyadic Synthesis Filter Bank”. 6-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Multirate Filtering in Simulink Multirate Filtering in Simulink DSP System Toolbox software provides a collection of multirate filtering examples that illustrate typical applications of the multirate filtering blocks. Multirate Filtering Examples Description Command for Opening Examples in MATLAB Audio Sample Rate Conversion Illustrates sample rate conversion of an audio signal dspaudiosrc from 22.050 kHz to 8 kHz using a multirate FIR rate conversion approach Sigma-Delta A/D Converter Illustrates analog-to-digital conversion using a sigma- dspsdadc delta algorithm implementation Wavelet Reconstruction and Noise Reduction Uses the Dyadic Analysis Filter Bank and Dyadic Synthesis Filter Bank blocks to show both the perfect reconstruction property of wavelets and an application for noise reduction www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان dspwavelet 6-19 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 6-20 7 Transforms, Estimation, and Spectral Analysis Learn about transforms, estimation and spectral analysis. • “Transform Time-Domain Data into Frequency Domain” on page 7-2 • “Transform Frequency-Domain Data into Time Domain” on page 7-7 • “Linear and Bit-Reversed Output Order” on page 7-12 • “Calculate Channel Latencies Required for Wavelet Reconstruction” on page 7-14 • “Spectral Analysis” on page 7-23 • “Power Spectrum Estimates” on page 7-24 • “Spectrograms” on page 7-35 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Transforms, Estimation, and Spectral Analysis Transform Time-Domain Data into Frequency Domain When you want to transform time-domain data into the frequency domain, use the FFT block. In this example, you use the Sine Wave block to generate two sinusoids, one at 15 Hz and the other at 40 Hz. You sum the sinusoids point-by-point to generate the compound sinusoid u = sin ( 30p t ) + sin ( 80p t) Then, you transform this sinusoid into the frequency domain using an FFT block: 1 At the MATLAB command prompt, type ex_fft_tut. The FFT Example opens. 7-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Transform Time-Domain Data into Frequency Domain 2 Double-click the Sine Wave block. The Block Parameters: Sine Wave dialog box opens. 3 Set the block parameters as follows: • Amplitude = 1 • Frequency = [15 40] • Phase offset = 0 • Sample time = 0.001 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-3 7 Transforms, Estimation, and Spectral Analysis • Samples per frame = 128 Based on these parameters, the Sine Wave block outputs two sinusoidal signals with identical amplitudes, phases, and sample times. One sinusoid oscillates at 15 Hz and the other at 40 Hz. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Matrix Sum block. The Block Parameters: Matrix Sum dialog box opens. 6 Set the Sum over parameter to Specified dimension and the Dimension parameter to 2. Click OK to save your changes. Because each column represents a different signal, you need to sum along the individual rows in order to add the values of the sinusoids at each time step. 7 Double-click the Complex to Magnitude-Angle block. The Block Parameters: Complex to Magnitude-Angle dialog box opens. 8 Set the Output parameter to Magnitude, and then click OK. This block takes the complex output of the FFT block and converts this output to magnitude. 9 Double-click the Vector Scope block. 10 Set the block parameters as follows, and then click OK: • Click the Scope Properties tab. • Input domain = Frequency • Click the Axis Properties tab. • Frequency units = Hertz (This corresponds to the units of the input signals.) • Frequency range = [0...Fs/2] • Select the Inherit sample time from input check box. • Amplitude scaling = Magnitude 11 Run the model. The scope shows the two peaks at 15 and 40 Hz, as expected. 7-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Transform Time-Domain Data into Frequency Domain You have now transformed two sinusoidal signals from the time domain to the frequency domain. Note that the sequence of FFT, Complex to Magnitude-Angle, and Vector Scope blocks could be replaced by a single Spectrum Analyzer block, which computes the magnitude FFT internally. Other blocks that compute the FFT internally are the blocks in the www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-5 7 Transforms, Estimation, and Spectral Analysis Power Spectrum Estimation library. See “Spectral Analysis” on page 7-23 for more information about these blocks. 7-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Transform Frequency-Domain Data into Time Domain Transform Frequency-Domain Data into Time Domain When you want to transform frequency-domain data into the time domain, use the IFFT block. In this example, you use the Sine Wave block to generate two sinusoids, one at 15 Hz and the other at 40 Hz. You sum the sinusoids point-by-point to generate the compound sinusoid, u = sin ( 30p t ) + sin(80p t) . You transform this sinusoid into the frequency domain using an FFT block, and then immediately transform the frequency-domain signal back to the time domain using the IFFT block. Lastly, you plot the difference between the original time-domain signal and transformed time-domain signal using a scope: 1 At the MATLAB command prompt, type ex_ifft_tut. The IFFT Example opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-7 7 Transforms, Estimation, and Spectral Analysis 2 Double-click the Sine Wave block. The Block Parameters: Sine Wave dialog box opens. 3 Set the block parameters as follows: • Amplitude = 1 • Frequency = [15 40] • Phase offset = 0 • Sample time = 0.001 • Samples per frame = 128 7-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Transform Frequency-Domain Data into Time Domain Based on these parameters, the Sine Wave block outputs two sinusoidal signals with identical amplitudes, phases, and sample times. One sinusoid oscillates at 15 Hz and the other at 40 Hz. 4 Save these parameters and close the dialog box by clicking OK. 5 Double-click the Matrix Sum block. The Block Parameters: Matrix Sum dialog box opens. 6 Set the Sum over parameter to Specified dimension and the Dimension parameter to 2. Click OK to save your changes. Because each column represents a different signal, you need to sum along the individual rows in order to add the values of the sinusoids at each time step. 7 Double-click the FFT block. The Block Parameters: FFT dialog box opens. 8 Select the Output in bit-reversed order check box., and then click OK. 9 Double-click the IFFT block. The Block Parameters: IFFT dialog box opens. 10 Set the block parameters as follows, and then click OK: • Select the Input is in bit-reversed order check box. • Select the Input is conjugate symmetric check box. Because the original sinusoidal signal is real valued, the output of the FFT block is conjugate symmetric. By conveying this information to the IFFT block, you optimize its operation. Note that the Sum block subtracts the original signal from the output of the IFFT block, which is the estimation of the original signal. 11 Double-click the Vector Scope block. 12 Set the block parameters as follows, and then click OK: • Click the Scope Properties tab. • Input domain = Time 13 Run the model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-9 7 Transforms, Estimation, and Spectral Analysis The flat line on the scope suggests that there is no difference between the original signal and the estimate of the original signal. Therefore, the IFFT block has accurately reconstructed the original time-domain signal from the frequency-domain input. 14 Right-click in the Vector Scope window, and select Autoscale. 7-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Transform Frequency-Domain Data into Time Domain In actuality, the two signals are identical to within round-off error. The previous figure shows the enlarged trace. The differences between the two signals is on the order of 10-15. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-11 7 Transforms, Estimation, and Spectral Analysis Linear and Bit-Reversed Output Order In this section... “FFT and IFFT Blocks Data Order” on page 7-12 “Find the Bit-Reversed Order of Your Frequency Indices” on page 7-12 FFT and IFFT Blocks Data Order The FFT block enables you to output the frequency indices in linear or bit-reversed order. Because linear ordering of the frequency indices requires a bit-reversal operation, the FFT block may run more quickly when the output frequencies are in bit-reversed order. The input to the IFFT block can be in linear or bit-reversed order. Therefore, you do not have to alter the ordering of your data before transforming it back into the time domain. However, the IFFT block may run more quickly when the input is provided in bit-reversed order. Find the Bit-Reversed Order of Your Frequency Indices Two numbers are bit-reversed values of each other when the binary representation of one is the mirror image of the binary representation of the other. For example, in a threebit system, one and four are bit-reversed values of each other, since the three-bit binary representation of one, 001, is the mirror image of the three-bit binary representation of four, 100. In the diagram below, the frequency indices are in linear order. To put them in bit-reversed order 1 Translate the indices into their binary representation with the minimum number of bits. In this example, the minimum number of bits is three because the binary representation of 7 is 111. 2 Find the mirror image of each binary entry, and write it beside the original binary representation. 3 Translate the indices back to their decimal representation. The frequency indices are now in bit-reversed order. 7-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Linear and Bit-Reversed Output Order The next diagram illustrates the linear and bit-reversed outputs of the FFT block. The output values are the same, but they appear in different order. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-13 7 Transforms, Estimation, and Spectral Analysis Calculate Channel Latencies Required for Wavelet Reconstruction In this section... “Analyze Your Model” on page 7-14 “Calculate the Group Delay of Your Filters” on page 7-16 “Reconstruct the Filter Bank System” on page 7-18 “Equalize the Delay on Each Filter Path” on page 7-18 “Update and Run the Model” on page 7-21 “References” on page 7-22 Analyze Your Model The following sections guide you through the process of calculating the channel latencies required for perfect wavelet reconstruction. This example uses the ex_wavelets model, but you can apply the process to perform perfect wavelet reconstruction in any model. To open the example model, type ex_wavelets at the MATLAB command line. Note: You must have a Wavelet Toolbox™ product license to run the ex_wavelets model. 7-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Calculate Channel Latencies Required for Wavelet Reconstruction Before you can begin calculating the latencies required for perfect wavelet reconstruction, you must know the types of filters being used in your model. The Dyadic Analysis Filter Bank and the Dyadic Synthesis Filter Bank blocks in the ex_wavelets model have the following settings: • Filter = Biorthogonal • Filter order [synthesis/analysis] = [3/5] • Number of levels = 3 • Tree structure = Asymmetric • Input = Multiple ports Based on these settings, the “Dyadic Analysis Filter Bank” and the “Dyadic Synthesis Filter Bank” blocks construct biorthogonal filters using the Wavelet Toolbox wfilters function. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-15 7 Transforms, Estimation, and Spectral Analysis Calculate the Group Delay of Your Filters Once you know the types of filters being used by the Dyadic Analysis and Dyadic Synthesis Filter Bank blocks, you need to calculate the group delay of those filters. To do so, you can use the Signal Processing Toolbox fvtool. Before you can use fvtool, you must first reconstruct the filters in the MATLAB workspace. To do so, type the following code at the MATLAB command line: [Lo_D, Hi_D, Lo_R, Hi_R] = wfilters('bior3.5') Where Lo_D and Hi_D represent the low- and high-pass filters used by the Dyadic Analysis Filter Bank block, and Lo_R and Hi_R represent the low- and high-pass filters used by the Dyadic Synthesis Filter Bank block. After you construct the filters in the MATLAB workspace, you can use fvtool to determine the group delay of the filters. To analyze the low-pass biorthogonal filter used by the Dyadic Analysis Filter Bank block, you must do the following: • Type fvtool(Lo_D) at the MATLAB command line to launch the Filter Visualization Tool. • When the Filter Visualization Tool opens, click the Group delay response button ( on the toolbar, or select Group Delay Response from the Analysis menu. Based on the Filter Visualization Tool's analysis, you can see that the group delay of the Dyadic Analysis Filter Bank block's low-pass biorthogonal filter is 5.5. 7-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان ) Calculate Channel Latencies Required for Wavelet Reconstruction Note: Repeat this procedure to analyze the group delay of each of the filters in your model. This section does not show the results for each filter in the ex_wavelets model because all wavelet filters in this particular example have the same group delay. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-17 7 Transforms, Estimation, and Spectral Analysis Reconstruct the Filter Bank System To determine the delay introduced by the analysis and synthesis filter bank system, you must reconstruct the tree structures of the Dyadic Analysis Filter Bank and the Dyadic Synthesis Filter Bank blocks. To learn more about constructing tree structures for the Dyadic Analysis Filter Bank and Dyadic Synthesis Filter Bank blocks, see the following sections of the DSP System Toolbox User's Guide: • “Dyadic Analysis Filter Banks” • “Dyadic Synthesis Filter Banks” Because the filter blocks in the ex_wavelets model use biorthogonal filters with three levels and an asymmetric tree structure, the filter bank system appears as shown in the following figure. Delay N F1 2 F0 2 F1 2 F0 2 F0 2 F1 2 2 F0 2 F0 2 F0 2 2 2 G1 Path 4 2 G1 2 G0 Path 3 G1 2 G0 2 G0 Path 2 G0 2 G0 2 G0 Path 1 Delay M F0 = Delay due to low-pass filter of Dyadic Analysis Filter Bank F1 = Delay due to high-pass filter of Dyadic Analysis Filter Bank G0 = Delay due to low-pass filter of Dyadic Synthesis Filter Bank G1 = Delay due to high-pass filter of Dyadic Synthesis Filter Bank The extra delay values of M and N on paths 3 and 4 in the previous figure ensure that the total delay on each of the four filter paths is identical. Equalize the Delay on Each Filter Path Now that you have reconstructed the filter bank system, you can calculate the delay on each filter path. To do so, use the following Noble identities: 7-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Calculate Channel Latencies Required for Wavelet Reconstruction First Noble Identity z-2 2 Equivalent to 2 z-1 z-1 2 Second Noble Identity 2 z-2 Equivalent to You can apply the Noble identities by summing the delay on each signal path from right to left. The first Noble identity indicates that moving a delay of 1 before a downsample of 2 is equivalent to multiplying that delay value by 2. Similarly, the second Noble identity indicates that moving a delay of 2 before an upsample of 2 is equivalent to dividing that delay value by 2. The fvtool analysis in step 1 found that both the low- and high-pass filters of the analysis filter bank have the same group delay (F0 = F1 = 5.5). Thus, you can use F to represent the group delay of the analysis filter bank. Similarly, the group delay of the low- and high-pass filters of the synthesis filter bank is the same (G0=G1=5.5), so you can use G to represent the group delay of the synthesis filter bank. The following figure shows the filter bank system with the intermediate delay sums displayed below each path. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-19 7 Transforms, Estimation, and Spectral Analysis F 2N+(F+G) Delay N 2 2N+G F N+0.5G 2 F 7(F+G) 2 6F+7G F 7(F+G) 3F+3.5G 2 6F+7G F 3F+3.5G 0.5G Delay M 2 4M+3(F+G) 4M+2F+3G 2M+F+1.5G 2M+1.5G F 2 2 F 2F+3.5G F+1.75G 1.75G F 2 F 2F+3.5G F+1.75G 1.75G 0.75G 2 0.875G 2 0.875G 2 G 1.75G 2 1.75G 1.5G G 0.75G 0.5G 1.5G G Path 3 G Path 2 G Path 1 1.5G G 2 0.5G G 2 0.75G 2 G 2 G Path 4 G 2 M+0.75G G G 2 0.5G G F = Delay due to Dyadic Analysis Filter Bank G = Delay due to Dyadic Synthesis Filter Bank You can see from the previous figure that the signal delays on paths 1 and 2 are identical: 7(F+G). Because each path of the filter bank system has identical delay, you can equate the delay equations for paths 3 and 4 with the delay equation for paths 1 and 2. After constructing these equations, you can solve for M and N, respectively: Path 3 = Path 1 fi 4 M + 3 ( F + G) = 7( F + G) fi M = F + G Path 4 = Path 1 fi 2 N + ( F + G) = 7( F + G ) fi N = 3( F + G) The fvtool analysis in step 1 found the group delay of each biorthogonal wavelet filter in this model to be 5.5 samples. Therefore, F = 5.5 and G = 5.5. By inserting these values into the two previous equations, you get M = 11 and N = 33. Because the total delay on each filter path must be the same, you can find the overall delay of the filter bank system by inserting F = 5.5 and G = 5.5 into the delay equation for any of the four filter paths. Inserting the values of F and G into 7(F+G) yields an overall delay of 77 samples for the filter bank system of the ex_wavelets model. 7-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Calculate Channel Latencies Required for Wavelet Reconstruction Update and Run the Model Now that you know the latencies required for perfect wavelet reconstruction, you can incorporate those delay values into the model. The ex_wavelets model has already been updated with the correct delay values (M = 11, N = 33, Overall = 77), so it is ready to run. After you run the model, examine the reconstruction error in the Difference scope. To further examine any particular areas of interest, use the zoom tools available on the toolbar of the scope window or from the View menu. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-21 7 Transforms, Estimation, and Spectral Analysis References [1] Strang, G. and Nguyen, T. Wavelets and Filter Banks. Wellesley, MA: WellesleyCambridge Press, 1996. 7-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectral Analysis Spectral Analysis The Power Spectrum Estimation library provides a number of blocks for spectral analysis. Many of them have correlates in Signal Processing Toolbox software, which are shown in parentheses: • Burg Method (pburg) • Covariance Method (pcov) • Magnitude FFT (periodogram) • Modified Covariance Method (pmcov) • Short-Time FFT • Yule-Walker Method (pyulear) See “Spectral Analysis” in the Signal Processing Toolbox documentation for an overview of spectral analysis theory and a discussion of the above methods. DSP System Toolbox software provides two examples that illustrate the spectral analysis blocks: • A Comparison of Spectral Analysis Techniques (dspsacomp) • Spectral Analysis: Short-Time FFT (dspstfft) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-23 7 Transforms, Estimation, and Spectral Analysis Power Spectrum Estimates In this section... “Create the Block Diagram” on page 7-24 “Set the Model Parameters” on page 7-25 “View the Power Spectrum Estimates” on page 7-32 Create the Block Diagram Up until now, you have been dealing with signals in the time domain. The DSP System Toolbox product is also capable of working with signals in the frequency domain. You can use the software to perform fast Fourier transforms (FFTs), power spectrum analysis, short-time FFTs, and many other frequency-domain applications. The power spectrum of a signal represents the contribution of every frequency of the spectrum to the power of the overall signal. It is useful because many signal processing applications, such as noise cancellation and system identification, are based on frequency-specific modifications of signals. First, assemble and connect the blocks needed to calculate the power spectrum of your speech signal: 1 Open a new Simulink model. 2 Add the following blocks to your model. Subsequent topics describe how to use these blocks. 3 7-24 Block Library Signal From Workspace Sources Buffer Signal Management / Buffers Periodogram Estimation / Power Spectrum Estimation Vector Scope Sinks Connect the blocks as shown in the next figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Power Spectrum Estimates Once you have assembled the blocks needed to calculate the power spectrum of your speech signal, you can set the block parameters. Set the Model Parameters Now that you have assembled the blocks needed to calculate the power spectrum of your speech signal, you need to set the block parameters. These parameter values ensure that the model calculates the power spectrum of your signal accurately: 1 If the model you created in “Create the Block Diagram” on page 7-24 is not open on your desktop, you can open an equivalent model by typing ex_gstut9 at the MATLAB command prompt. 2 Load the speech signal into the MATLAB workspace by typing load mtlb at the MATLAB command prompt. This speech signal is a woman's voice saying “MATLAB.” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-25 7 Transforms, Estimation, and Spectral Analysis 3 Use the Signal From Workspace block to import the speech signal from the MATLAB workspace into your Simulink model. Open the Signal From Workspace dialog box by double-clicking the block. Set the block parameters as follows: • Signal = mtlb • Sample time = 1/8000 • Samples per frame = 80 • Form output after final data value by = Setting to zero Once you are done setting these parameters, the Signal From Workspace dialog box should look similar to the figure below. Click OK to apply your changes. 7-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Power Spectrum Estimates The DSP System Toolbox product is capable of frame-based processing. In other words, DSP System Toolbox blocks can process multiple samples of data at one time. This improves the computational speed of your model. In this case, by setting the Samples per frame parameter to 80, you are telling the Signal From Workspace block to output a frame that contains 80 signal samples at each simulation time step. Note that the sample period of the input signal is 1/8000 seconds. Also, after the block outputs the final signal value, all other outputs are zero. 4 Use the Buffer block to buffer the input signal into frames that contain 128 samples. Open the Buffer dialog box by double-clicking the block. Set the block parameters as follows: • Output buffer size (per channel) = 128 • Buffer overlap = 48 • Initial conditions = 0 • Treat Mx1 and unoriented sample-based signals as = One channel Once you are done setting these parameters, the Buffer dialog box should look similar to the figure below. Click OK to apply your changes. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-27 7 Transforms, Estimation, and Spectral Analysis Based on these parameters, the first output frame contains 48 initial condition values followed by the first 80 samples from the first input frame. The second output frame contains the last 48 values from the previous frame followed by the second 80 samples from the second input frame, and so on. You are buffering your input signal into an output signal with 128 samples per frame to minimize the estimation noise added to your signal. Because 128 is a power of 2, this operation also enables the Periodogram block to perform an FFT on the signal. 5 Use the Periodogram block to compute a nonparametric estimate of the power spectrum of the speech signal. Open the Periodogram dialog box by double-clicking the block and set the block parameters as follows: • Measurement = Power spectral density • Window = Hamming • Window sampling = Periodic • Select the Inherit FFT length from input dimensions check box. • Number of spectral averages = 2 Once you are done setting these parameters, the Periodogram dialog box should look similar to the figure below. Click OK to apply your changes. 7-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Power Spectrum Estimates Based on these parameters, the block applies a Hamming window periodically to the input speech signal and averages two spectra at one time. The length of the FFT is assumed to be 128, which is the number of samples per frame being output from the Buffer block. 6 Use the Vector Scope block to view the power spectrum of the speech signal. Open the Vector Scope dialog box by double-clicking the block. Set the block parameters as follows: • Input domain = Frequency • Click the Axis Properties tab. • Clear the Inherit sample time from input check box. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-29 7 Transforms, Estimation, and Spectral Analysis • Sample time of original time series = 1/8000 • Y-axis label = Magnitude-squared, dB Once you are done setting these parameters, the Axis Properties pane of the Vector Scope dialog box should look similar to the figure below. As you can see by the Yaxis scaling parameter, the decibel amplitude is plotted in a vector scope window. 7-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Power Spectrum Estimates 7-31 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7 Transforms, Estimation, and Spectral Analysis Because you are buffering the input with a nonzero overlap, you have altered the sample time of the signal. As a result, you need to specify the sample time of the original time series. Otherwise, the overlapping buffer samples lead the block to believe that the sample time is shorter than it actually is. After you have set the block parameter values, you can calculate and view the power spectrum of the speech signal. View the Power Spectrum Estimates In the previous topics, you created a power spectrum model and set its parameters. In this topic, you simulate the model and view the power spectrum of your speech signal: 1 If the model you created in “Set the Model Parameters” on page 7-25 is not open on your desktop, you can open an equivalent model by typing ex_gstut10 at the MATLAB command prompt. 2 Set the configuration parameters. Open the Configuration Parameters dialog box by selecting Model Configuration Parameters from the Simulation menu. Select Solver from the menu on the left side of the dialog box, and set the parameters as follows: • Stop time = 0.5 • Type = Fixed-step • Solver = Discrete (no continuous states) 7-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Power Spectrum Estimates 3 Apply these parameters and close the Configuration Parameters dialog box by clicking OK. These parameters are saved only when you save your model. 4 If you have not already done so, load the speech signal into the MATLAB workspace by typing load mtlb. 5 Run the model to open the Vector Scope window. The data is not immediately visible at the end of the simulation. To autoscale the y-axis to fit the data, in the Vector Scope window, right-click and choose Autoscale. The following figure shows the data displayed in the Vector Scope window. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-33 7 Transforms, Estimation, and Spectral Analysis During the simulation, the Vector Scope window displays a series of frames output from the Periodogram block. Each of these frames corresponds to a window of the original speech signal. The data in each frame represents the power spectrum, or contribution of every frequency to the power of the original speech signal, for a given window. In the next section, “Spectrograms” on page 7-35, you use these power spectra to create a spectrogram of the speech signal. 7-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectrograms Spectrograms In this section... “Modify the Block Diagram” on page 7-35 “Set the Model Parameters” on page 7-37 “View the Spectrogram of the Speech Signal” on page 7-41 Modify the Block Diagram Spectrograms are color-based visualizations of the evolution of the power spectrum of a speech signal as this signal is swept through time. Spectrograms use the periodogram power spectrum estimation method and are widely used by speech and audio engineers. You can use them to develop a visual understanding of the frequency content of your speech signal while a particular sound is being vocalized. In the previous section, you built a model capable of calculating the power spectrum of a speech signal that represents a woman saying “MATLAB.” In this topic, you modify this model to view the spectrogram of your signal: 1 If the model you created in “View the Power Spectrum Estimates” on page 7-32 is not open on your desktop, you can open an equivalent model by typing ex_gstut11 at the MATLAB command prompt. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-35 7 Transforms, Estimation, and Spectral Analysis 2 3 7-36 Add the following blocks to your model. Subsequent topics describe how to use these blocks. Block Library Selector Simulink / Signal Routing dB Conversion Math Functions / Math Operations Buffer Signal Management / Buffers Reshape Simulink / Math Operations Matrix Viewer Sinks Connect the blocks as shown in the figure below. These blocks extract the positive frequencies of each power spectrum and concatenate them into a matrix that represents the spectrogram of the speech signal. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectrograms Once you have assembled the blocks needed to view the spectrogram of your speech signal, you can set the block parameters. Set the Model Parameters In the previous topic, you assembled the blocks you need to view the spectrogram of your speech signal. Now you must set the block parameters: 1 If the model you created in “Modify the Block Diagram” on page 7-35 is not open on your desktop, you can open an equivalent model by typing ex_gstut12 at the MATLAB command prompt. 2 Use the Selector block to extract the first 64 elements, or the positive frequencies, of each power spectrum. Open the Selector dialog box by double-clicking the block. Set the block parameters as follows: • Number of input dimensions = 1 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-37 7 Transforms, Estimation, and Spectral Analysis • Index mode = One-based • Index option = Index vector (dialog) • Index = 1:64 • Input port size = 128 At each time instance, the input to the Selector block is a vector of 128 elements. The block assigns one-based indices to these elements and extracts the first 64. Once you are done setting these parameters, the Selector dialog box should look similar to the figure below. To apply your changes, click OK. 3 The dB Conversion block converts the magnitude of the input FFT signal to decibels. Leave this block at its default parameters. 4 Use the Buffer1 block to buffer up the individual power spectrums. Open the Buffer1 dialog box by double-clicking the block. Set the block parameters as follows: • Output buffer size (per channel) = 64*48 • Buffer overlap = 64*46 7-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectrograms • Initial conditions = -70 • Treat Mx1 and unoriented sample-based signals as = One channel Once you are done setting these parameters, the Buffer1 dialog box should look similar to the following figure. To apply your changes, click OK. Setting the value of the Buffer overlap parameter slightly less than the value of the Output buffer size (per channel) parameter ensures that your spectrogram represents smooth movement through time. The Initial conditions parameter represents the initial values in the buffer; -70 represents silence. 5 Use the Reshape block to reshape the input signal into a 64-by-48 matrix. To do so, set the Output dimensionality to Customize and the Output dimensions to [64 48]. 6 The Matrix Viewer enables you to view the spectrogram of the speech signal. Open the Matrix Viewer dialog box by double-clicking the block. Set the block parameters as follows: • Click the Image Properties tab. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-39 7 Transforms, Estimation, and Spectral Analysis • Colormap matrix = jet(256) • Minimum input value = -150 • Maximum input value = -65 • Select the Display colorbar check box. Once you are done setting these parameters, the Image Properties pane should look similar to the figure below. • Click the Axis Properties tab. • Axis origin = Lower left corner • X-axis title = Time Index • Y-axis title = Frequency Index • Colorbar title = dB Magnitude 7-40 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectrograms In this case, you are assuming that the power spectrum values do not exceed -65 dB. Once you are done setting these parameters, the Axis Properties pane should look similar to the figure below. To apply your changes, click OK. After you have set the parameter values, you can calculate and view the spectrogram of the speech signal. View the Spectrogram of the Speech Signal In the topic “View the Power Spectrum Estimates” on page 7-32, you used a Vector Scope block to display the power spectrum of your speech signal. In this topic, you view the spectrogram of your speech signal using a Matrix Viewer block. The speech signal represents a woman's voice saying “MATLAB”: 1 If the model you created in “Set the Model Parameters” on page 7-37 is not open on your desktop, you can open an equivalent model by typing www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-41 7 Transforms, Estimation, and Spectral Analysis ex_gstut13 at the MATLAB command prompt. 2 7-42 Run the model. During the simulation, the Vector Scope window displays a sequence of power spectrums, one for each window of the original speech signal. The power spectrum is the contribution of every frequency to the power of the speech signal. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Spectrograms The Matrix Viewer window, shown below, displays the spectrogram of the speech signal. This spectrogram is calculated using the Periodogram power spectrum estimation method. Note the harmonics that are visible in the signal when the vowels are spoken. Most of the signal's energy is concentrated in these harmonics; therefore, two distinct peaks are visible in the spectrogram. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 7-43 7 Transforms, Estimation, and Spectral Analysis In this example, you viewed the spectrogram of your speech signal using a Matrix Viewer block. You can find additional DSP System Toolbox product examples in the Help browser. To access these examples, click the Contents tab, double-click DSP System Toolbox, and then click Examples. A list of the examples in the DSP System Toolbox documentation appears in the right pane of the Help browser. 7-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Mathematics Learn about statistics and linear algebra. • “Statistics” on page 8-2 • “Linear Algebra and Least Squares” on page 8-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8 Mathematics Statistics In this section... “Statistics Blocks” on page 8-2 “Basic Operations” on page 8-2 “Running Operations” on page 8-3 Statistics Blocks The Statistics library provides fundamental statistical operations such as minimum, maximum, mean, variance, and standard deviation. Most blocks in the Statistics library support two types of operations; basic and running. The blocks listed below toggle between basic and running modes using the Running check box in the parameter dialog box: • Histogram • Mean • RMS • Standard Deviation • Variance An unselected Running check box means that the block is operating in basic mode, while a selected Running box means that the block is operating in running mode. The Maximum and Minimum blocks are slightly different from the blocks above, and provide a Mode parameter in the block dialog box to select the type of operation. The Value and Index, Value, and Index options in the Mode menu all specify basic operation, in each case enabling a different set of output ports on the block. The Running option in the Mode menu selects running operation. Basic Operations A basic operation is one that processes each input independently of previous and subsequent inputs. For example, in basic mode (with Value and Index selected, for example) the Maximum block finds the maximum value in each column of the current input, and returns this result at the top output (Val). Each consecutive Val output 8-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Statistics therefore has the same number of columns as the input, but only one row. Furthermore, the values in a given output only depend on the values in the corresponding input. The block repeats this operation for each successive input. This type of operation is exactly equivalent to the MATLAB command val = max(u) % Equivalent MATLAB code which computes the maximum of each column in input u. The next section is an example of a basic statistical operation. Create a Sliding Window You can use the basic statistics operations in conjunction with the Buffer block to implement basic sliding window statistics operations. A sliding window is like a stencil that you move along a data stream, exposing only a set number of data points at one time. For example, you may want to process data in 128-sample frames, moving the window along by one sample point for each operation. One way to implement such a sliding window is shown in the following ex_mean_tut model. The Buffer block's Buffer size (Mo) parameter determines the size of the window. The Buffer overlap (L) parameter defines the “slide factor” for the window. At each sample instant, the window slides by Mo-L points. The Buffer overlap is often Mo-1, so that a new statistic is computed for every new signal sample. Running Operations A running operation is one that processes successive inputs, and computes a result that reflects both current and past inputs. In this mode, you must use the Input processing parameter to specify whether the block performs sample- or frame-based processing on the inputs. A reset port enables you to restart this tracking at any time. The running www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-3 8 Mathematics statistic is computed for each input channel independently, so the block's output is the same size as the input. For example, in running mode (Running selected from the Mode parameter) the Maximum block outputs a record of the input's maximum value over time. The following figure illustrates how a Maximum block in running mode operates on a 3-by-2 matrix input, u, when the Input processing parameter is set to Columns as channels (frame based). The running maximum is reset at t=2 by an impulse to the block's optional Rst port. 8-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Linear Algebra and Least Squares Linear Algebra and Least Squares In this section... “Linear Algebra Blocks” on page 8-5 “Linear System Solvers” on page 8-5 “Matrix Factorizations” on page 8-7 “Matrix Inverses” on page 8-8 Linear Algebra Blocks The Matrices and Linear Algebra library provides three large sublibraries containing blocks for linear algebra; Linear System Solvers, Matrix Factorizations, and Matrix Inverses. A fourth library, Matrix Operations, provides other essential blocks for working with matrices. Linear System Solvers The Linear System Solvers library provides the following blocks for solving the system of linear equations AX = B: • Autocorrelation LPC • Cholesky Solver • Forward Substitution • LDL Solver • Levinson-Durbin • LU Solver • QR Solver • SVD Solver Some of the blocks offer particular strengths for certain classes of problems. For example, the Cholesky Solver block is particularly adapted for a square Hermitian positive definite matrix A, whereas the Backward Substitution block is particularly suited for an upper triangular matrix A. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-5 8 Mathematics Solve AX=B Using the LU Solver Block In the following ex_lusolver_tut model, the LU Solver block solves the equation Ax = b, where È1 -2 3˘ A = ÍÍ4 0 6 ˙˙ b = ÎÍ 2 -1 3˙˚ È1˘ Í- 2˙ Í ˙ ÎÍ- 1˚˙ and finds x to be the vector [-2 0 1]'. You can verify the solution by using the Matrix Multiply block to perform the multiplication Ax, as shown in the following ex_matrixmultiply_tut1 model. 8-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Linear Algebra and Least Squares Matrix Factorizations The Matrix Factorizations library provides the following blocks for factoring various kinds of matrices: • Cholesky Factorization • LDL Factorization • LU Factorization • QR Factorization • Singular Value Decomposition Some of the blocks offer particular strengths for certain classes of problems. For example, the Cholesky Factorization block is particularly suited to factoring a Hermitian positive definite matrix into triangular components, whereas the QR Factorization is particularly suited to factoring a rectangular matrix into unitary and upper triangular components. Factor a Matrix into Upper and Lower Submatrices Using the LU Factorization Block In the following ex_lufactorization_tut model, the LU Factorization block factors a matrix Ap into upper and lower triangular submatrices U and L, where Ap is row equivalent to input matrix A, where www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-7 8 Mathematics The lower output of the LU Factorization, P, is the permutation index vector, which indicates that the factored matrix Ap is generated from A by interchanging the first and second rows. È4 0 6 ˘ A p = ÍÍ1 -2 3˙˙ ÍÎ 2 -1 3˙˚ The upper output of the LU Factorization, LU, is a composite matrix containing the two submatrix factors, U and L, whose product LU is equal to Ap. 6 ˘ 0 0˘ È4 0 È 1 U = ÍÍ 0 -2 1.5 ˙˙ L = ÍÍ0 .25 1 0 ˙˙ ÍÎ 0 0 -0 .75 ˙˚ ÍÎ 0 .5 0.5 1 ˙˚ You can check that LU = Ap with the Matrix Multiply block, as shown in the following ex_matrixmultiply_tut2 model. Matrix Inverses The Matrix Inverses library provides the following blocks for inverting various kinds of matrices: • Cholesky Inverse • LDL Inverse 8-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Linear Algebra and Least Squares • LU Inverse • Pseudoinverse Find the Inverse of a Matrix Using the LU Inverse Block In the following ex_luinverse_tut model, the LU Inverse block computes the inverse of input matrix A, where È1 -2 3˘ A = ÍÍ4 0 6 ˙˙ ÍÎ 2 -1 3˙˚ and then forms the product A-1A, which yields the identity matrix of order 3, as expected. As shown above, the computed inverse is A -1 -0 .5 2 ˘ È -1 Í =Í 0 0.5 -1 ˙˙ ÍÎ 0.6667 0.5 - 1.333 ˙˚ www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-9 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 8-10 9 Fixed-Point Design Learn about fixed-point data types and how to convert floating-point models to fixedpoint. • “Fixed-Point Signal Processing” on page 9-2 • “Fixed-Point Concepts and Terminology” on page 9-4 • “Arithmetic Operations” on page 9-9 • “Fixed-Point Support for MATLAB System Objects” on page 9-19 • “Specify Fixed-Point Attributes for Blocks” on page 9-25 • “Quantizers” on page 9-47 • “Fixed-Point Filter Design” on page 9-61 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9 Fixed-Point Design Fixed-Point Signal Processing In this section... “Fixed-Point Features” on page 9-2 “Benefits of Fixed-Point Hardware” on page 9-2 “Benefits of Fixed-Point Design with System Toolboxes Software” on page 9-3 Note: To take full advantage of fixed-point support in System Toolbox software, you must install Fixed-Point Designer software. Fixed-Point Features Many of the blocks in this product have fixed-point support, so you can design signal processing systems that use fixed-point arithmetic. Fixed-point support in DSP System Toolbox software includes • Signed two's complement and unsigned fixed-point data types • Word lengths from 2 to 128 bits in simulation • Word lengths from 2 to the size of a long on the Simulink Coder C code-generation target • Overflow handling and rounding methods • C code generation for deployment on a fixed-point embedded processor, with Simulink Coder code generation software. The generated code uses all allowed data types supported by the embedded target, and automatically includes all necessary shift and scaling operations Benefits of Fixed-Point Hardware There are both benefits and trade-offs to using fixed-point hardware rather than floatingpoint hardware for signal processing development. Many signal processing applications require low-power and cost-effective circuitry, which makes fixed-point hardware a natural choice. Fixed-point hardware tends to be simpler and smaller. As a result, these units require less power and cost less to produce than floating-point circuitry. Floating-point hardware is usually larger because it demands functionality and ease of development. Floating-point hardware can accurately represent real-world numbers, and 9-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Signal Processing its large dynamic range reduces the risk of overflow, quantization errors, and the need for scaling. In contrast, the smaller dynamic range of fixed-point hardware that allows for low-power, inexpensive units brings the possibility of these problems. Therefore, fixed-point development must minimize the negative effects of these factors, while exploiting the benefits of fixed-point hardware; cost- and size-effective units, less power and memory usage, and fast real-time processing. Benefits of Fixed-Point Design with System Toolboxes Software Simulating your fixed-point development choices before implementing them in hardware saves time and money. The built-in fixed-point operations provided by the System Toolboxes software save time in simulation and allow you to generate code automatically. This software allows you to easily run multiple simulations with different word length, scaling, overflow handling, and rounding method choices to see the consequences of various fixed-point designs before committing to hardware. The traditional risks of fixedpoint development, such as quantization errors and overflow, can be simulated and mitigated in software before going to hardware. Fixed-point C code generation with System Toolbox software and Simulink Coder code generation software produces code ready for execution on a fixed-point processor. All the choices you make in simulation in terms of scaling, overflow handling, and rounding methods are automatically optimized in the generated code, without necessitating timeconsuming and costly hand-optimized code. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-3 9 Fixed-Point Design Fixed-Point Concepts and Terminology In this section... “Fixed-Point Data Types” on page 9-4 “Scaling” on page 9-5 “Precision and Range” on page 9-6 Note: The “Glossary” defines much of the vocabulary used in these sections. For more information on these subjects, see the “Fixed-Point Designer” documentation. Fixed-Point Data Types In digital hardware, numbers are stored in binary words. A binary word is a fixed-length sequence of bits (1's and 0's). How hardware components or software functions interpret this sequence of 1's and 0's is defined by the data type. Binary numbers are represented as either fixed-point or floating-point data types. In this section, we discuss many terms and concepts relating to fixed-point numbers, data types, and mathematics. A fixed-point data type is characterized by the word length in bits, the position of the binary point, and whether it is signed or unsigned. The position of the binary point is the means by which fixed-point values are scaled and interpreted. For example, a binary representation of a generalized fixed-point number (either signed or unsigned) is shown below: where • bi is the ith binary digit. 9-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Concepts and Terminology • wl is the word length in bits. • bwl–1 is the location of the most significant, or highest, bit (MSB). • b0 is the location of the least significant, or lowest, bit (LSB). • The binary point is shown four places to the left of the LSB. In this example, therefore, the number is said to have four fractional bits, or a fraction length of four. Fixed-point data types can be either signed or unsigned. Signed binary fixed-point numbers are typically represented in one of three ways: • Sign/magnitude • One's complement • Two's complement Two's complement is the most common representation of signed fixed-point numbers and is used by System Toolbox software. See “Two's Complement” on page 9-10 for more information. Scaling Fixed-point numbers can be encoded according to the scheme real- world value = ( slope ¥ integer) + bias where the slope can be expressed as slope = slope adjustment ¥ 2exponent The integer is sometimes called the stored integer. This is the raw binary number, in which the binary point assumed to be at the far right of the word. In System Toolboxes, the negative of the exponent is often referred to as the fraction length. The slope and bias together represent the scaling of the fixed-point number. In a number with zero bias, only the slope affects the scaling. A fixed-point number that is only scaled by binary point position is equivalent to a number in the Fixed-Point Designer [Slope Bias] representation that has a bias equal to zero and a slope adjustment equal to one. This is referred to as binary point-only scaling or power-of-two scaling: real- world value = 2 exponent ¥ integer www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-5 9 Fixed-Point Design or real- world value = 2- fraction length ¥ integer In System Toolbox software, you can define a fixed-point data type and scaling for the output or the parameters of many blocks by specifying the word length and fraction length of the quantity. The word length and fraction length define the whole of the data type and scaling information for binary-point only signals. All System Toolbox blocks that support fixed-point data types support signals with binary-point only scaling. Many fixed-point blocks that do not perform arithmetic operations but merely rearrange data, such as Delay and Matrix Transpose, also support signals with [Slope Bias] scaling. Precision and Range You must pay attention to the precision and range of the fixed-point data types and scalings you choose for the blocks in your simulations, in order to know whether rounding methods will be invoked or if overflows will occur. Range The range is the span of numbers that a fixed-point data type and scaling can represent. The range of representable numbers for a two's complement fixed-point number of word length wl, scaling S, and bias B is illustrated below: For both signed and unsigned fixed-point numbers of any data type, the number of different bit patterns is 2wl. For example, in two's complement, negative numbers must be represented as well as zero, so the maximum value is 2wl–1. Because there is only one representation for zero, there are an unequal number of positive and negative numbers. This means there is a representation for -2wl–1 but not for 2wl –1: 9-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Concepts and Terminology Overflow Handling Because a fixed-point data type represents numbers within a finite range, overflows can occur if the result of an operation is larger or smaller than the numbers in that range. System Toolbox software does not allow you to add guard bits to a data type on-the-fly in order to avoid overflows. Any guard bits must be allocated upon model initialization. However, the software does allow you to either saturate or wrap overflows. Saturation represents positive overflows as the largest positive number in the range being used, and negative overflows as the largest negative number in the range being used. Wrapping uses modulo arithmetic to cast an overflow back into the representable range of the data type. See “Modulo Arithmetic” on page 9-9 for more information. Precision The precision of a fixed-point number is the difference between successive values representable by its data type and scaling, which is equal to the value of its least significant bit. The value of the least significant bit, and therefore the precision of the number, is determined by the number of fractional bits. A fixed-point value can be represented to within half of the precision of its data type and scaling. For example, a fixed-point representation with four bits to the right of the binary point has a precision of 2-4 or 0.0625, which is the value of its least significant bit. Any number within the range of this data type and scaling can be represented to within (2-4)/2 or 0.03125, which is half the precision. This is an example of representing a number with finite precision. Rounding Modes When you represent numbers with finite precision, not every number in the available range can be represented exactly. If a number cannot be represented exactly by the specified data type and scaling, it is rounded to a representable number. Although precision is always lost in the rounding operation, the cost of the operation and the www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-7 9 Fixed-Point Design amount of bias that is introduced depends on the rounding mode itself. To provide you with greater flexibility in the trade-off between cost and bias, DSP System Toolbox software currently supports the following rounding modes: • Ceiling rounds the result of a calculation to the closest representable number in the direction of positive infinity. • Convergent rounds the result of a calculation to the closest representable number. In the case of a tie, Convergent rounds to the nearest even number. This is the least biased rounding mode provided by the toolbox. • Floor, which is equivalent to truncation, rounds the result of a calculation to the closest representable number in the direction of negative infinity. • Nearest rounds the result of a calculation to the closest representable number. In the case of a tie, Nearest rounds to the closest representable number in the direction of positive infinity. • Round rounds the result of a calculation to the closest representable number. In the case of a tie, Round rounds positive numbers to the closest representable number in the direction of positive infinity, and rounds negative numbers to the closest representable number in the direction of negative infinity. • Simplest rounds the result of a calculation using the rounding mode (Floor or Zero) that adds the least amount of extra rounding code to your generated code. For more information, see “Rounding Mode: Simplest” in the Fixed-Point Designer documentation. • Zero rounds the result of a calculation to the closest representable number in the direction of zero. To learn more about each of these rounding modes, see “Rounding” in the Fixed-Point Designer documentation. For a direct comparison of the rounding modes, see “Choosing a Rounding Method” in the Fixed-Point Designer documentation. 9-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Arithmetic Operations Arithmetic Operations In this section... “Modulo Arithmetic” on page 9-9 “Two's Complement” on page 9-10 “Addition and Subtraction” on page 9-11 “Multiplication” on page 9-12 “Casts” on page 9-14 Note: These sections will help you understand what data type and scaling choices result in overflows or a loss of precision. Modulo Arithmetic Binary math is based on modulo arithmetic. Modulo arithmetic uses only a finite set of numbers, wrapping the results of any calculations that fall outside the given set back into the set. For example, the common everyday clock uses modulo 12 arithmetic. Numbers in this system can only be 1 through 12. Therefore, in the “clock” system, 9 plus 9 equals 6. This can be more easily visualized as a number circle: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-9 9 Fixed-Point Design Similarly, binary math can only use the numbers 0 and 1, and any arithmetic results that fall outside this range are wrapped “around the circle” to either 0 or 1. Two's Complement Two's complement is a way to interpret a binary number. In two's complement, positive numbers always start with a 0 and negative numbers always start with a 1. If the leading bit of a two's complement number is 0, the value is obtained by calculating the standard binary value of the number. If the leading bit of a two's complement number is 1, the value is obtained by assuming that the leftmost bit is negative, and then calculating the binary value of the number. For example, 01 = (0 + 20 ) = 1 11 = ((- 21 ) + ( 20 )) = (-2 + 1) = -1 To compute the negative of a binary number using two's complement, 9-10 1 Take the one's complement, or “flip the bits.” 2 Add a 1 using binary math. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Arithmetic Operations 3 Discard any bits carried beyond the original word length. For example, consider taking the negative of 11010 (-6). First, take the one's complement of the number, or flip the bits: 11010 Æ 00101 Next, add a 1, wrapping all numbers to 0 or 1: 00101 +1 00110 (6) Addition and Subtraction The addition of fixed-point numbers requires that the binary points of the addends be aligned. The addition is then performed using binary arithmetic so that no number other than 0 or 1 is used. For example, consider the addition of 010010.1 (18.5) with 0110.110 (6.75): 010010.1 (18.5) +0110.110 (6.75) 011001.010 (25.25) Fixed-point subtraction is equivalent to adding while using the two's complement value for any negative values. In subtraction, the addends must be sign extended to match each other's length. For example, consider subtracting 0110.110 (6.75) from 010010.1 (18.5): Most fixed-point DSP System Toolbox blocks that perform addition cast the adder inputs to an accumulator data type before performing the addition. Therefore, no further www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-11 9 Fixed-Point Design shifting is necessary during the addition to line up the binary points. See “Casts” on page 9-14 for more information. Multiplication The multiplication of two's complement fixed-point numbers is directly analogous to regular decimal multiplication, with the exception that the intermediate results must be sign extended so that their left sides align before you add them together. For example, consider the multiplication of 10.11 (-1.25) with 011 (3): Multiplication Data Types The following diagrams show the data types used for fixed-point multiplication in the System Toolbox software. The diagrams illustrate the differences between the data types used for real-real, complex-real, and complex-complex multiplication. See individual reference pages to determine whether a particular block accepts complex fixed-point inputs. In most cases, you can set the data types used during multiplication in the block mask. See Accumulator Parameters, Intermediate Product Parameters, Product Output Parameters, and Output Parameters. These data types are defined in “Casts” on page 9-14. Note: The following diagrams show the use of fixed-point data types in multiplication in System Toolbox software. They do not represent actual subsystems used by the software to perform multiplication. 9-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Arithmetic Operations Real-Real Multiplication The following diagram shows the data types used in the multiplication of two real numbers in System Toolbox software. The software returns the output of this operation in the product output data type, as the next figure shows. Real-Complex Multiplication The following diagram shows the data types used in the multiplication of a real and a complex fixed-point number in System Toolbox software. Real-complex and complex-real multiplication are equivalent. The software returns the output of this operation in the product output data type, as the next figure shows. Complex-Complex Multiplication The following diagram shows the multiplication of two complex fixed-point numbers in System Toolbox software. Note that the software returns the output of this operation in the accumulator output data type, as the next figure shows. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-13 9 Fixed-Point Design System Toolbox blocks cast to the accumulator data type before performing addition or subtraction operations. In the preceding diagram, this is equivalent to the C code acc=ac; acc-=bd; for the subtractor, and acc=ad; acc+=bc; for the adder, where acc is the accumulator. Casts Many fixed-point System Toolbox blocks that perform arithmetic operations allow you to specify the accumulator, intermediate product, and product output data types, as 9-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Arithmetic Operations applicable, as well as the output data type of the block. This section gives an overview of the casts to these data types, so that you can tell if the data types you select will invoke sign extension, padding with zeros, rounding, and/or overflow. Casts to the Accumulator Data Type For most fixed-point System Toolbox blocks that perform addition or subtraction, the operands are first cast to an accumulator data type. Most of the time, you can specify the accumulator data type on the block mask. See Accumulator Parameters. Since the addends are both cast to the same accumulator data type before they are added together, no extra shift is necessary to insure that their binary points align. The result of the addition remains in the accumulator data type, with the possibility of overflow. Casts to the Intermediate Product or Product Output Data Type For System Toolbox blocks that perform multiplication, the output of the multiplier is placed into a product output data type. Blocks that then feed the product output back into the multiplier might first cast it to an intermediate product data type. Most of the time, you can specify these data types on the block mask. See Intermediate Product Parameters and Product Output Parameters. Casts to the Output Data Type Many fixed-point System Toolbox blocks allow you to specify the data type and scaling of the block output on the mask. Remember that the software does not allow mixed types on the input and output ports of its blocks. Therefore, if you would like to specify a fixedpoint output data type and scaling for a System Toolbox block that supports fixed-point data types, you must feed the input port of that block with a fixed-point signal. The final cast made by a fixed-point System Toolbox block is to the output data type of the block. Note that although you can not mix fixed-point and floating-point signals on the input and output ports of blocks, you can have fixed-point signals with different word and fraction lengths on the ports of blocks that support fixed-point signals. Casting Examples It is important to keep in mind the ramifications of each cast when selecting these intermediate data types, as well as any other intermediate fixed-point data types that are allowed by a particular block. Depending upon the data types you select, overflow and/or rounding might occur. The following two examples demonstrate cases where overflow and rounding can occur. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-15 9 Fixed-Point Design Cast from a Shorter Data Type to a Longer Data Type Consider the cast of a nonzero number, represented by a four-bit data type with two fractional bits, to an eight-bit data type with seven fractional bits: As the diagram shows, the source bits are shifted up so that the binary point matches the destination binary point position. The highest source bit does not fit, so overflow might occur and the result can saturate or wrap. The empty bits at the low end of the destination data type are padded with either 0's or 1's: • If overflow does not occur, the empty bits are padded with 0's. • If wrapping occurs, the empty bits are padded with 0's. • If saturation occurs, • The empty bits of a positive number are padded with 1's. • The empty bits of a negative number are padded with 0's. You can see that even with a cast from a shorter data type to a longer data type, overflow might still occur. This can happen when the integer length of the source data type (in this case two) is longer than the integer length of the destination data type (in this case 9-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Arithmetic Operations one). Similarly, rounding might be necessary even when casting from a shorter data type to a longer data type, if the destination data type and scaling has fewer fractional bits than the source. Cast from a Longer Data Type to a Shorter Data Type Consider the cast of a nonzero number, represented by an eight-bit data type with seven fractional bits, to a four-bit data type with two fractional bits: As the diagram shows, the source bits are shifted down so that the binary point matches the destination binary point position. There is no value for the highest bit from the source, so the result is sign extended to fill the integer portion of the destination data type. The bottom five bits of the source do not fit into the fraction length of the destination. Therefore, precision can be lost as the result is rounded. In this case, even though the cast is from a longer data type to a shorter data type, all the integer bits are maintained. Conversely, full precision can be maintained even if you cast to a shorter data type, as long as the fraction length of the destination data type is the same length or longer than the fraction length of the source data type. In that case, however, bits are lost from the high end of the result and overflow might occur. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-17 9 Fixed-Point Design The worst case occurs when both the integer length and the fraction length of the destination data type are shorter than those of the source data type and scaling. In that case, both overflow and a loss of precision can occur. 9-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Support for MATLAB System Objects Fixed-Point Support for MATLAB System Objects In this section... “Get Information About Fixed-Point System Objects” on page 9-19 “Display Fixed-Point Properties for System Objects” on page 9-22 “Set System Object Fixed-Point Properties” on page 9-23 “Full Precision for Fixed-Point System Objects” on page 9-24 Get Information About Fixed-Point System Objects System objects that support fixed-point data processing have fixedpoint properties, which you can display for a particular object by typing dsp.<ObjectName>.helpFixedPoint at the command line. See “ Display Fixed-Point Properties for System Objects” to set the display of System object fixed-point properties. The following signal processing System objects support fixed-point data processing. DSP System Toolbox System Objects that Support Fixed Point Object Description Estimation dsp.LevinsonSolver Solve linear system of equations using LevinsonDurbin recursion Filters dsp.AllpoleFilter IIR Filter with no zeros dsp.BiquadFilter Model biquadratic IIR (SOS) filters dsp.CICDecimator Decimate inputs using a Cascaded Integrator-Comb (CIC) filter dsp.CICInterpolator Interpolate inputs using a Cascaded IntegratorComb (CIC) filter dsp.DigitalFilter Filter each channel of input over time using discrete-time filter implementations www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-19 9 Fixed-Point Design Object Description dsp.FIRDecimator Filter and downsample input signals dsp.FIRFilter Static or time-varying FIR filter dsp.FIRInterpolator Upsample and filter input signals dsp.FIRRateConverter Upsample, filter and downsample input signals dsp.IIRFilter Infinite Impulse Response (IIR) filter dsp.LMSFilter Compute output, error, and weights using LMS adaptive algorithm dsp.SubbandAnalysisFilter Decompose signal into high-frequency and lowfrequency subbands dsp.SubbandSynthesisFilter Reconstruct a signal from high-frequency and lowfrequency subbands Math Functions 9-20 dsp.ArrayVectorAdder Add vector to array along specified dimension dsp.ArrayVectorDivider Divide array by vector along specified dimension dsp.ArrayVectorMultiplier Multiply array by vector along specified dimension dsp.ArrayVectorSubtractor Subtract vector from array along specified dimension dsp.CumulativeProduct Compute cumulative product of channel, column, or row elements dsp.CumulativeSum Compute cumulative sum of channel, column, or row elements dsp.LDLFactor Factor square Hermitian positive definite matrices into lower, upper, and diagonal components dsp.LevinsonSolver Solve linear system of equations using LevinsonDurbin recursion dsp.LowerTriangularSolver Solve LX = B for X when L is lower triangular matrix dsp.LUFactor Factor square matrix into lower and upper triangular matrices dsp.Normalizer Normalize input www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان DSP System Toolbox System Objects that Support Fixed Point Object Description dsp.UpperTriangularSolver Solve UX = B for X when U is upper triangular matrix Quantizers dsp.ScalarQuantizerDecoder Convert each index value into quantized output value dsp.ScalarQuantizerEncoder Perform scalar quantization encoding dsp.VectorQuantizerDecoder Find vector quantizer codeword for given index value dsp.VectorQuantizerEncoder Perform vector quantization encoding Signal Management dsp.Buffer Buffer an input signal dsp.Counter Count up or down through specified range of numbers Signal Operations dsp.Convolver Compute convolution of two inputs dsp.DigitalDownConverter Digitally down convert the input signal dsp.DigitalUpConverter Digitally up convert the input signal dsp.NCO Generate real or complex sinusoidal signals dsp.PeakFinder Determine extrema (maxima or minima) in input signal dsp.VariableFractionalDelay Delay input by time-varying fractional number of sample periods dsp.Window Window object Sinks dsp.SignalSink Log MATLAB simulation data dsp.TimeScope Display time-domain signals Sources dsp.SignalSource Import a variable from the MATLAB workspace dsp.SineWave Generate discrete sine wave www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-21 9 Fixed-Point Design Object Description Statistics dsp.Autocorrelator Compute autocorrelation of vector inputs dsp.Crosscorrelator Compute cross-correlation of two inputs dsp.Histogram Output histogram of an input or sequence of inputs dsp.Maximum Compute maximum value in input dsp.Mean Compute average or mean value in input dsp.Median Compute median value in input dsp.Minimum Compute minimum value in input dsp.Variance Compute variance of input or sequence of inputs Transforms dsp.DCT Compute discrete cosine transform (DCT) of input dsp.FFT Compute fast Fourier transform (FFT) of input dsp.IDCT Compute inverse discrete cosine transform (IDCT) of input dsp.IFFT Compute inverse fast Fourier transform (IFFT) of input Display Fixed-Point Properties for System Objects You can control whether the software displays fixed-point properties with either of the following commands: • matlab.system.showFixedPointProperties • matlab.system.hideFixedPointProperties at the MATLAB command line. These commands set the Show fixed-point properties display option. You can also set the display option directly via the MATLAB preferences dialog box. Click Preferences on the MATLAB Toolstrip. The Preferences dialog box opens. Scroll down and select System Objects. Finally, select or deselect Show fixedpoint properties. 9-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان DSP System Toolbox System Objects that Support Fixed Point If an object supports fixed-point data processing, its fixed-point properties are active regardless of whether they are displayed or not. Set System Object Fixed-Point Properties A number of properties affect the fixed-point data processing used by a System object. Objects perform fixed-point processing and use the current fixed-point property settings when they receive fixed-point input. You change the values of fixed-point properties in the same way as you change any System object property value. See “Configure Components for Your System”. You also use the Fixed-Point Designer numerictype object to specify the desired data type as fixed- www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-23 9 Fixed-Point Design point, the signedness, and the word- and fraction-lengths. System objects support these values of DataTypeMode: Boolean, Double, Single, and Fixed-point: binary point scaling. In the same way as for blocks, the data type properties of many System objects can set the appropriate word lengths and scalings automatically by using full precision. System objects assume that the target specified on the Configuration Parameters Hardware Implementation target is ASIC/FPGA. If you have not set the property that activates a dependent property and you attempt to change that dependent property, a warning message displays. For example, for the dsp.FFT object, before you set CustomOutputDataType to numerictype(1,32,30) you must set OutputDataType to 'Custom'. Note: System objects do not support fixed-point word lengths greater than 128 bits. For any System object provided in the Toolbox, the fimath settings for any fimath attached to a fi input or a fi property are ignored. Outputs from a System object never have an attached fimath. Full Precision for Fixed-Point System Objects FullPrecisionOverride is a convenience property that, when you set to true, automatically sets the appropriate properties for an object to use full-precision to process fixed-point input. For System objects, full precision, fixed-point operation refers to growing just enough additional bits to compute the ideal full precision result. This operation has no minimum or maximum range overflow nor any precision loss due to rounding or underflow. It is also independent of any hardware-specific settings. The data types chosen are based only on known data type ranges and not on actual numeric values. Unlike full precision for dfilt objects, full precision for System objects does not optimize coefficient values. When you set the FullPrecisionOverride property to true, the other fixed-point properties it controls no longer apply and any of their non-default values are ignored. These properties are also hidden. To specify individual fixed-point properties, you must first set FullPrecisionOverride to false. 9-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Specify Fixed-Point Attributes for Blocks In this section... “Fixed-Point Block Parameters” on page 9-25 “Specify System-Level Settings” on page 9-28 “Inherit via Internal Rule” on page 9-29 “Specify Data Types for Fixed-Point Blocks” on page 9-39 Fixed-Point Block Parameters System Toolbox blocks that have fixed-point support usually allow you to specify fixedpoint characteristics through block parameters. By specifying data type and scaling information for these fixed-point parameters, you can simulate your target hardware more closely. Note: Floating-point inheritance takes precedence over the settings discussed in this section. When the block has floating-point input, all block data types match the input. You can find most fixed-point parameters on the Data Types pane of System Toolbox blocks. The following figure shows a typical Data Types pane. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-25 9 Fixed-Point Design All System Toolbox blocks with fixed-point capabilities share a set of common parameters, but each block can have a different subset of these fixed-point parameters. The following table provides an overview of the most common fixed-point block parameters. Fixed-Point Data Type Parameter Description Rounding Mode Specifies the rounding mode for the block to use when the specified data type and scaling cannot exactly represent the result of a fixed-point calculation. See “Rounding Modes” on page 9-7 for more information on the available options. Overflow Mode Specifies the overflow mode to use when the result of a fixedpoint calculation does not fit into the representable range of the specified data type. See “Overflow Handling” on page 9-7 for more information on the available options. 9-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Fixed-Point Data Type Parameter Description Intermediate Product Specifies the data type and scaling of the intermediate product for fixed-point blocks. Blocks that feed multiplication results back to the input of the multiplier use the intermediate product data type. See the reference page of a specific block to learn about the intermediate product data type for that block. Product Output Specifies the data type and scaling of the product output for fixed-point blocks that must compute multiplication results. See the reference page of a specific block to learn about the product output data type for that block. For or complexcomplex multiplication, the multiplication result is in the accumulator data type. See “Multiplication Data Types” on page 9-12 for more information on complex fixed-point multiplication in System toolbox software. Accumulator Specifies the data type and scaling of the accumulator (sum) for fixed-point blocks that must hold summation results for further calculation. Most such blocks cast to the accumulator data type before performing the add operations (summation). See the reference page of a specific block for details on the accumulator data type of that block. Output Specifies the output data type and scaling for blocks. Using the Data Type Assistant The Data Type Assistant is an interactive graphical tool available on the Data Types pane of some fixed-point System Toolbox blocks. To learn more about using the Data Type Assistant to help you specify block data type parameters, see the following section of the Simulink documentation: “Specify Data Types Using Data Type Assistant” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-27 9 Fixed-Point Design Checking Signal Ranges Some fixed-point System Toolbox blocks have Minimum and Maximum parameters on the Data Types pane. When a fixed-point data type has these parameters, you can use them to specify appropriate minimum and maximum values for range checking purposes. To learn how to specify signal ranges and enable signal range checking, see “Signal Ranges” in the Simulink documentation. Specify System-Level Settings You can monitor and control fixed-point settings for System Toolbox blocks at a system or subsystem level with the Fixed-Point Tool. For additional information on these subjects, see • The fxptdlg reference page — A reference page on the Fixed-Point Tool in the Simulink documentation • “Fixed-Point Tool” — A tutorial that highlights the use of the Fixed-Point Tool in the Fixed-Point Designer software documentation Logging The Fixed-Point Tool logs overflows, saturations, and simulation minimums and maximums for fixed-point System Toolbox blocks. The Fixed-Point Tool does not log overflows and saturations when the Data overflow line in the Diagnostics > Data Integrity pane of the Configuration Parameters dialog box is set to None. Autoscaling You can use the Fixed-Point Tool autoscaling feature to set the scaling for System Toolbox fixed-point data types. Data type override System Toolbox blocks obey the Use local settings, Double, Single, and Off modes of the Data type override parameter in the Fixed-Point Tool. The Scaled double mode is also supported for System Toolboxes source and byte-shuffling blocks, and for some arithmetic blocks such as Difference and Normalization. 9-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Inherit via Internal Rule Selecting appropriate word lengths and scalings for the fixed-point parameters in your model can be challenging. To aid you, an Inherit via internal rule choice is often available for fixed-point block data type parameters, such as the Accumulator and Product output signals. The following sections describe how the word and fraction lengths are selected for you when you choose Inherit via internal rule for a fixedpoint block data type parameter in System Toolbox software: • “Internal Rule for Accumulator Data Types” on page 9-29 • “Internal Rule for Product Data Types” on page 9-30 • “Internal Rule for Output Data Types” on page 9-30 • “The Effect of the Hardware Implementation Pane on the Internal Rule” on page 9-30 • “Internal Rule Examples” on page 9-32 Note: In the equations in the following sections, WL = word length and FL = fraction length. Internal Rule for Accumulator Data Types The internal rule for accumulator data types first calculates the ideal, full-precision result. Where N is the number of addends: WLideal accumulator = WLinput to accumulator + floor(log 2 ( N - 1)) + 1 FLideal accumulator = FLinput to accumulator For example, consider summing all the elements of a vector of length 6 and data type sfix10_En8. The ideal, full-precision result has a word length of 13 and a fraction length of 8. The accumulator can be real or complex. The preceding equations are used for both the real and imaginary parts of the accumulator. For any calculation, after the full-precision result is calculated, the final word and fraction lengths set by the internal rule are www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-29 9 Fixed-Point Design affected by your particular hardware. See “The Effect of the Hardware Implementation Pane on the Internal Rule” on page 9-30 for more information. Internal Rule for Product Data Types The internal rule for product data types first calculates the ideal, full-precision result: WLideal product = WLinput 1 + WLinput 2 FLideal product = FLinput 1 + FLinput 2 For example, multiplying together the elements of a real vector of length 2 and data type sfix10_En8. The ideal, full-precision result has a word length of 20 and a fraction length of 16. For real-complex multiplication, the ideal word length and fraction length is used for both the complex and real portion of the result. For complex-complex multiplication, the ideal word length and fraction length is used for the partial products, and the internal rule for accumulator data types described above is used for the final sums. For any calculation, after the full-precision result is calculated, the final word and fraction lengths set by the internal rule are affected by your particular hardware. See “The Effect of the Hardware Implementation Pane on the Internal Rule” on page 9-30 for more information. Internal Rule for Output Data Types A few System Toolbox blocks have an Inherit via internal rule choice available for the block output. The internal rule used in these cases is block-specific, and the equations are listed in the block reference page. As with accumulator and product data types, the final output word and fraction lengths set by the internal rule are affected by your particular hardware, as described in “The Effect of the Hardware Implementation Pane on the Internal Rule” on page 9-30. The Effect of the Hardware Implementation Pane on the Internal Rule The internal rule selects word lengths and fraction lengths that are appropriate for your hardware. To get the best results using the internal rule, you must specify the type of hardware you are using on the Hardware Implementation pane of the Configuration 9-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Parameters dialog box. You can open this dialog box from the Simulation menu in your model. ASIC/FPGA On an ASIC/FPGA target, the ideal, full-precision word length and fraction length calculated by the internal rule are used. If the calculated ideal word length is larger than the largest allowed word length, you receive an error. The largest word length allowed for Simulink and System Toolbox software is 128 bits. Other targets For all targets other than ASIC/FPGA, the ideal, full-precision word length calculated by the internal rule is rounded up to the next available word length of the target. The calculated ideal fraction length is used, keeping the least-significant bits. If the calculated ideal word length for a product data type is larger than the largest word length on the target, you receive an error. If the calculated ideal word length for an accumulator or output data type is larger than the largest word length on the target, the largest target word length is used. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-31 9 Fixed-Point Design Internal Rule Examples The following sections show examples of how the internal rule interacts with the Hardware Implementation pane to calculate accumulator data types and product data types. Accumulator Data Types Consider the following model ex_internalRule_accumExp. In the Difference blocks, the Accumulator parameter is set to Inherit: Inherit via internal rule, and the Output parameter is set to Inherit: Same as accumulator. Therefore, you can see the accumulator data type calculated by the internal rule on the output signal in the model. 9-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks In the preceding model, the Device type parameter in the Hardware Implementation pane of the Configuration Parameters dialog box is set to ASIC/FPGA. Therefore, the accumulator data type used by the internal rule is the ideal, full-precision result. Calculate the full-precision word length for each of the Difference blocks in the model: WLideal accumulator = WLinput to accumulator + floor(log 2 (numb er of accumulations)) + 1 WLideal accumulator = 9 + floor(log 2 (1))) + 1 WLideal accumulator = 9 + 0 + 1 = 10 WLideal accumulator1 = WLinpput to accumulator1 + floor(log 2 ( number of accumulations)) + 1 WLideal accumulator1 = 16 + floor(log 2 (1)) + 1 WLideal accumulator1 = 16 + 0 + 1 = 17 WLideal accumulator 2 = WLinput to accumulator2 + floor(log 2 (number of accumulations)) + 1 WLideal accumulatoor 2 = 127 + floor(log 2 (1)) + 1 WLideal accumulator 2 = 127 + 0 + 1 = 128 Calculate the full-precision fraction length, which is the same for each Matrix Sum block in this example: FLideal accumulator = FLinput to accumulator FLideal accumulator = 4 Now change the Device type parameter in the Hardware Implementation pane of the Configuration Parameters dialog box to 32–bit Embedded Processor, by changing the parameters as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-33 9 Fixed-Point Design As you can see in the dialog box, this device has 8-, 16-, and 32-bit word lengths available. Therefore, the ideal word lengths of 10, 17, and 128 bits calculated by the internal rule cannot be used. Instead, the internal rule uses the next largest available word length in each case You can see this if you rerun the model, as shown in the following figure. 9-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Product Data Types Consider the following model ex_internalRule_prodExp. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-35 9 Fixed-Point Design In the Array-Vector Multiply blocks, the Product Output parameter is set to Inherit: Inherit via internal rule, and the Output parameter is set to Inherit: Same as product output. Therefore, you can see the product output data type calculated by the internal rule on the output signal in the model. The setting of the Accumulator parameter does not matter because this example uses real values. For the preceding model, the Device type parameter in the Hardware Implementation pane of the Configuration Parameters dialog box is set to ASIC/FPGA. Therefore, the product data type used by the internal rule is the ideal, full-precision result. Calculate the full-precision word length for each of the Array-Vector Multiply blocks in the model: 9-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks WLideal product = WLinput a + WLinput b WLideal product = 7 + 5 = 12 WLideal product1 = WLinput a + WLinput b WLideal product1 = 16 + 15 = 31 Calculate the full-precision fraction length, which is the same for each Array-Vector Multiply block in this example: FLideal accumulator = FLinput to accumulator FLideal accumulator = 4 Now change the Device type parameter in the Hardware Implementation pane of the Configuration Parameters dialog box to 32–bit Embedded Processor, as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-37 9 Fixed-Point Design As you can see in the dialog box, this device has 8-, 16-, and 32-bit word lengths available. Therefore, the ideal word lengths of 12 and 31 bits calculated by the internal rule cannot be used. Instead, the internal rule uses the next largest available word length in each case. You can see this if you rerun the model, as shown in the following figure. 9-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Specify Data Types for Fixed-Point Blocks The following sections show you how to use the Fixed-Point Tool to select appropriate data types for fixed-point blocks in the ex_fixedpoint_tut model: • “Prepare the Model” on page 9-39 • “Use Data Type Override to Find a Floating-Point Benchmark” on page 9-44 • “Use the Fixed-Point Tool to Propose Fraction Lengths” on page 9-45 • “Examine the Results and Accept the Proposed Scaling” on page 9-45 Prepare the Model 1 Open the model by typing ex_fixedpoint_tut at the MATLAB command line. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-39 9 Fixed-Point Design This model uses the Cumulative Sum block to sum the input coming from the FixedPoint Sources subsystem. The Fixed-Point Sources subsystem outputs two signals with different data types: • The Signed source has a word length of 16 bits and a fraction length of 15 bits. 2 • The Unsigned source has a word length of 16 bits and a fraction length of 16 bits. Run the model to check for overflow. MATLAB displays the following warnings at the command line: Warning: Overflow occurred. This originated from 'ex_fixedpoint_tut/Signed Cumulative Sum'. Warning: Overflow occurred. This originated from 'ex_fixedpoint_tut/Unsigned Cumulative Sum'. 3 9-40 According to these warnings, overflow occurs in both Cumulative Sum blocks. To investigate the overflows in this model, use the Fixed-Point Tool. You can open the Fixed-Point Tool by selecting Tools > Fixed-Point > Fixed-Point Tool www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks 4 from the model menu. Turn on logging for all blocks in your model by setting the Fixed-point instrumentation mode parameter to Minimums, maximums and overflows. Now that you have turned on logging, rerun the model by clicking the Simulation button. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-41 9 Fixed-Point Design 5 The results of the simulation appear in a table in the central Contents pane of the Fixed-Point Tool. Review the following columns: • Name — Provides the name of each signal in the following format: Subsystem Name/Block Name: Signal Name. • SimDT — The simulation data type of each logged signal. • SpecifiedDT — The data type specified on the block dialog for each signal. • SimMin — The smallest representable value achieved during simulation for each logged signal. • SimMax — The largest representable value achieved during simulation for each logged signal. • OverflowWraps — The number of overflows that wrap during simulation. For more information on each of the columns in this table, see the “Contents Pane” section of the Simulink fxptdlg function reference page. You can also see that the SimMin and SimMax values for the Accumulator data types range from 0 to .9997. The logged results indicate that 8,192 overflows wrapped during simulation in the Accumulator data type of the Signed Cumulative Sum block. Similarly, the Accumulator data type of the Unsigned Cumulative Sum block had 16,383 overflows wrap during simulation. To get more information about each of these data types, highlight them in the 6 Contents pane, and click the Show details for selected result button ( ) Assume a target hardware that supports 32-bit integers, and set the Accumulator word length in both Cumulative Sum blocks to 32. To do so, perform the following steps: 1 Right-click the Signed Cumulative Sum: Accumulator row in the FixedPoint Tool pane, and select Highlight Block In Model. 2 Double-click the block in the model, and select the Data Types pane of the dialog box. 3 Open the Data Type Assistant for Accumulator by clicking the Assistant button ( 4 9-42 ) in the Accumulator data type row. Set the Mode to Fixed Point. To see the representable range of the current specified data type, click the Fixed-point details link. The tool displays the www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks representable maximum and representable minimum values for the current data type. 5 Change the Word length to 32, and click the Refresh details button in the Fixed-point details section to see the updated representable range. When you change the value of the Word length parameter, the data type string in the Data Type edit box automatically updates. 6 Click OK on the block dialog box to save your changes and close the window. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-43 9 Fixed-Point Design 7 Set the word length of the Accumulator data type of the Unsigned Cumulative Sum block to 32 bits. You can do so in one of two ways: • Type the data type string fixdt([],32,0) directly into Data Type edit box for the Accumulator data type parameter. 7 • Perform the same steps you used to set the word length of the Accumulator data type of the Signed Cumulative Sum block to 32 bits. To verify your changes in word length and check for overflow, rerun your model. To do so, click the Simulate button in the Fixed-Point Tool. The Contents pane of the Fixed-Point Tool updates, and you can see that no overflows occurred in the most recent simulation. However, you can also see that the SimMin and SimMax values range from 0 to 0. This underflow happens because the fraction length of the Accumulator data type is too small. The SpecifiedDT cannot represent the precision of the data values. The following sections discuss how to find a floating-point benchmark and use the Fixed-Point Tool to propose fraction lengths. Use Data Type Override to Find a Floating-Point Benchmark The Data type override feature of the Fixed-Point tool allows you to override the data types specified in your model with floating-point types. Running your model in Double override mode gives you a reference range to help you select appropriate fraction lengths for your fixed-point data types. To do so, perform the following steps: 1 2 3 4 9-44 Open the Fixed-Point Tool and set Data type override to Double. Run your model by clicking the Run simulation and store active results button. Examine the results in the Contents pane of the Fixed-Point Tool. Because you ran the model in Double override mode, you get an accurate, idealized representation of the simulation minimums and maximums. These values appear in the SimMin and SimMax parameters. Now that you have an accurate reference representation of the simulation minimum and maximum values, you can more easily choose appropriate fraction lengths. Before making these choices, save your active results to reference so you can use them as your floating-point benchmark. To do so, select Results > Move Active Results To Reference from the Fixed-Point Tool menu. The status displayed in the Run column changes from Active to Reference for all signals in your model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Fixed-Point Attributes for Blocks Use the Fixed-Point Tool to Propose Fraction Lengths Now that you have your Double override results saved as a floating-point reference, you are ready to propose fraction lengths. 1 2 3 To propose fraction lengths for your data types, you must have a set of Active results available in the Fixed-Point Tool. To produce an active set of results, simply rerun your model. The tool now displays both the Active results and the Reference results for each signal. Select the Use simulation min/max if design min/max is not available check box. You did not specify any design minimums or maximums for the data types in this model. Thus, the tool uses the logged information to compute and propose fraction lengths. For information on specifying design minimums and maximums, see “Signal Ranges” in the Simulink documentation. ). The tool populates the proposed Click the Propose fraction lengths button ( data types in the ProposedDT column of the Contents pane. The corresponding proposed minimums and maximums are displayed in the ProposedMin and ProposedMax columns. Examine the Results and Accept the Proposed Scaling Before accepting the fraction lengths proposed by the Fixed-Point Tool, it is important to look at the details of that data type. Doing so allows you to see how much of your data the suggested data type can represent. To examine the suggested data types and accept the proposed scaling, perform the following steps: 1 In the Contents pane of the Fixed-Point Tool, you can see the proposed fraction lengths for the data types in your model. • The proposed fraction length for the Accumulator data type of both the Signed and Unsigned Cumulative Sum blocks is 17 bits. • To get more details about the proposed scaling for a particular data type, highlight the data type in the Contents pane of the Fixed-Point Tool. • Open the Autoscale Information window for the highlighted data type by clicking 2 the Show autoscale information for the selected result button ( ). When the Autoscale Information window opens, check the Value and Percent Proposed Representable columns for the Simulation Minimum and Simulation Maximum parameters. You can see that the proposed data type can represent 100% of the range of simulation data. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-45 9 Fixed-Point Design 3 To accept the proposed data types, select the check box in the Accept column for each data type whose proposed scaling you want to keep. Then, click the Apply accepted fraction lengths button ( 4 ). The tool updates the specified data types on the block dialog boxes and the SpecifiedDT column in the Contents pane. To verify the newly accepted scaling, set the Data type override parameter back to Use local settings, and run the model. Looking at Contents pane of the FixedPoint Tool, you can see the following details: • The SimMin and SimMax values of the Active run match the SimMin and SimMax values from the floating-point Reference run. • There are no longer any overflows. • The SimDT does not match the SpecifiedDT for the Accumulator data type of either Cumulative Sum block. This difference occurs because the Cumulative Sum block always inherits its Signedness from the input signal and only allows you to specify a Signedness of Auto. Therefore, the SpecifiedDT for both Accumulator data types is fixdt([],32,17). However, because the Signed Cumulative Sum block has a signed input signal, the SimDT for the Accumulator parameter of that block is also signed (fixdt(1,32,17)). Similarly, the SimDT for the Accumulator parameter of the Unsigned Cumulative Sum block inherits its Signedness from its input signal and thus is unsigned (fixdt(0,32,17)). 9-46 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers Quantizers In this section... “Scalar Quantizers” on page 9-47 “Vector Quantizers” on page 9-54 Scalar Quantizers • “Analysis and Synthesis of Speech” on page 9-47 • “Identify Your Residual Signal and Reflection Coefficients” on page 9-49 • “Create a Scalar Quantizer” on page 9-50 Analysis and Synthesis of Speech You can use blocks from the DSP System Toolbox Quantizers library to design scalar quantizer encoders and decoders. A speech signal is usually represented in digital format, which is a sequence of binary bits. For storage and transmission applications, it is desirable to compress a signal by representing it with as few bits as possible, while maintaining its perceptual quality. Quantization is the process of representing a signal with a reduced level of precision. If you decrease the number of bits allocated for the quantization of your speech signal, the signal is distorted and the speech quality degrades. In narrowband digital speech compression, speech signals are sampled at a rate of 8000 samples per second. Each sample is typically represented by 8 bits. This corresponds to a bit rate of 64 kbits per second. Further compression is possible at the cost of quality. Most of the current low bit rate speech coders are based on the principle of linear predictive speech coding. This topic shows you how to use the Scalar Quantizer Encoder and Scalar Quantizer Decoder blocks to implement a simple speech coder. 1 Type ex_sq_example1 at the MATLAB command line to open the example model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-47 9 Fixed-Point Design This model preemphasizes the input speech signal by applying an FIR filter. Then, it calculates the reflection coefficients of each frame using the Levinson-Durbin algorithm. The model uses these reflection coefficients to create the linear prediction analysis filter (lattice-structure). Next, the model calculates the residual signal by filtering each frame of the preemphasized speech samples using the reflection coefficients. The residual signal, which is the output of the analysis stage, usually has a lower energy than the input signal. The blocks in the synthesis stage of the model filter the residual signal using the reflection coefficients and apply an all-pole deemphasis filter. Note that the deemphasis filter is the inverse of the preemphasis filter. The result is the full recovery of the original signal. 2 9-48 Run this model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers 3 Double-click the Original Signal and Processed Signal blocks and listen to both the original and the processed signal. There is no significant difference between the two because no quantization was performed. To better approximate a real-world speech analysis and synthesis system, you need to quantize the residual signal and reflection coefficients before they are transmitted. The following topics show you how to design scalar quantizers to accomplish this task. Identify Your Residual Signal and Reflection Coefficients In the previous topic, “Analysis and Synthesis of Speech” on page 9-47, you learned the theory behind the LPC Analysis and Synthesis of Speech example model. In this topic, you define the residual signal and the reflection coefficients in your MATLAB workspace as the variables E and K, respectively. Later, you use these values to create your scalar quantizers: 1 Open the example model by typing ex_sq_example2 at the MATLAB command line. 2 Save the model file as ex_sq_example2 in your working folder. 3 From the Simulink Sinks library, click-and-drag two To Workspace blocks into your model. 4 Connect the output of the Levinson-Durbin block to one of the To Workspace blocks. 5 Double-click this To Workspace block and set the Variable name parameter to K. Click OK. 6 Connect the output of the Time-Varying Analysis Filter block to the other To Workspace block. 7 Double-click this To Workspace block and set the Variable name parameter to E. Click OK. You model should now look similar to this figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-49 9 Fixed-Point Design 8 Run your model. The residual signal, E, and your reflection coefficients, K, are defined in the MATLAB workspace. In the next topic, you use these variables to design your scalar quantizers. Create a Scalar Quantizer In this topic, you create scalar quantizer encoders and decoders to quantize the residual signal, E, and the reflection coefficients, K: 1 9-50 If the model you created in “Identify Your Residual Signal and Reflection Coefficients” on page 9-49 is not open on your desktop, you can open an equivalent model by typing ex_sq_example2 at the MATLAB command prompt. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers 2 Run this model to define the variables E and K in the MATLAB workspace. 3 From the Quantizers library, click-and-drag a Scalar Quantizer Design block into your model. Double-click this block to open the SQ Design Tool GUI. 4 For the Training Set parameter, enter K. The variable K represents the reflection coefficients you want to quantize. By definition, they range from -1 to 1. Note: Theoretically, the signal that is used as the Training Set parameter should contain a representative set of values for the parameter to be quantized. However, this example provides an approximation to this global training process. 5 For the Number of levels parameter, enter 128. Assume that your compression system has 7 bits to represent each reflection coefficient. This means it is capable of representing 27 or 128 values. The Number of levels parameter is equal to the total number of codewords in the codebook. 6 Set the Block type parameter to Both. 7 For the Encoder block name parameter, enter SQ Encoder - Reflection Coefficients. 8 For the Decoder block name parameter, enter SQ Decoder - Reflection Coefficients. 9 Make sure that your desired destination model, ex_sq_example2, is the current model. You can type gcs in the MATLAB Command Window to display the name of your current model. 10 In the SQ Design Tool GUI, click the Design and Plot button to apply the changes you made to the parameters. The GUI should look similar to the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-51 9 Fixed-Point Design 11 Click the Generate Model button. Two new blocks, SQ Encoder - Reflection Coefficients and SQ Decoder - Reflection Coefficients, appear in your model file. 12 Click the SQ Design Tool GUI and, for the Training Set parameter, enter E. 9-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers 13 Repeat steps 5 to 11 for the variable E, which represents the residual signal you want to quantize. In steps 6 and 7, name your blocks SQ Encoder - Residual and SQ Decoder - Residual. Once you have completed these steps, two new blocks, SQ Encoder - Residual and SQ Decoder - Residual, appear in your model file. 14 Close the SQ Design Tool GUI. You do not need to save the SQ Design Tool session. You have now created a scalar quantizer encoder and a scalar quantizer decoder for each signal you want to quantize. You are ready to quantize the residual signal, E, and the reflection coefficients, K. 15 Save the model as ex_sq_example3. Your model should look similar to the following figure. 16 Run your model. 17 Double-click the Original Signal and Processed Signal blocks, and listen to both signals. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-53 9 Fixed-Point Design Again, there is no perceptible difference between the two. You can therefore conclude that quantizing your residual and reflection coefficients did not affect the ability of your system to accurately reproduce the input signal. You have now quantized the residual and reflection coefficients. The bit rate of a quantization system is calculated as (bits per frame)*(frame rate). In this example, the bit rate is [(80 residual samples/frame)*(7 bits/sample) + (12 reflection coefficient samples/frame)*(7 bits/sample)]*(100 frames/second), or 64.4 kbits per second. This is higher than most modern speech coders, which typically have a bit rate of 8 to 24 kbits per second. If you decrease the number of bits allocated for the quantization of the reflection coefficients or the residual signal, the overall bit rate would decrease. However, the speech quality would also degrade. For information about decreasing the bit rate without affecting speech quality, see “Vector Quantizers” on page 9-54. Vector Quantizers • “Build Your Vector Quantizer Model” on page 9-54 • “Configure and Run Your Model” on page 9-56 Build Your Vector Quantizer Model In the previous section, you created scalar quantizer encoders and decoders and used them to quantize your residual signal and reflection coefficients. The bit rate of your scalar quantization system was 64.4 kbits per second. This bit rate is higher than most modern speech coders. To accommodate a greater number of users in each channel, you need to lower this bit rate while maintaining the quality of your speech signal. You can use vector quantizers, which exploit the correlations between each sample of a signal, to accomplish this task. In this topic, you modify your scalar quantization model so that you are using a split vector quantizer to quantize your reflection coefficients: 1 9-54 Open a model similar to the one you created in “Create a Scalar Quantizer” on page 9-50 by typing ex_vq_example1 at the MATLAB command prompt. The example model ex_vq_example1 adds a new LSF Vector Quantization subsystem to the ex_sq_example3 model. This subsystem is preconfigured to work as a vector quantizer. You can use this subsystem to encode and decode your reflection coefficients using the split vector quantization method. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers 2 Delete the SQ Encoder – Reflection Coefficients and SQ Decoder – Reflection Coefficients blocks. 3 From the Simulink Sinks library, click-and-drag a Terminator block into your model. 4 From the DSP System Toolbox Estimation > Linear Prediction library, click-anddrag a LSF/LSP to LPC Conversion block and two LPC to/from RC blocks into your model. 5 Connect the blocks as shown in the following figure. You do not need to connect Terminator blocks to the P ports of the LPC to/from RC blocks. These ports disappear once you set block parameters. You have modified your model to include a subsystem capable of vector quantization. In the next topic, you reset your model parameters to quantize your reflection coefficients using the split vector quantization method. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-55 9 Fixed-Point Design Configure and Run Your Model In the previous topic, you configured your scalar quantization model for vector quantization by adding the LSF Vector Quantization subsystem. In this topic, you set your block parameters and quantize your reflection coefficients using the split vector quantization method. 1 If the model you created in “Build Your Vector Quantizer Model” on page 9-54 is not open on your desktop, you can open an equivalent model by typing ex_vq_example2 at the MATLAB command prompt. 2 Double-click the LSF Vector Quantization subsystem, and then double-click the LSF Split VQ subsystem. The subsystem opens, and you see the three Vector Quantizer Encoder blocks used to implement the split vector quantization method. 9-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers This subsystem divides each vector of 10 line spectral frequencies (LSFs), which represent your reflection coefficients, into three LSF subvectors. Each of these subvectors is sent to a separate vector quantizer. This method is called split vector quantization. 3 Double-click the VQ of LSF: 1st subvector block. The Block Parameters: VQ of LSF: 1st subvector dialog box opens. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-57 9 Fixed-Point Design The variable CB_lsf1to3_10bit is the codebook for the subvector that contains the first three elements of the LSF vector. It is a 3-by-1024 matrix, where 3 is the number of elements in each codeword and 1024 is the number of codewords in the codebook. Because 210 = 1024 , it takes 10 bits to quantize this first subvector. Similarly, a 10-bit vector quantizer is applied to the second and third subvectors, 9-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Quantizers which contain elements 4 to 6 and 7 to 10 of the LSF vector, respectively. Therefore, it takes 30 bits to quantize all three subvectors. Note: If you used the vector quantization method to quantize your reflection coefficients, you would need 230 or 1.0737e9 codebook values to achieve the same degree of accuracy as the split vector quantization method. 4 In your model file, double-click the Autocorrelation block and set the Maximum non-negative lag (less than input length) parameter to 10. Click OK. This parameter controls the number of linear polynomial coefficients (LPCs) that are input to the split vector quantization method. 5 Double-click the LPC to/from RC block that is connected to the input of the LSF Vector Quantization subsystem. Clear the Output normalized prediction error power check box. Click OK. 6 Double-click the LSF/LSP to LPC Conversion block and set the Input parameter to LSF in range (0 to pi). Click OK. 7 Double-click the LPC to/from RC block that is connected to the output of the LSF/ LSP to LPC Conversion block. Set the Type of conversion parameter to LPC to RC, and clear the Output normalized prediction error power check box. Click OK. 8 Run your model. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-59 9 Fixed-Point Design 9 Double-click the Original Signal and Processed Signal blocks to listen to both the original and the processed signal. There is no perceptible difference between the two. Quantizing your reflection coefficients using a split vector quantization method produced good quality speech without much distortion. You have now used the split vector quantization method to quantize your reflection coefficients. The vector quantizers in the LSF Vector Quantization subsystem use 30 bits to quantize a frame containing 80 reflection coefficients. The bit rate of a quantization system is calculated as (bits per frame)*(frame rate). In this example, the bit rate is [(80 residual samples/frame)*(7 bits/sample) + (30 bits/ frame)]*(100 frames/second), or 59 kbits per second. This is less than 64.4 kbits per second, the bit rate of the scalar quantization system. However, the quality of the speech signal did not degrade. If you want to further reduce the bit rate of your system, you can use the vector quantization method to quantize the residual signal. 9-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design Fixed-Point Filter Design In this section... “Overview of Fixed-Point Filters” on page 9-61 “Data Types for Filter Functions” on page 9-61 “Floating-Point to Fixed-Point Filter Conversion” on page 9-62 “Create an FIR Filter Using Integer Coefficients” on page 9-71 “Fixed-Point Filtering in Simulink” on page 9-87 Overview of Fixed-Point Filters The most common use of fixed-point filters is in the DSP chips, where the data storage capabilities are limited, or embedded systems and devices where low-power consumption is necessary. For example, the data input may come from a 12 bit ADC, the data bus may be 16 bit, and the multiplier may have 24 bits. Within these space constraints, DSP System Toolbox software enables you to design the best possible fixed-point filter. What Is a Fixed-Point Filter? A fixed-point filter uses fixed-point arithmetic and is represented by an equation with fixed-point coefficients. To learn about fixed-point arithmetic, see “Arithmetic Operations”. Data Types for Filter Functions • “Data Type Support” on page 9-61 • “Fixed Data Type Support” on page 9-62 • “Single Data Type Support” on page 9-62 Data Type Support There are three different data types supported in DSP System Toolbox software: • Fixed — Requires Fixed-Point Designer and is supported by packages listed in “Fixed Data Type Support” on page 9-62. • Double — Double precision, floating point and is the default data type for DSP System Toolbox software; accepted by all functions www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-61 9 Fixed-Point Design • Single — Single precision, floating point and is supported by specific packages outlined in “Single Data Type Support” on page 9-62. Fixed Data Type Support To use fixed data type, you must have Fixed-Point Designer. Type ver at the MATLAB command prompt to get a listing of all installed products. The fixed data type is reserved for any filter whose property arithmetic is set to fixed. Furthermore all functions that work with this filter, whether in analysis or design, also accept and support the fixed data types. To set the filter's arithmetic property: f = fdesign.bandpass(.35,.45,.55,.65,60,1,60); Hf = design(f, 'equiripple'); Hf.Arithmetic = 'fixed'; Single Data Type Support The support of the single data types comes in two varieties. First, input data of type single can be fed into a double filter, where it is immediately converted to double. Thus, while the filter still operates in the double mode, the single data type input does not break it. The second variety is where the filter itself is set to single precision. In this case, it accepts only single data type input, performs all calculations, and outputs data in single precision. Furthermore, such analyses as noisepsd and freqrespest also operate in single precision. To set the filter to single precision: >> f = fdesign.bandpass(.35,.45,.55,.65,60,1,60); >> Hf = design(f, 'equiripple'); >> Hf.Arithmetic = 'single'; Floating-Point to Fixed-Point Filter Conversion • “Process Overview” on page 9-63 • “Design the Filter” on page 9-63 • “Quantize the Coefficients” on page 9-64 • “Dynamic Range Analysis” on page 9-67 • “Compare Magnitude Response and Magnitude Response Estimate” on page 9-68 9-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design Process Overview The conversion from floating point to fixed point consists of two main parts: quantizing the coefficients and performing the dynamic range analysis. Quantizing the coefficients is a process of converting the coefficients to fixed-point numbers. The dynamic range analysis is a process of fine tuning the scaling of each node to ensure that the fraction lengths are set for full input range coverage and maximum precision. The following steps describe this conversion process. Design the Filter Start by designing a regular, floating-point, equiripple bandpass filter, as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-63 9 Fixed-Point Design where the passband is from .45 to .55 of normalized frequency, the amount of ripple acceptable in the passband is 1 dB, the first stopband is from 0 to .35 (normalized), the second stopband is from .65 to 1 (normalized), and both stopbands provide 60 dB of attenuation. To design this filter, evaluate the following code, or type it at the MATLAB command prompt: f = fdesign.bandpass(.35,.45,.55,.65,60,1,60); Hd = design(f, 'equiripple'); fvtool(Hd) The last line of code invokes the Filter Visualization Tool, which displays the designed filter. You use Hd, which is a double, floating-point filter, both as the baseline and a starting point for the conversion. Quantize the Coefficients The first step in quantizing the coefficients is to find the valid word length for the coefficients. Here again, the hardware usually dictates the maximum allowable setting. However, if this constraint is large enough, there is room for some trial and error. Start with the coefficient word length of 8 and determine if the resulting filter is sufficient for your needs. To set the coefficient word length of 8, evaluate or type the following code at the MATLAB command prompt: Hf = Hd; Hf.Arithmetic = 'fixed'; set(Hf, 'CoeffWordLength', 8); fvtool(Hf) The resulting filter is shown in the following figure. 9-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design As the figure shows, the filter design constraints are not met. The attenuation is not complete, and there is noise at the edges of the stopbands. You can experiment with different coefficient word lengths if you like. For this example, however, the word length of 12 is sufficient. To set the coefficient word length of 12, evaluate or type the following code at the MATLAB command prompt: set(Hf, 'CoeffWordLength', 12); fvtool(Hf) The resulting filter satisfies the design constraints, as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-65 9 Fixed-Point Design Now that the coefficient word length is set, there are other data width constraints that might require attention. Type the following at the MATLAB command prompt: >> info(Hf) Discrete-Time FIR Filter (real) ------------------------------Filter Structure : Direct-Form FIR Filter Length : 48 Stable : Yes Linear Phase : Yes (Type 2) Arithmetic : fixed Numerator : s12,14 -> [-1.250000e-001 1.250000e-001) Input : s16,15 -> [-1 1) 9-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design Filter Internals : Full Precision Output : s31,29 -> [-2 2) (auto determined) Product : s27,29 -> [-1.250000e-001 1.250000e-001)... (auto determined) Accumulator : s31,29 -> [-2 2) (auto determined) Round Mode : No rounding Overflow Mode : No overflow You see the output is 31 bits, the accumulator requires 31 bits and the multiplier requires 27 bits. A typical piece of hardware might have a 16 bit data bus, a 24 bit multiplier, and an accumulator with 4 guard bits. Another reasonable assumption is that the data comes from a 12 bit ADC. To reflect these constraints type or evaluate the following code: set set set set set (Hf, (Hf, (Hf, (Hf, (Hf, 'InputWordLength', 12); 'FilterInternals', 'SpecifyPrecision'); 'ProductWordLength', 24); 'AccumWordLength', 28); 'OutputWordLength', 16); Although the filter is basically done, if you try to filter some data with it at this stage, you may get erroneous results due to overflows. Such overflows occur because you have defined the constraints, but you have not tuned the filter coefficients to handle properly the range of input data where the filter is designed to operate. Next, the dynamic range analysis is necessary to ensure no overflows. Dynamic Range Analysis The purpose of the dynamic range analysis is to fine tune the scaling of the coefficients. The ideal set of coefficients is valid for the full range of input data, while the fraction lengths maximize precision. Consider carefully the range of input data to use for this step. If you provide data that covers the largest dynamic range in the filter, the resulting scaling is more conservative, and some precision is lost. If you provide data that covers a very narrow input range, the precision can be much greater, but an input out of the design range may produce an overflow. In this example, you use the worst-case input signal, covering a full dynamic range, in order to ensure that no overflow ever occurs. This worst-case input signal is a scaled version of the sign of the flipped impulse response. To scale the coefficients based on the full dynamic range, type or evaluate the following code: x = 1.9*sign(fliplr(impz(Hf))); Hf = autoscale(Hf, x); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-67 9 Fixed-Point Design To check that the coefficients are in range (no overflows) and have maximum possible precision, type or evaluate the following code: fipref('LoggingMode', 'on', 'DataTypeOverride', 'ForceOff'); y = filter(Hf, x); fipref('LoggingMode', 'off'); R = qreport(Hf) Where R is shown in the following figure: The report shows no overflows, and all data falls within the designed range. The conversion has completed successfully. Compare Magnitude Response and Magnitude Response Estimate You can use the fvtool GUI to analysis on your quantized filter, to see the effects of the quantization on stopband attenuation, etc. Two important last checks when analyzing a quantized filter are the Magnitude Response Estimate and the Round-off Noise Power Spectrum. The value of the Magnitude Response Estimate analysis can be seen in the following example. 9-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design View the Magnitude Response Estimate Begin by designing a simple lowpass filter using the command. h = design(fdesign.lowpass, 'butter','SOSScaleNorm','Linf'); Now set the arithmetic to fixed-point. h.arithmetic = 'fixed'; Open the filter using fvtool. fvtool(h) When fvtool displays the filter using the Magnitude response view, the quantized filter seems to match the original filter quite well. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-69 9 Fixed-Point Design However if you look at the Magnitude Response Estimate plot from the Analysis menu, you will see that the actual filter created may not perform nearly as well as indicated by the Magnitude Response plot. 9-70 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design This is because by using the noise-based method of the Magnitude Response Estimate, you estimate the complex frequency response for your filter as determined by applying a noise- like signal to the filter input. Magnitude Response Estimate uses the Monte Carlo trials to generate a noise signal that contains complete frequency content across the range 0 to Fs. For more information about analyzing filters in this way, refer to the section titled “Analyzing Filters with a Noise-Based Method” in the User Guide. For more information, refer to McClellan, et al., Computer-Based Exercises for Signal Processing Using MATLAB 5, Prentice-Hall, 1998. See Project 5: Quantization Noise in Digital Filters, page 231. Create an FIR Filter Using Integer Coefficients Review of Fixed-Point Numbers Terminology of Fixed-Point Numbers DSP System Toolbox functions assume fixed-point quantities are represented in two's complement format, and are described using the WordLength and FracLength parameters. It is common to represent fractional quantities of WordLength 16 with the leftmost bit representing the sign and the remaining bits representing the fraction to the www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-71 9 Fixed-Point Design right of the binary point. Often the FracLength is thought of as the number of bits to the right of the binary point. However, there is a problem with this interpretation when the FracLength is larger than the WordLength, or when the FracLength is negative. To work around these cases, you can use the following interpretation of a fixed-point quantity: The register has a WordLength of B, or in other words it has B bits. The bits are numbered from left to right from 0 to B-1. The most significant bit (MSB) is the leftmost bit, bB-1. The least significant bit is the right-most bit, b0. You can think of the FracLength as a quantity specifying how to interpret the bits stored and resolve the value they represent. The value represented by the bits is determined by assigning a weight to each bit: In this figure, L is the integer FracLength. It can assume any value, depending on the quantization step size. L is necessary to interpret the value that the bits represent. This value is given by the equation value = -bB-1 2 B-1-L + B -2 Â bk 2k- L k =0 . The value 2–L is the smallest possible difference between two numbers represented in this format, otherwise known as the quantization step. In this way, it is preferable to think of the FracLength as the negative of the exponent used to weigh the right-most, or leastsignificant, bit of the fixed-point number. To reduce the number of bits used to represent a given quantity, you can discard the least-significant bits. This method minimizes the quantization error since the bits 9-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design you are removing carry the least weight. For instance, the following figure illustrates reducing the number of bits from 4 to 2: This means that the FracLength has changed from L to L – 2. You can think of integers as being represented with a FracLength of L = 0, so that the quantization step becomes . Suppose B = 16 and L = 0. Then the numbers that can be represented are the integers { -32768, -32767,..., -1, 0,1 ..., 32766, 32767} . If you need to quantize these numbers to use only 8 bits to represent them, you will want to discard the LSBs as mentioned above, so that B=8 and L = 0–8 = –8. The increments, or quantization step then becomes 2 -( -8) = 2 8 = 256 . So you will still have the same range of values, but with less precision, and the numbers that can be represented become { -32768, -32512,..., -256 ,0, 256 ,...32256, 32512} . With this quantization the largest possible error becomes about 256/2 when rounding to the nearest, with a special case for 32767. Integers and Fixed-Point Filters This section provides an example of how you can create a filter with integer coefficients. In this example, a raised-cosine filter with floating-point coefficients is created, and the filter coefficients are then converted to integers. Define the Filter Coefficients To illustrate the concepts of using integers with fixed-point filters, this example will use a raised-cosine filter: b = rcosdesign(.25, 12.5, 8, 'sqrt'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-73 9 Fixed-Point Design The coefficients of b are normalized so that the passband gain is equal to 1, and are all smaller than 1. In order to make them integers, they will need to be scaled. If you wanted to scale them to use 18 bits for each coefficient, the range of possible values for the coefficients becomes: [ -2 -17 , 217 - 1] == [ -131072,131071 ] Because the largest coefficient of b is positive, it will need to be scaled as close as possible to 131071 (without overflowing) in order to minimize quantization error. You can determine the exponent of the scale factor by executing: B = 18; % Number of bits L = floor(log2((2^(B-1)-1)/max(b))); bsc = b*2^L; % Round towards zero to avoid overflow Alternatively, you can use the fixed-point numbers autoscaling tool as follows: bq = fi(b, true, B); % signed = true, B = 18 bits L = bq.FractionLength; It is a coincidence that B and L are both 18 in this case, because of the value of the largest coefficient of b. If, for example, the maximum value of b were 0.124, L would be 20 while B (the number of bits) would remain 18. Build the FIR Filter First create the filter using the direct form, tapped delay line structure: h = dfilt.dffir(bsc); In order to set the required parameters, the arithmetic must be set to fixed-point: h.Arithmetic = 'fixed'; h.CoeffWordLength = 18; You can check that the coefficients of h are all integers: all(h.Numerator == round(h.Numerator)) ans = 1 Now you can examine the magnitude response of the filter using fvtool: 9-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design fvtool(h, 'Color', 'white') This shows a large gain of 117 dB in the passband, which is due to the large values of the coefficients— this will cause the output of the filter to be much larger than the input. A method of addressing this will be discussed in the following sections. Set the Filter Parameters to Work with Integers You will need to set the input parameters of your filter to appropriate values for working with integers. For example, if the input to the filter is from a A/D converter with 12 bit resolution, you should set the input as follows: h.InputWordLength = 12; h.InputFracLength = 0; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-75 9 Fixed-Point Design The info method returns a summary of the filter settings. info(h) Discrete-Time FIR Filter (real) ------------------------------Filter Structure : Direct-Form FIR Filter Length : 101 Stable : Yes Linear Phase : Yes (Type 1) Arithmetic : fixed Numerator : s18,0 -> [-131072 131072) Input : s12,0 -> [-2048 2048) Filter Internals : Full Precision Output : s31,0 -> [-1073741824 1073741824) (auto determined) Product : s29,0 -> [-268435456 268435456) (auto determined) Accumulator : s31,0 -> [-1073741824 1073741824) (auto determined) Round Mode : No rounding Overflow Mode : No overflow In this case, all the fractional lengths are now set to zero, meaning that the filter h is set up to handle integers. Create a Test Signal for the Filter You can generate an input signal for the filter by quantizing to 12 bits using the autoscaling feature, or you can follow the same procedure that was used for the coefficients, discussed previously. In this example, create a signal with two sinusoids: n = 0:999; f1 = 0.1*pi; % Normalized frequency of first sinusoid f2 = 0.8*pi; % Normalized frequency of second sinusoid x = 0.9*sin(0.1*pi*n) + 0.9*sin(0.8*pi*n); xq = fi(x, true, 12); % signed = true, B = 12 xsc = fi(xq.int, true, 12, 0); Filter the Test Signal To filter the input signal generated above, enter the following: ysc = filter(h, xsc); Here ysc is a full precision output, meaning that no bits have been discarded in the computation. This makes ysc the best possible output you can achieve given the 12–bit input and the 18–bit coefficients. This can be verified by filtering using double-precision floating-point and comparing the results of the two filtering operations: hd = double(h); 9-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design xd = double(xsc); yd = filter(hd, xd); norm(yd-double(ysc)) ans = 0 Now you can examine the output compared to the input. This example is plotting only the last few samples to minimize the effect of transients: idx = 800:950; xscext = double(xsc(idx)'); gd = grpdelay(h, [f1 f2]); yidx = idx + gd(1); yscext = double(ysc(yidx)'); stem(n(idx)', [xscext, yscext]); axis([800 950 -2.5e8 2.5e8]); legend('input', 'output'); set(gcf, 'color', 'white'); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-77 9 Fixed-Point Design It is difficult to compare the two signals in this figure because of the large difference in scales. This is due to the large gain of the filter, so you will need to compensate for the filter gain: stem(n(idx)', [2^18*xscext, yscext]); axis([800 950 -5e8 5e8]); legend('scaled input', 'output'); You can see how the signals compare much more easily once the scaling has been done, as seen in the above figure. Truncate the Output WordLength If you examine the output wordlength, ysc.WordLength ans = 9-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design 31 you will notice that the number of bits in the output is considerably greater than in the input. Because such growth in the number of bits representing the data may not be desirable, you may need to truncate the wordlength of the output. As discussed in “Terminology of Fixed-Point Numbers” on page 9-71the best way to do this is to discard the least significant bits, in order to minimize error. However, if you know there are unused high order bits, you should discard those bits as well. To determine if there are unused most significant bits (MSBs), you can look at where the growth in WordLength arises in the computation. In this case, the bit growth occurs to accommodate the results of adding products of the input (12 bits) and the coefficients (18 bits). Each of these products is 29 bits long (you can verify this using info(h)). The bit growth due to the accumulation of the product depends on the filter length and the coefficient values- however, this is a worst-case determination in the sense that no assumption on the input signal is made besides, and as a result there may be unused MSBs. You will have to be careful though, as MSBs that are deemed unused incorrectly will cause overflows. Suppose you want to keep 16 bits for the output. In this case, there is no bit-growth due to the additions, so the output bit setting will be 16 for the wordlength and –14 for the fraction length. Since the filtering has already been done, you can discard some bits from ysc: yout = fi(ysc, true, 16, -14); Alternatively, you can set the filter output bit lengths directly (this is useful if you plan on filtering many signals): specifyall(h); h.OutputWordLength = 16; h.OutputFracLength = -14; yout2 = filter(h, xsc); You can verify that the results are the same either way: norm(double(yout) - double(yout2)) ans = 0 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-79 9 Fixed-Point Design However, if you compare this to the full precision output, you will notice that there is rounding error due to the discarded bits: norm(double(yout)-double(ysc)) ans = 1.446323386867543e+005 In this case the differences are hard to spot when plotting the data, as seen below: stem(n(yidx), [double(yout(yidx)'), double(ysc(yidx)')]); axis([850 950 -2.5e8 2.5e8]); legend('Scaled Input', 'Output'); set(gcf, 'color', 'white'); Scale the Output Because the filter in this example has such a large gain, the output is at a different scale than the input. This scaling is purely theoretical however, and you can scale the 9-80 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design data however you like. In this case, you have 16 bits for the output, but you can attach whatever scaling you choose. It would be natural to reinterpret the output to have a weight of 2^0 (or L = 0) for the LSB. This is equivalent to scaling the output signal down by a factor of 2^(-14). However, there is no computation or rounding error involved. You can do this by executing the following: yri = fi(yout.int, true, 16, 0); stem(n(idx)', [xscext, double(yri(yidx)')]); axis([800 950 -1.5e4 1.5e4]); legend('input', 'rescaled output'); This plot shows that the output is still larger than the input. If you had done the filtering in double-precision floating-point, this would not be the case— because here more bits are being used for the output than for the input, so the MSBs are weighted differently. You can see this another way by looking at the magnitude response of the scaled filter: [H,w] = freqz(h); plot(w/pi, 20*log10(2^(-14)*abs(H))); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-81 9 Fixed-Point Design This plot shows that the passband gain is still above 0 dB. To put the input and output on the same scale, the MSBs must be weighted equally. The input MSB has a weight of 2^11, whereas the scaled output MSB has a weight of 2^(29– 14) = 2^15. You need to give the output MSB a weight of 2^11 as follows: yf = fi(zeros(size(yri)), true, 16, 4); yf.bin = yri.bin; stem(n(idx)', [xscext, double(yf(yidx)')]); legend('input', 'rescaled output'); 9-82 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design This operation is equivalent to scaling the filter gain down by 2^(-18). [H,w] = freqz(h); plot(w/pi, 20*log10(2^(-18)*abs(H))); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-83 9 Fixed-Point Design The above plot shows a 0 dB gain in the passband, as desired. With this final version of the output, yf is no longer an integer. However this is only due to the interpretation- the integers represented by the bits in yf are identical to the ones represented by the bits in yri. You can verify this by comparing them: max(abs(yf.int - yri.int)) ans = 0 Configure Filter Parameters to Work with Integers Using the set2int Method • “Set the Filter Parameters to Work with Integers” on page 9-85 • “Reinterpret the Output” on page 9-86 9-84 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design Set the Filter Parameters to Work with Integers The set2int method provides a convenient way of setting filter parameters to work with integers. The method works by scaling the coefficients to integer numbers, and setting the coefficients and input fraction length to zero. This makes it possible for you to use floating-point coefficients directly. h = dfilt.dffir(b); h.Arithmetic = 'fixed'; The coefficients are represented with 18 bits and the input signal is represented with 12 bits: g = set2int(h, 18, 12); g_dB = 20*log10(g) g_dB = 1.083707984390332e+002 The set2int method returns the gain of the filter by scaling the coefficients to integers, so the gain is always a power of 2. You can verify that the gain we get here is consistent with the gain of the filter previously. Now you can also check that the filter h is set up properly to work with integers: info(h) Discrete-Time FIR Filter (real) ------------------------------Filter Structure : Direct-Form FIR Filter Length : 101 Stable : Yes Linear Phase : Yes (Type 1) Arithmetic : fixed Numerator : s18,0 -> [-131072 131072) Input : s12,0 -> [-2048 2048) Filter Internals : Full Precision Output : s31,0 -> [-1073741824 1073741824) (auto determined) Product : s29,0 -> [-268435456 268435456) (auto determined) Accumulator: s31,0 -> [-1073741824 1073741824) (auto determined) Round Mode : No rounding Overflow Mode : No overflow Here you can see that all fractional lengths are now set to zero, so this filter is set up properly for working with integers. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-85 9 Fixed-Point Design Reinterpret the Output You can compare the output to the double-precision floating-point reference output, and verify that the computation done by the filter h is done in full precision. yint = filter(h, xsc); norm(yd - double(yint)) ans = 0 You can then truncate the output to only 16 bits: yout = fi(yint, true, 16); stem(n(yidx), [xscext, double(yout(yidx)')]); axis([850 950 -2.5e8 2.5e8]); legend('input', 'output'); Once again, the plot shows that the input and output are at different scales. In order to scale the output so that the signals can be compared more easily in a plot, you will need 9-86 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Fixed-Point Filter Design to weigh the MSBs appropriately. You can compute the new fraction length using the gain of the filter when the coefficients were integer numbers: WL = yout.WordLength; FL = yout.FractionLength + log2(g); yf2 = fi(zeros(size(yout)), true, WL, FL); yf2.bin = yout.bin; stem(n(idx)', [xscext, double(yf2(yidx)')]); axis([800 950 -2e3 2e3]); legend('input', 'rescaled output'); This final plot shows the filtered data re-scaled to match the input scale. Fixed-Point Filtering in Simulink • “Fixed-Point Filtering Blocks” on page 9-88 • “Filter Implementation Blocks” on page 9-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 9-87 9 Fixed-Point Design • “Filter Design and Implementation Blocks” on page 9-88 Fixed-Point Filtering Blocks The following DSP System Toolbox blocks enable you to design and/or realize a variety of fixed-point filters: • CIC Decimation • CIC Interpolation • Filter Realization Wizard • FIR Decimation • FIR Interpolation • Two-Channel Analysis Subband Filter • Two-Channel Synthesis Subband Filter Filter Implementation Blocks The FIR Decimation, FIR Interpolation, Two-Channel Analysis Subband Filter, and TwoChannel Synthesis Subband Filter blocks are all implementation blocks. They allow you to implement filters for which you already know the filter coefficients. Filter Design and Implementation Blocks The Filter Realization Wizard block invokes part of the Filter Design and Analysis Tool from Signal Processing Toolbox software. This block allows you both to design new filters and to implement filters for which you already know the coefficients. In its implementation stage, the Filter Realization Wizard creates a filter realization using Sum, Gain, and Delay blocks. You can use this block to design and/or implement numerous types of fixed-point and floating-point single-channel filters. See the Filter Realization Wizard reference page for more information about this block. The CIC Decimation and CIC Interpolation blocks allow you to design and implement Cascaded Integrator-Comb filters. See their block reference pages for more information. 9-88 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 C Code Generation Learn how to generate code for signal processing applications. • “Understanding C Code Generation” on page 10-2 • “Functions and System Objects Supported for C Code Generation” on page 10-4 • “C Code Generation from MATLAB” on page 10-12 • “C Code Generation from Simulink” on page 10-13 • “How to Run a Generated Executable Outside MATLAB” on page 10-18 • “DSP System Toolbox Supported Hardware” on page 10-19 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10 C Code Generation Understanding C Code Generation In this section... “C Code Generation with the Simulink Coder Product” on page 10-2 “Highly Optimized Generated ANSI C Code” on page 10-3 C Code Generation with the Simulink Coder Product You can use the DSP System Toolbox, Simulink Coder, and Embedded Coder® products together to generate code that you can use to implement your model for a practical application. For instance, you can create an executable from your Simulink model to run on a target chip. This chapter introduces you to the basic concepts of code generation using these tools. Shared Library Dependencies In general, the code you generate from DSP System Toolbox blocks is portable ANSI C code. After you generate the code, you can deploy it on another machine. For more information on how to do so, see “Relocate Code to Another Development Environment” in the Simulink Coder documentation. There are a few DSP System Toolbox blocks that generate code with limited portability. These blocks use precompiled shared libraries, such as DLLs, to support I/O for specific types of devices and file formats. To find out which blocks use precompiled shared libraries, open the DSP System Toolbox Block Support Table. You can identify blocks that use precompiled shared libraries by checking the footnotes listed in the Code Generation Support column of the table. All blocks that use shared libraries have the following footnote: Host computer only. Excludes Real-Time Windows (RTWIN) target. Simulink Coder provides functions to help you set up and manage the build information for your models. For example, one of the functions that Simulink Coder provides is getNonBuildFiles. This function allows you to identify the shared libraries required by blocks in your model. If your model contains any blocks that use precompiled shared libraries, you can install those libraries on the target system. The folder that you install the shared libraries in must be on the system path. The target system does not need to have MATLAB installed, but it does need to be supported by MATLAB. 10-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Understanding C Code Generation Highly Optimized Generated ANSI C Code All DSP System Toolbox blocks generate highly optimized ANSI C code. This C code is often suitable for embedded applications, and includes the following optimizations: • Function reuse (run-time libraries) — The generated code reuses common algorithmic functions via calls to shared utility functions. Shared utility functions are highly optimized ANSI/ISO C functions that implement core algorithms such as FFT and convolution. • Parameter reuse (Simulink Coder run-time parameters) — In many cases, if there are multiple instances of a block that all have the same value for a specific parameter, each block instance points to the same variable in the generated code. This process reduces memory requirements. • Blocks have parameters that affect code optimization — Some blocks, such as the Sine Wave block, have parameters that enable you to optimize the simulation for memory or for speed. These optimizations also apply to code generation. • Other optimizations — Use of contiguous input and output arrays, reusable inputs, overwritable arrays, and inlined algorithms provide smaller generated C code that is more efficient at run time. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-3 10 C Code Generation Functions and System Objects Supported for C Code Generation If you have a MATLAB Coder license, you can generate C and C++ code from MATLAB code that contains DSP System Toolbox functions and System objects. For more information about C and C++ code generation from MATLAB code, see the MATLAB Coder documentation. For more information about generating code from System objects, see “System Objects in MATLAB Code Generation”. The following DSP System Toolbox functions and System objects are supported for C and C++ code generation from MATLAB code. Name Remarks and Limitations Estimation dsp.BurgAREstimator “System Objects in MATLAB Code Generation” dsp.BurgSpectrumEstimator “System Objects in MATLAB Code Generation” dsp.CepstralToLPC “System Objects in MATLAB Code Generation” dsp.CrossSpectrumEstimator “System Objects in MATLAB Code Generation” dsp.LevinsonSolver “System Objects in MATLAB Code Generation” dsp.LPCToAutocorrelation “System Objects in MATLAB Code Generation” dsp.LPCToCepstral “System Objects in MATLAB Code Generation” dsp.LPCToLSF “System Objects in MATLAB Code Generation” dsp.LPCToLSP “System Objects in MATLAB Code Generation” dsp.LPCToRC “System Objects in MATLAB Code Generation” dsp.LSFToLPC “System Objects in MATLAB Code Generation” dsp.LSPToLPC “System Objects in MATLAB Code Generation” dsp.RCToAutocorrelation “System Objects in MATLAB Code Generation” dsp.RCToLPC “System Objects in MATLAB Code Generation” dsp.SpectrumEstimator “System Objects in MATLAB Code Generation” dsp.TransferFunctionEstimator “System Objects in MATLAB Code Generation” Filters ca2tf 10-4 All inputs must be constant. Expressions or variables are allowed if their values do not change. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and System Objects Supported for C Code Generation Name Remarks and Limitations cl2tf All inputs must be constant. Expressions or variables are allowed if their values do not change. dsp.AdaptiveLatticeFilter “System Objects in MATLAB Code Generation” dsp.AffineProjectionFilter “System Objects in MATLAB Code Generation” dsp.AllpoleFilter • “System Objects in MATLAB Code Generation” • Only the Denominator property is tunable for code generation. dsp.BiquadFilter “System Objects in MATLAB Code Generation” dsp.CICCompensationDecimator “System Objects in MATLAB Code Generation” dsp.CICCompensationInterpolator “System Objects in MATLAB Code Generation” dsp.CICDecimator “System Objects in MATLAB Code Generation” dsp.CICInterpolator “System Objects in MATLAB Code Generation” dsp.FarrowRateConverter “System Objects in MATLAB Code Generation” dsp.FastTransversalFilter “System Objects in MATLAB Code Generation” dsp.FilterCascade • You cannot generate code directly from dsp.FilterCascade. You can use the generateFilteringCode method to generate a MATLAB function. You can generate C/C++ code from this MATLAB function. • “System Objects in MATLAB Code Generation” dsp.FilteredXLMSFilter “System Objects in MATLAB Code Generation” dsp.FIRDecimator “System Objects in MATLAB Code Generation” dsp.FIRFilter • “System Objects in MATLAB Code Generation” • Only the Numerator property is tunable for code generation. dsp.FIRHalfbandDecimator “System Objects in MATLAB Code Generation” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-5 10 C Code Generation Name Remarks and Limitations dsp.FIRHalfbandInterpolator “System Objects in MATLAB Code Generation” dsp.FIRInterpolator “System Objects in MATLAB Code Generation” dsp.FIRRateConverter “System Objects in MATLAB Code Generation” dsp.FrequencyDomainAdaptiveFilter “System Objects in MATLAB Code Generation” dsp.IIRFilter • Only the Numerator and Denominator properties are tunable for code generation. • “System Objects in MATLAB Code Generation” dsp.KalmanFilter “System Objects in MATLAB Code Generation” dsp.LMSFilter “System Objects in MATLAB Code Generation” dsp.RLSFilter “System Objects in MATLAB Code Generation” dsp.SampleRateConverter “System Objects in MATLAB Code Generation” firceqrip All inputs must be constant. Expressions or variables are allowed if their values do not change. fireqint All inputs must be constant. Expressions or variables are allowed if their values do not change. firgr • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. firhalfband All inputs must be constant. Expressions or variables are allowed if their values do not change. firlpnorm • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. 10-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and System Objects Supported for C Code Generation Name Remarks and Limitations firminphase All inputs must be constant. Expressions or variables are allowed if their values do not change. firnyquist All inputs must be constant. Expressions or variables are allowed if their values do not change. firpr2chfb All inputs must be constant. Expressions or variables are allowed if their values do not change. ifir All inputs must be constant. Expressions or variables are allowed if their values do not change. iircomb All inputs must be constant. Expressions or variables are allowed if their values do not change. iirgrpdelay • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirlpnorm • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirlpnormc • All inputs must be constant. Expressions or variables are allowed if their values do not change. • Does not support syntaxes that have cell array input. iirnotch All inputs must be constant. Expressions or variables are allowed if their values do not change. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-7 10 C Code Generation Name Remarks and Limitations iirpeak All inputs must be constant. Expressions or variables are allowed if their values do not change. tf2ca All inputs must be constant. Expressions or variables are allowed if their values do not change. tf2cl All inputs must be constant. Expressions or variables are allowed if their values do not change. Math Operations dsp.ArrayVectorAdder “System Objects in MATLAB Code Generation” dsp.ArrayVectorDivider “System Objects in MATLAB Code Generation” dsp.ArrayVectorMultiplier “System Objects in MATLAB Code Generation” dsp.ArrayVectorSubtractor “System Objects in MATLAB Code Generation” dsp.CumulativeProduct “System Objects in MATLAB Code Generation” dsp.CumulativeSum “System Objects in MATLAB Code Generation” dsp.LDLFactor “System Objects in MATLAB Code Generation” dsp.LevinsonSolver “System Objects in MATLAB Code Generation” dsp.LowerTriangularSolver “System Objects in MATLAB Code Generation” dsp.LUFactor “System Objects in MATLAB Code Generation” dsp.Normalizer “System Objects in MATLAB Code Generation” dsp.UpperTriangularSolver “System Objects in MATLAB Code Generation” Quantizers dsp.ScalarQuantizerDecoder “System Objects in MATLAB Code Generation” dsp.ScalarQuantizerEncoder “System Objects in MATLAB Code Generation” dsp.VectorQuantizerDecoder “System Objects in MATLAB Code Generation” dsp.VectorQuantizerEncoder “System Objects in MATLAB Code Generation” Scopes 10-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and System Objects Supported for C Code Generation Name Remarks and Limitations dsp.SpectrumAnalyzer This System object does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. dsp.TimeScope This System object does not generate code. It is automatically declared as an extrinsic variable using the coder.extrinsic function. Signal Management dsp.Counter “System Objects in MATLAB Code Generation” dsp.DelayLine “System Objects in MATLAB Code Generation” Signal Operations dsp.Convolver “System Objects in MATLAB Code Generation” dsp.DCBlocker “System Objects in MATLAB Code Generation” dsp.Delay “System Objects in MATLAB Code Generation” dsp.DigitalDownConverter “System Objects in MATLAB Code Generation” dsp.DigitalUpConverter “System Objects in MATLAB Code Generation” dsp.Interpolator “System Objects in MATLAB Code Generation” dsp.NCO “System Objects in MATLAB Code Generation” dsp.PeakFinder “System Objects in MATLAB Code Generation” dsp.PhaseExtractor “System Objects in MATLAB Code Generation” dsp.PhaseUnwrapper “System Objects in MATLAB Code Generation” dsp.VariableFractionalDelay “System Objects in MATLAB Code Generation” dsp.VariableIntegerDelay “System Objects in MATLAB Code Generation” dsp.Window • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.ZeroCrossingDetector “System Objects in MATLAB Code Generation” Sinks dsp.AudioPlayer “System Objects in MATLAB Code Generation” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-9 10 C Code Generation Name Remarks and Limitations dsp.AudioFileWriter “System Objects in MATLAB Code Generation” dsp.UDPSender “System Objects in MATLAB Code Generation” Sources dsp.AudioFileReader “System Objects in MATLAB Code Generation” dsp.AudioRecorder “System Objects in MATLAB Code Generation” dsp.SignalSource “System Objects in MATLAB Code Generation” dsp.SineWave • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.UDPReceiver “System Objects in MATLAB Code Generation” Statistics dsp.Autocorrelator “System Objects in MATLAB Code Generation” dsp.Crosscorrelator “System Objects in MATLAB Code Generation” dsp.Histogram • This object has no tunable properties for code generation. • “System Objects in MATLAB Code Generation” dsp.Maximum “System Objects in MATLAB Code Generation” dsp.Mean “System Objects in MATLAB Code Generation” dsp.Median “System Objects in MATLAB Code Generation” dsp.Minimum “System Objects in MATLAB Code Generation” dsp.PeakToPeak “System Objects in MATLAB Code Generation” dsp.PeakToRMS “System Objects in MATLAB Code Generation” dsp.RMS “System Objects in MATLAB Code Generation” dsp.StandardDeviation “System Objects in MATLAB Code Generation” dsp.StateLevels “System Objects in MATLAB Code Generation” dsp.Variance “System Objects in MATLAB Code Generation” Transforms 10-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Functions and System Objects Supported for C Code Generation Name Remarks and Limitations dsp.AnalyticSignal “System Objects in MATLAB Code Generation” dsp.DCT “System Objects in MATLAB Code Generation” dsp.FFT “System Objects in MATLAB Code Generation” dsp.IDCT “System Objects in MATLAB Code Generation” dsp.IFFT “System Objects in MATLAB Code Generation” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-11 10 C Code Generation C Code Generation from MATLAB When you have a license for the MATLAB Coder product, you can generate standalone C and C++ from MATLAB code. See the MATLAB Coder documentation for details on supported functionality and workflow. 10-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C Code Generation from Simulink C Code Generation from Simulink In this section... “Open and Run the Model” on page 10-13 “Generate Code from the Model” on page 10-15 “Build and Run the Generated Code” on page 10-15 Note: You must have both the DSP System Toolbox and Simulink Coder products installed on your computer to complete the procedures in this section. Open and Run the Model The ex_codegen_dsp model implements a simple adaptive filter to remove noise from a signal while simultaneously identifying a filter that characterizes the noise frequency content. To open this model, enter open_system('ex_codegen_dsp') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-13 10 C Code Generation Run the model and observe the output in both scopes. This model saves the filter weights each time they adapt. You can plot the last set of coefficients using the following command: plot(filter_wts(:,:,1201)) 10-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C Code Generation from Simulink Generate Code from the Model To generate code from the model, you must first ensure that you have write permission in your current folder. The code generation process creates a new subfolder inside the current MATLAB working folder. MATLAB saves all of the files created by the code generation process in that subfolder, including those which contain the generated C source code. To start the code generation process, click the Build Model icon ( ) on your model toolbar. After the model finishes generating code, the Code Generation Report appears, allowing you to inspect the generated code. You may also notice that the build process created a new subfolder inside of your current MATLAB working folder. The name of this folder consists of the model name, followed by the suffix _grt_rtw. In the case of this example, the subfolder that contains the generated C source code is named ex_codegen_dsp_grt_rtw. Build and Run the Generated Code Setup the C/C++ Compiler If you want to build and run the generated code, you need to have access to a C compiler. For more information about which compilers are supported in the current release, see http://www.mathworks.com/support/compilers/current_release/. To setup your compiler, run the following command: mex –setup Build the Generated Code After your compiler is setup, you can build and run the generated code. The ex_codegen_dsp model is currently configured to generate code only. To build the generated code, you must first make the following changes: 1 Open the Model Configuration Parameters dialog, navigate to the Code Generation tab, and clear the Generate Code Only checkbox. 2 Click OK to apply your changes and close the dialog box. 3 From the model toolbar, click the Build Model icon ( www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان ). 10-15 10 C Code Generation Because you re-configured the model to generate and build code, the code generation process continues until the code is compiled and linked. Run the Generated Code To run the generated code, enter the following command at the MATLAB prompt: !ex_codegen_dsp Running the generated code creates a MAT-file which contains the same variables as those generated by simulating the model. The variables in the MAT-file are named with a prefix of rt_. After you run the generated code, you can load the variables from the MAT-file by typing the following command at the MATLAB prompt: load ex_codegen_dsp.mat You can now compare the variables from the generated code with the variables from the model simulation. To plot the last set of coefficients from the generated code, enter the following command at the MATLAB prompt: plot(rt_filter_wts(:,:,1201)) The last set of coefficients from the generated code are shown in the following figure. 10-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان C Code Generation from Simulink For further information on generating code from Simulink, see the “Simulink Coder” documentation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-17 10 C Code Generation How to Run a Generated Executable Outside MATLAB To run your generated standalone executable application in Shell, you need to set the environment variables as follows: Platform Command Mac setenv DYLD_LIBRARY_PATH $DYLD_LIBRARY_PATH: $MATLABROOT/ bin/maci64 (csh/tcsh) export DYLD_LIBRARY_PATH $DYLD_LIBRARY_PATH: $MATLABROOT/ bin/maci64 (Bash) Linux setenv LD_LIBRARY_PATH $LD_LIBRARY_PATH: $MATLABROOT/ bin/glnxa64 (csh/tcsh) export LD_LIBRARY_PATH $LD_LIBRARY_PATH: $MATLABROOT/ bin/glnxa64 (Bash) Windows set PATH = $MATLABROOT\bin\win32; %PATH% set PATH = $MATLABROOT\bin\win64; %PATH% 10-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان DSP System Toolbox Supported Hardware DSP System Toolbox Supported Hardware As of this release, DSP System Toolbox supports the following hardware. Support Package Vendor Platforms Earliest Release Available Last Release Available “ARM Cortex-M Processors” ARM Windows, Mac, Linux® R2013b Current “ARM Cortex-A Processors” ARM Windows, Mac, Linux R2014b Current For a complete list of supported hardware, see Hardware Support. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-19 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 10-20 11 Define New System Objects • “Summary List of Methods for Defining New System Objects” on page 11-3 • “Define Basic System Objects” on page 11-5 • “Change Number of Step Inputs or Outputs” on page 11-7 • “Specify System Block Input and Output Names” on page 11-11 • “Validate Property and Input Values” on page 11-13 • “Initialize Properties and Setup One-Time Calculations” on page 11-16 • “Set Property Values at Construction Time” on page 11-19 • “Reset Algorithm State” on page 11-21 • “Define Property Attributes” on page 11-23 • “Hide Inactive Properties” on page 11-27 • “Limit Property Values to Finite String Set” on page 11-29 • “Process Tuned Properties” on page 11-32 • “Release System Object Resources” on page 11-34 • “Define Composite System Objects” on page 11-36 • “Define Finite Source Objects” on page 11-39 • “Save System Object” on page 11-41 • “Load System Object” on page 11-44 • “Clone System Object” on page 11-47 • “Define System Object Information” on page 11-48 • “Define System Block Icon” on page 11-50 • “Add Header to System Block Dialog” on page 11-52 • “Add Property Groups to System Object and Block Dialog” on page 11-54 • “Set Output Size” on page 11-58 • “Set Output Data Type” on page 11-60 • “Set Output Complexity” on page 11-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11 Define New System Objects • “Specify Whether Output Is Fixed- or Variable-Size” on page 11-64 • “Specify Discrete State Output Specification” on page 11-66 • “Use Update and Output for Nondirect Feedthrough” on page 11-68 • “Enable For Each Subsystem Support” on page 11-71 • “Methods Timing” on page 11-73 • “System Object Input Arguments and ~ in Code Examples” on page 11-76 • “What Are Mixin Classes?” on page 11-77 • “Best Practices for Defining System Objects” on page 11-78 11-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Summary List of Methods for Defining New System Objects Summary List of Methods for Defining New System Objects The following Impl methods comprise the System objects API for defining new System objects. For more information see “Define New System Objects”. • cloneImpl • getDiscreteStateImpl • getDiscreteStateSpecificationImpl • getHeaderImpl • getIconImpl • getInputNamesImpl • getNumInputsImpl • getNumOutputsImpl • getOutputDataTypeImpl • getOutputNamesImpl • getOutputSizeImpl • getPropertyGroupsImpl • infoImpl • isInactivePropertyImpl • isInputDirectFeedthroughImpl • isOutputComplexImpl • isOutputFixedSizeImpl • loadObjectImpl • outputImpl • processTunedPropertiesImpl • propagatedInputComplexity • propagatedInputDataType • propagatedInputFixedSize • propagatedInputSize • releaseImpl • resetImpl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-3 11 Define New System Objects • saveObjectImpl • setProperties • setupImpl • stepImpl • supportsMultipleInstanceImpl • updateImpl • validateInputsImpl • validatePropertiesImpl 11-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Basic System Objects Define Basic System Objects This example shows how to create a basic System object that increments a number by one. The class definition file contains the minimum elements required to define a System object. Create the Class Definition File 1 Create a MATLAB file named AddOne.m to contain the definition of your System object. edit AddOne.m 2 Subclass your object from matlab.System. Insert this line as the first line of your file. classdef AddOne < matlab.System 3 Add the stepImpl method, which contains the algorithm that runs when users call the step method on your object. You always set the stepImpl method access to protected because it is an internal method that users do not directly call or run. All methods, except static methods, expect the System object handle as the first input argument. You can use any name for your System object handle. In this example, instead of passing in the object handle, ~ is used to indicate that the object handle is not used in the function. Using ~ instead of an object handle prevents warnings about unused variables from occurring. By default, the number of inputs and outputs are both one. To change the number of inputs or outputs, use the getNumInputsImpl or getNumOutputsImpl method, respectively. methods (Access = protected) function y = stepImpl(~,x) y = x + 1; end end Note: Instead of manually creating your class definition file, you can use an option on the New > System Object menu to open a template. The Basic template opens a simple www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-5 11 Define New System Objects System object template. The Advanced template includes more advanced features of System objects, such as backup and restore. The Simulink Extension template includes additional customizations of the System object for use in the Simulink MATLAB System block. You then can edit the template file, using it as guideline, to create your own System object. Complete Class Definition File for Basic System Object classdef AddOne < matlab.System % ADDONE Compute an output value one greater than the input value % All methods occur inside a methods declaration. % The stepImpl method has protected access methods (Access = protected) function y = stepImpl(~,x) y = x + 1; end end end See Also matlab.System | getNumInputsImpl | getNumOutputsImpl | stepImpl Related Examples • “Change Number of Step Inputs or Outputs” on page 11-7 More About • 11-6 “System Design and Simulation in MATLAB” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Change Number of Step Inputs or Outputs Change Number of Step Inputs or Outputs This example shows how to specify two inputs and two outputs for the step method. If you specify the inputs and outputs to the stepImpl method, you do not need to specify the getNumInputsImpl and getNumOutputsImpl methods. If you have a variable number of inputs or outputs (using varargin or varargout), include the getNumInputsImpl or getNumOutputsImpl method, respectively, in your class definition file. Note: You should only use getNumInputsImpl or getNumOutputsImpl methods to change the number of System object inputs or outputs. Do not use any other handle objects within a System object to change the number of inputs or outputs. You always set the getNumInputsImpl and getNumOutputsImpl methods access to protected because they are internal methods that users do not directly call or run. Update the Algorithm for Multiple Inputs and Outputs Update the stepImpl method to specify two inputs and two outputs. You do not need to implement associated getNumInputsImpl or getNumOutputsImpl methods. methods (Access = protected) function [y1,y2] = stepImpl(~,x1,x2) y1 = x1 + 1 y2 = x2 + 1; end end Update the Algorithm and Associated Methods Update the stepImpl method to use varargin and varargout. In this case, you must implement the associated getNumInputsImpl and getNumOutputsImpl methods to specify two or three inputs and outputs. methods (Access = protected) function varargout = stepImpl(obj,varargin) varargout{1} = varargin{1}+1; varargout{2} = varargin{2}+1; if (obj.numInputsOutputs = 3) varargout{3} = varargin{3}+1; end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-7 11 Define New System Objects end function validatePropertiesImpl(obj) if ~((obj.numInputsOutputs == 2) ||... (obj.numInputsOutputs == 3)) error('Only 2 or 3 input and outputs allowed.'); end end function numIn = getNumInputsImpl(obj) numIn = 3; if (obj.numInputsOutputs == 2) numIn = 2; end end function numOut = getNumOutputsImpl(obj) numOut = 3; if (obj.numInputsOutputs == 2) numOut = 2; end end end Use this syntax to run the algorithm with two inputs and two outputs. x1 = 3; x2 = 7; [y1,y2] = step(AddOne,x1,x2); To change the number of inputs or outputs, you must release the object before rerunning it. release(AddOne) x1 = 3; x2 = 7; x3 = 10 [y1,y2,y3] = step(AddOne,x1,x2,x3); Complete Class Definition File with Multiple Inputs and Outputs classdef AddOne < matlab.System % ADDONE Compute output values one greater than the input values % This property is nontunable and cannot be changed 11-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Change Number of Step Inputs or Outputs % after the setup or step method has been called. properties (Nontunable) numInputsOutputs = 3; % Default value end % All methods occur inside a methods declaration. % The stepImpl method has protected access methods (Access = protected) function varargout = stepImpl(obj,varargin) if (obj.numInputsOutputs = 2) varargout{1} = varargin{1}+1; varargout{2} = varargin{2}+1; else varargout{1} = varargin{1}+1; varargout{2} = varargin{2}+1; varargout{3} = varargin{3}+1; end end function validatePropertiesImpl(obj) if ~((obj.numInputsOutputs == 2) || (obj.numInputsOutputs == 3)) error('Only 2 or 3 input and outputs allowed.'); end end function numIn = getNumInputsImpl(obj) numIn = 3; if (obj.numInputsOutputs == 2) numIn = 2; end end function numOut = getNumOutputsImpl(obj) numOut = 3; if (obj.numInputsOutputs == 2) numOut = 2; end end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-9 11 Define New System Objects end See Also getNumInputsImpl | getNumOutputsImpl Related Examples • “Validate Property and Input Values” on page 11-13 • “Define Basic System Objects” on page 11-5 More About • 11-10 “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify System Block Input and Output Names Specify System Block Input and Output Names This example shows how to specify the names of the input and output ports of a System object–based block implemented using a MATLAB System block. Define Input and Output Names This example shows how to use getInputNamesImpl and getOutputNamesImpl to specify the names of the input port as “source data” and the output port as “count.” If you do not specify the getInputNamesImpl and getOutputNamesImpl methods, the object uses the stepImpl method input and output variable names for the input and output port names, respectively. If the stepImpl method uses varargin and varargout instead of variable names, the port names default to empty strings. methods (Access = protected) function inputName = getInputNamesImpl(~) inputName = 'source data'; end function outputName = getOutputNamesImpl(~) outputName = 'count'; end end Complete Class Definition File with Named Inputs and Outputs classdef MyCounter < matlab.System % MyCounter Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods function obj = MyCounter(varargin) setProperties (obj,nargin,varargin{:}); end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-11 11 Define New System Objects methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u) if (u > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function inputName = getInputNamesImpl(~) inputName = 'source data'; end function outputName = getOutputNamesImpl(~) outputName = 'count'; end end end See Also getInputNamesImpl | getNumInputsImpl | getNumOutputsImpl | getOutputNamesImpl Related Examples • “Change Number of Step Inputs or Outputs” on page 11-7 More About • 11-12 “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Validate Property and Input Values Validate Property and Input Values This example shows how to verify that the user’s inputs and property values are valid. Validate Properties This example shows how to validate the value of a single property using set.PropertyName syntax. In this case, the PropertyName is Increment. methods % Validate the properties of the object function set.Increment(obj,val) if val >= 10 error('The increment value must be less than 10'); end obj.Increment = val; end end This example shows how to validate the value of two interdependent properties using the validatePropertiesImpl method. In this case, the UseIncrement property value must be true and the WrapValue property value must be less than the Increment property value. methods (Access = protected) function validatePropertiesImpl(obj) if obj.UseIncrement && obj.WrapValue < obj.Increment error('Wrap value must be less than increment value'); end end end Validate Inputs This example shows how to validate that the first input is a numeric value. methods (Access = protected) function validateInputsImpl(~,x) if ~isnumeric(x) error('Input must be numeric'); end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-13 11 Define New System Objects end Complete Class Definition File with Property and Input Validation classdef AddOne < matlab.System % ADDONE Compute an output value by incrementing the input value % All properties occur inside a properties declaration. % These properties have public access (the default) properties (Logical) UseIncrement = true end properties (PositiveInteger) Increment = 1 WrapValue = 10 end methods % Validate the properties of the object function set.Increment(obj, val) if val >= 10 error('The increment value must be less than 10'); end obj.Increment = val; end end methods (Access = protected) function validatePropertiesImpl(obj) if obj.UseIncrement && obj.WrapValue < obj.Increment error('Wrap value must be less than increment value'); end end % Validate the inputs to the object function validateInputsImpl(~,x) if ~isnumeric(x) error('Input must be numeric'); end end function out = stepImpl(obj,in) if obj.UseIncrement out = in + obj.Increment; 11-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Validate Property and Input Values else out = in + 1; end end end end Note: All inputs default to variable-size inputs. See “Change Input Complexity or Dimensions” for more information. See Also validateInputsImpl | validatePropertiesImpl Related Examples • “Define Basic System Objects” on page 11-5 More About • “Methods Timing” on page 11-73 • “Property Set Methods” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-15 11 Define New System Objects Initialize Properties and Setup One-Time Calculations This example shows how to write code to initialize and set up a System object. In this example, you allocate file resources by opening the file so the System object can write to that file. You do these initialization tasks one time during setup, rather than every time you call the step method. Define Public Properties to Initialize In this example, you define the public Filename property and specify the value of that property as the nontunable string, default.bin. Users cannot change nontunable properties after the setup method has been called. Refer to the Methods Timing section for more information. properties (Nontunable) Filename = 'default.bin' end Define Private Properties to Initialize Users cannot access private properties directly, but only through methods of the System object. In this example, you define the pFileID property as a private property. You also define this property as hidden to indicate it is an internal property that never displays to the user. properties (Hidden,Access = private) pFileID; end Define Setup You use the setupImpl method to perform setup and initialization tasks. You should include code in the setupImpl method that you want to execute one time only. The setupImpl method is called once during the first call to the step method. In this example, you allocate file resources by opening the file for writing binary data. methods function setupImpl(obj) obj.pFileID = fopen(obj.Filename,'wb'); if obj.pFileID < 0 error('Opening the file failed'); 11-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Initialize Properties and Setup One-Time Calculations end end end Although not part of setup, you should close files when your code is done using them. You use the releaseImpl method to release resources. Complete Class Definition File with Initialization and Setup classdef MyFile < matlab.System % MyFile write numbers to a file % These properties are nontunable. They cannot be changed % after the setup or step method has been called. properties (Nontunable) Filename = 'default.bin' % the name of the file to create end % These properties are private. Customers can only access % these properties through methods on this object properties (Hidden,Access = private) pFileID; % The identifier of the file to open end methods (Access = protected) % In setup allocate any resources, which in this case % means opening the file. function setupImpl(obj) obj.pFileID = fopen(obj.Filename,'wb'); if obj.pFileID < 0 error('Opening the file failed'); end end % This System object™ writes the input to the file. function stepImpl(obj,data) fwrite(obj.pFileID,data); end % Use release to close the file to prevent the % file handle from being left open. function releaseImpl(obj) fclose(obj.pFileID); end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-17 11 Define New System Objects end See Also releaseImpl | setupImpl | stepImpl Related Examples • “Release System Object Resources” on page 11-34 • “Define Property Attributes” on page 11-23 More About • 11-18 “Methods Timing” on page 11-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Set Property Values at Construction Time Set Property Values at Construction Time This example shows how to define a System object constructor and allow it to accept name-value property pairs as input. Set Properties to Use Name-Value Pair Input Define the System object constructor, which is a method that has the same name as the class (MyFile in this example). Within that method, you use the setProperties method to make all public properties available for input when the user constructs the object. nargin is a MATLAB function that determines the number of input arguments. varargin indicates all of the object’s public properties. methods function obj = MyFile(varargin) setProperties(obj,nargin,varargin{:}); end end Complete Class Definition File with Constructor Setup classdef MyFile < matlab.System % MyFile write numbers to a file % These properties are nontunable. They cannot be changed % after the setup or step method has been called. properties (Nontunable) Filename ='default.bin' % the name of the file to create Access = 'wb' % The file access string (write, binary) end % These properties are private. Customers can only access % these properties through methods on this object properties (Hidden,Access = private) pFileID; % The identifier of the file to open end methods % You call setProperties in the constructor to let % a user specify public properties of object as % name-value pairs. function obj = MyFile(varargin) setProperties(obj,nargin,varargin{:}); end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-19 11 Define New System Objects end methods (Access = protected) % In setup allocate any resources, which in this case is % opening the file. function setupImpl(obj) obj.pFileID = fopen(obj.Filename,obj.Access); if obj.pFileID < 0 error('Opening the file failed'); end end % This System object™ writes the input to the file. function stepImpl(obj,data) fwrite(obj.pFileID,data); end % Use release to close the file to prevent the % file handle from being left open. function releaseImpl(obj) fclose(obj.pFileID); end end end See Also nargin | setProperties Related Examples 11-20 • “Define Property Attributes” on page 11-23 • “Release System Object Resources” on page 11-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Reset Algorithm State Reset Algorithm State This example shows how to reset an object state. Reset Counter to Zero pCount is an internal counter property of the System object obj. The user calls the reset method, which calls the resetImpl method. In this example , pCount resets to 0. Note: When resetting an object’s state, make sure you reset the size, complexity, and data type correctly. methods (Access = protected) function resetImpl(obj) obj.pCount = 0; end end Complete Class Definition File with State Reset classdef Counter < matlab.System % Counter System object™ that increments a counter properties (Access = private) pCount end methods (Access = protected) % In step, increment the counter and return % its value as an output function c = stepImpl(obj) obj.pCount = obj.pCount + 1; c = obj.pCount; end % Reset the counter to zero. function resetImpl(obj) obj.pCount = 0; end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-21 11 Define New System Objects end See “Methods Timing” on page 11-73 for more information. See Also resetImpl More About • 11-22 “Methods Timing” on page 11-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Property Attributes Define Property Attributes This example shows how to specify property attributes. Property attributes, which add details to a property, provide a layer of control to your properties. In addition to the MATLAB property attributes, System objects can use these three additional attributes—nontunable, logical, and positiveInteger. To specify multiple attributes, separate them with commas. Specify Property as Nontunable Use the nontunable attribute for a property when the algorithm depends on the value being constant once data processing starts. Defining a property as nontunable may improve the efficiency of your algorithm by removing the need to check for or react to values that change. For code generation, defining a property as nontunable allows the memory associated with that property to be optimized. You should define all properties that affect the number of input or output ports as nontunable. System object users cannot change nontunable properties after the setup or step method has been called. In this example, you define the InitialValue property, and set its value to 0. properties (Nontunable) InitialValue = 0; end Specify Property as Logical Logical properties have the value, true or false. System object users can enter 1 or 0 or any value that can be converted to a logical. The value, however, displays as true or false. You can use sparse logical values, but they must be scalar values. In this example, the Increment property indicates whether to increase the counter. By default, Increment is tunable property. The following restrictions apply to a property with the Logical attribute, • Cannot also be Dependent or PositiveInteger • Default value must be true or false. You cannot use 1 or 0 as a default value. properties (Logical) Increment = true end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-23 11 Define New System Objects Specify Property as Positive Integer In this example, the private property pCount is constrained to accept only real, positive integers. You cannot use sparse values. The following restriction applies to a property with the PositiveInteger attribute, • Cannot also be Dependent or Logical properties (PositiveInteger) Count end Specify Property as DiscreteState If your algorithm uses properties that hold state, you can assign those properties the DiscreteState attribute . Properties with this attribute display their state values when users call getDiscreteStateImpl via the getDiscreteState method. The following restrictions apply to a property with the DiscreteState attribute, • Numeric, logical, or fi value, but not a scaled double fi value • Does not have any of these attributes: Nontunable, Dependent, Abstract, Constant, or Transient. • No default value • Not publicly settable • GetAccess = Public by default • Value set only using the setupImpl method or when the System object is locked during resetImpl or stepImpl In this example, you define the Count property. properties (DiscreteState) Count; end Complete Class Definition File with Property Attributes classdef Counter < matlab.System % Counter Increment a counter to a maximum value % These properties are nontunable. They cannot be changed % after the setup or step method has been called. properties (Nontunable) 11-24 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Property Attributes % The inital value of the counter InitialValue = 0 end properties (Nontunable, PositiveInteger) % The maximum value of the counter MaxValue = 3 end properties (Logical) % Whether to increment the counter Increment = true end properties (DiscreteState) % Count state variable Count end methods (Access = protected) % In step, increment the counter and return its value % as an output function c = stepImpl(obj) if obj.Increment && (obj.Count < obj.MaxValue) obj.Count = obj.Count + 1; else disp(['Max count, ' num2str(obj.MaxValue) ',reached']) end c = obj.Count; end % Setup the Count state variable function setupImpl(obj) obj.Count = 0; end % Reset the counter to one. function resetImpl(obj) obj.Count = obj.InitialValue; end end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-25 11 Define New System Objects end More About 11-26 • “Class Attributes” • “Property Attributes” • “What You Cannot Change While Your System Is Running” • “Methods Timing” on page 11-73 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Hide Inactive Properties Hide Inactive Properties This example shows how to hide the display of a property that is not active for a particular object configuration. Hide an inactive property You use the isInactivePropertyImpl method to hide a property from displaying. If the isInactiveProperty method returns true to the property you pass in, then that property does not display. methods (Access = protected) function flag = isInactivePropertyImpl(obj,propertyName) if strcmp(propertyName,'InitialValue') flag = obj.UseRandomInitialValue; else flag = false; end end end Complete Class Definition File with Hidden Inactive Property classdef Counter < matlab.System % Counter Increment a counter % These properties are nontunable. They cannot be changed % after the setup or step method has been called. properties (Nontunable) % Allow the user to set the initial value UseRandomInitialValue = true InitialValue = 0 end % The private count variable, which is tunable by default properties (Access = private) pCount end methods (Access = protected) % In step, increment the counter and return its value % as an output function c = stepImpl(obj) obj.pCount = obj.pCount + 1; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-27 11 Define New System Objects c = obj.pCount; end % Reset the counter to either a random value or the initial % value. function resetImpl(obj) if obj.UseRandomInitialValue obj.pCount = rand(); else obj.pCount = obj.InitialValue; end end % This method controls visibility of the object's properties function flag = isInactivePropertyImpl(obj,propertyName) if strcmp(propertyName,'InitialValue') flag = obj.UseRandomInitialValue; else flag = false; end end end end See Also isInactivePropertyImpl 11-28 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Limit Property Values to Finite String Set Limit Property Values to Finite String Set This example shows how to limit a property to accept only a finite set of string values. Specify a Set of Valid String Values String sets use two related properties. You first specify the user-visible property name and default string value. Then, you specify the associated hidden property by appending “Set” to the property name. You must use a capital “S” in “Set.” In the “Set” property, you specify the valid string values as a cell array of the matlab.system.Stringset class. This example uses Color and ColorSet as the associated properties. properties Color = 'blue' end properties (Hidden,Transient) ColorSet = matlab.system.StringSet({'red','blue','green'}); end Complete Class Definition File with String Set classdef Whiteboard < matlab.System % Whiteboard Draw lines on a figure window % % This System object™ illustrates the use of StringSets properties Color = 'blue' end properties (Hidden,Transient) % Let them choose a color ColorSet = matlab.system.StringSet({'red','blue','green'}); end methods (Access = protected) function stepImpl(obj) h = Whiteboard.getWhiteboard(); plot(h, ... randn([2,1]),randn([2,1]), ... 'Color',obj.Color(1)); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-29 11 Define New System Objects end function releaseImpl(obj) cla(Whiteboard.getWhiteboard()); hold on end end methods (Static) function a = getWhiteboard() h = findobj('tag','whiteboard'); if isempty(h) h = figure('tag','whiteboard'); hold on end a = gca; end end end String Set System Object Example %% % Each call to step draws lines on a whiteboard %% Construct the System object hGreenInk = Whiteboard; hBlueInk = Whiteboard; % Change the color % Note: Press tab after typing the first single quote to % display all enumerated values. hGreenInk.Color = 'green'; hBlueInk.Color = 'blue'; % Take a few steps for i=1:3 hGreenInk.step(); hBlueInk.step(); end %% Clear the whiteboard hBlueInk.release(); %% Display System object used in this example 11-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Limit Property Values to Finite String Set type('Whiteboard.m'); See Also matlab.system.StringSet www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-31 11 Define New System Objects Process Tuned Properties This example shows how to specify the action to take when a tunable property value changes during simulation. The processTunedPropertiesImpl method is useful for managing actions to prevent duplication. In many cases, changing one of multiple interdependent properties causes an action. With the processTunedPropertiesImpl method, you can control when that action is taken so it is not repeated unnecessarily. Control When a Lookup Table Is Generated This example of processTunedPropertiesImpl causes the pLookupTable to be regenerated when either the NumNotes or MiddleC property changes. methods (Access = protected) function processTunedPropertiesImpl(obj) obj.pLookupTable = obj.MiddleC * ... (1+log(1:obj.NumNotes)/log(12)); end end Complete Class Definition File with Tuned Property Processing classdef TuningFork < matlab.System % TuningFork Illustrate the processing of tuned parameters % properties MiddleC = 440 NumNotes = 12 end properties (Access = private) pLookupTable end methods (Access = protected) function resetImpl(obj) obj.MiddleC = 440; obj.pLookupTable = obj.MiddleC * ... (1+log(1:obj.NumNotes)/log(12)); end 11-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Process Tuned Properties function hz = stepImpl(obj,noteShift) % A noteShift value of 1 corresponds to obj.MiddleC hz = obj.pLookupTable(noteShift); end function processTunedPropertiesImpl(obj) % Generate a lookup table of note frequencies obj.pLookupTable = obj.MiddleC * ... (1+log(1:obj.NumNotes)/log(12)); end end end See Also processTunedPropertiesImpl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-33 11 Define New System Objects Release System Object Resources This example shows how to release resources allocated and used by the System object. These resources include allocated memory, files used for reading or writing, etc. Release Memory by Clearing the Object This method allows you to clear the axes on the Whiteboard figure window while keeping the figure open. methods function releaseImpl(obj) cla(Whiteboard.getWhiteboard()); hold on end end Complete Class Definition File with Released Resources classdef Whiteboard < matlab.System % Whiteboard Draw lines on a figure window % % This System object™ shows the use of StringSets % properties Color = 'blue' end properties (Hidden) % Let user choose a color ColorSet = matlab.system.StringSet({'red','blue','green'}); end methods (Access = protected) function stepImpl(obj) h = Whiteboard.getWhiteboard(); plot(h, ... randn([2,1]), randn([2,1]), ... 'Color',obj.Color(1)); end function releaseImpl(obj) cla(Whiteboard.getWhiteboard()); hold on 11-34 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Release System Object Resources end methods (Static) function a = getWhiteboard() h = findobj('tag','whiteboard'); if isempty(h) h = figure('tag','whiteboard'); hold on end a = gca; end end end See Also releaseImpl Related Examples • “Initialize Properties and Setup One-Time Calculations” on page 11-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-35 11 Define New System Objects Define Composite System Objects This example shows how to define System objects that include other System objects. This example defines a filter System object from an FIR System object and an IIR System object. Store System Objects in Properties To define a System object from other System objects, store those objects in your class definition file as properties. In this example, FIR and IIR are separate System objects defined in their own class-definition files. You use those two objects to calculate the pFir and pIir property values. properties (Nontunable, Access = private) pFir % Store the FIR filter pIir % Store the IIR filter end methods function obj = Filter(varargin) setProperties(obj,nargin,varargin{:}); obj.pFir = FIR(obj.zero); obj.pIir = IIR(obj.pole); end end Complete Class Definition File of Composite System Object classdef Filter < matlab.System % Filter System object with a single pole and a single zero % % This System object illustrates composition by % composing an instance of itself. % properties (Nontunable) zero = 0.01 pole = 0.5 end properties (Nontunable,Access = private) pZero % Store the FIR filter pPole % Store the IIR filter 11-36 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Composite System Objects end methods function obj = Filter(varargin) setProperties(obj,nargin,varargin{:}); % Create instances of FIR and IIR as % private properties obj.pZero = Zero(obj.zero); obj.pPole = Pole(obj.pole); end end methods (Access = protected) function setupImpl(obj,x) setup(obj.pZero,x); setup(obj.pPole,x); end function resetImpl(obj) reset(obj.pZero); reset(obj.pPole); end function y = stepImpl(obj,x) y = step(obj.pZero,x) + step(obj.pPole,x); end function releaseImpl(obj) release(obj.pZero); release(obj.pPole); end end end Class Definition File for IIR Component of Filter classdef Pole < matlab.System properties Den = 1 end properties (Access = private) tap = 0 end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-37 11 Define New System Objects methods function obj = Pole(varargin) setProperties(obj,nargin,varargin{:},'Den'); end end methods (Access = protected) function y = stepImpl(obj,x) y = x + obj.tap * obj.Den; obj.tap = y; end end end Class Definition File for FIR Component of Filter classdef Zero < matlab.System properties Num = 1 end properties (Access = private) tap = 0 end methods function obj = Zero(varargin) setProperties(obj,nargin,varargin{:},'Num'); end end methods (Access = protected) function y = stepImpl(obj,x) y = x + obj.tap * obj.Num; obj.tap = x; end end end See Also nargin 11-38 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define Finite Source Objects Define Finite Source Objects This example shows how to define a System object that performs a specific number of steps or specific number of reads from a file. Use the FiniteSource Class and Specify End of the Source 1 Subclass from finite source class. classdef RunTwice < matlab.System & ... matlab.system.mixin.FiniteSource 2 Specify the end of the source with the isDoneImpl method. In this example, the source has two iterations. methods (Access = protected) function bDone = isDoneImpl(obj) bDone = obj.NumSteps==2 end Complete Class Definition File with Finite Source classdef RunTwice < matlab.System & ... matlab.system.mixin.FiniteSource % RunTwice System object that runs exactly two times % properties (Access = private) NumSteps end methods (Access = protected) function resetImpl(obj) obj.NumSteps = 0; end function y = stepImpl(obj) if ~obj.isDone() obj.NumSteps = obj.NumSteps + 1; y = obj.NumSteps; else y = 0; end end function bDone = isDoneImpl(obj) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-39 11 Define New System Objects bDone = obj.NumSteps==2; end end end See Also matlab.system.mixin.FiniteSource More About 11-40 • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Save System Object Save System Object This example shows how to save a System object. Save System Object and Child Object Define a saveObjectImpl method to specify that more than just public properties should be saved when the user saves a System object. Within this method, use the default [email protected] to save public properties to the struct, s. Use the saveObject method to save child objects. Save protected and dependent properties, and finally, if the object is locked, save the object’s state. methods (Access = protected) function s = saveObjectImpl(obj) s = [email protected](obj); s.child = matlab.System.saveObject(obj.child); s.protected = obj.protected; s.pdependentprop = obj.pdependentprop; if isLocked(obj) s.state = obj.state; end end end Complete Class Definition File with Save and Load classdef MySaveLoader < matlab.System properties (Access = private) child pdependentprop end properties (Access = protected) protected = rand; end properties (DiscreteState = true) state end properties (Dependent) dependentprop end www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-41 11 Define New System Objects methods function obj = MySaveLoader(varargin) [email protected](); setProperties(obj,nargin,varargin{:}); end end methods (Access = protected) function setupImpl(obj) obj.state = 42; end function out = stepImpl(obj,in) obj.state = in; out = obj.state; end end % Serialization methods (Access = protected) function s = saveObjectImpl(obj) % Call the base class method s = [email protected](obj); % Save the child System objects s.child = matlab.System.saveObject(obj.child); % Save the protected & private properties s.protected = obj.protected; s.pdependentprop = obj.pdependentprop; % Save the state only if object locked if isLocked(obj) s.state = obj.state; end end function loadObjectImpl(obj,s,wasLocked) % Load child System objects obj.child = matlab.System.loadObject(s.child); % Load protected and private properties 11-42 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Save System Object obj.protected = s.protected; obj.pdependentprop = s.pdependentprop; % Load the state only if object locked if wasLocked obj.state = s.state; end % Call base class method to load public properties [email protected](obj,s,wasLocked); end end end See Also loadObjectImpl | saveObjectImpl Related Examples • “Load System Object” on page 11-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-43 11 Define New System Objects Load System Object This example shows how to load a System object. Load System Object and Child Object Define a loadObjectImpl method to load a previously saved System object. Within this method, use the matlab.System.loadObject to assign the child object struct data to the associated object property. Assign protected and dependent property data to the associated object properties. If the object was locked when it was saved, assign the object’s state to the associated property. Load the saved public properties with the loadObjectImpl method. methods (Access = protected) function loadObjectImpl(obj,s,wasLocked) obj.child = matlab.System.loadObject(s.child); obj.protected = s.protected; obj.pdependentprop = s.pdependentprop; if wasLocked obj.state = s.state; end [email protected](obj,s,wasLocked); end end end Complete Class Definition File with Save and Load classdef MySaveLoader < matlab.System properties (Access = private) child pdependentprop end properties (Access = protected) protected = rand; end properties (DiscreteState = true) state end properties (Dependent) 11-44 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Load System Object dependentprop end methods function obj = MySaveLoader(varargin) [email protected](); setProperties(obj,nargin,varargin{:}); end end methods (Access = protected) function setupImpl(obj) obj.state = 42; end function out = stepImpl(obj,in) obj.state = in; out = obj.state; end end % Serialization methods (Access = protected) function s = saveObjectImpl(obj) % Call the base class method s = [email protected](obj); % Save the child System objects s.child = matlab.System.saveObject(obj.child); % Save the protected & private properties s.protected = obj.protected; s.pdependentprop = obj.pdependentprop; % Save the state only if object locked if isLocked(obj) s.state = obj.state; end end function loadObjectImpl(obj,s,wasLocked) % Load child System objects obj.child = matlab.System.loadObject(s.child); www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-45 11 Define New System Objects % Load protected and private properties obj.protected = s.protected; obj.pdependentprop = s.pdependentprop; % Load the state only if object locked if wasLocked obj.state = s.state; end % Call base class method to load public properties [email protected](obj,s,wasLocked); end end end See Also loadObjectImpl | saveObjectImpl Related Examples • 11-46 “Save System Object” on page 11-41 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Clone System Object Clone System Object This example shows how to clone a System object. Clone System Object You can define your own clone method, which is useful for copying objects without saving their state. The default cloneImpl method copies both a System object™ and its current state. If an object is locked, the default cloneImpl creates a cloned object that is also locked. An example of when you may want to write your own clone method is for cloning objects that handle resources. These objects cannot allocate resources twice and you would not want to save their states. To write your clone method, use the saveObject and loadObject methods to perform the clone within the cloneImpl method. methods (Access = protected) function obj2 = cloneImpl(obj1) s = saveObject (obj1); obj2 = loadObject(s); end end Complete Class Definition File with Clone classdef PassThrough < matlab.System methods (Access = protected) function y = stepImpl(~,u) y = u; end function obj2 = cloneImpl(obj1) s = matlab.System.saveObject(obj1); obj2 = matlab.System.loadObject(s); end end end See Also cloneImpl | loadObjectImpl | saveObjectImpl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-47 11 Define New System Objects Define System Object Information This example shows how to define information to display for a System object. Define System Object Info You can define your own info method to display specific information for your System object. The default infoImpl method returns an empty struct. This infoImpl method returns detailed information when the info method is called using info(x,'details') or only count information if it is called using info(x). methods (Access = protected) function s = infoImpl(obj,varargin) if nargin>1 && strcmp('details',varargin(1)) s = struct('Name','Counter',... 'Properties', struct('CurrentCount', ... obj.pCount,'Threshold',obj.Threshold)); else s = struct('Count',obj.pCount); end end end Complete Class Definition File with InfoImpl classdef Counter < matlab.System % Counter Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) obj.Count = 0; end 11-48 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define System Object Information function y = stepImpl(obj,u) if (u > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function s = infoImpl(obj,varargin) if nargin>1 && strcmp('details',varargin(1)) s = struct('Name','Counter',... 'Properties', struct('CurrentCount', ... obj.pCount,'Threshold',obj.Threshold)); else s = struct('Count',obj.pCount); end end end See Also infoImpl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-49 11 Define New System Objects Define System Block Icon This example shows how to define the block icon of a System object–based block implemented using a MATLAB System block. Use the CustomIcon Class and Define the Icon 1 Subclass from custom icon class. classdef MyCounter < matlab.System & ... matlab.system.mixin.CustomIcon 2 Use getIconImpl to specify the block icon as New Counter with a line break (\n) between the two words. methods (Access = protected) function icon = getIconImpl(~) icon = sprintf('New\nCounter'); end end Complete Class Definition File with Defined Icon classdef MyCounter < matlab.System & ... matlab.system.mixin.CustomIcon % MyCounter Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods function obj = MyCounter(varargin) setProperties(obj,nargin,varargin{:}); end end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end 11-50 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Define System Block Icon function resetImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u) if (u > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function icon = getIconImpl(~) icon = sprintf('New\nCounter'); end end end See Also matlab.system.mixin.CustomIcon | getIconImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-51 11 Define New System Objects Add Header to System Block Dialog This example shows how to add a header panel to a System object–based block implemented using a MATLAB System block. Define Header Title and Text This example shows how to use getHeaderImpl to specify a panel title and text for the MyCounter System object. If you do not specify the getHeaderImpl, the block does not display any title or text for the panel. You always set the getHeaderImpl method access to protected because it is an internal method that end users do not directly call or run. methods (Static, Access = protected) function header = getHeaderImpl header = matlab.system.display.Header('MyCounter',... 'Title','My Enhanced Counter'); end end Complete Class Definition File with Defined Header classdef MyCounter < matlab.System % MyCounter Count values properties Threshold = 1 end properties (DiscreteState) Count end methods (Static, Access = protected) function header = getHeaderImpl header = matlab.system.display.Header('MyCounter',... 'Title','My Enhanced Counter',... 'Text', 'This counter is an enhanced version.'); end end 11-52 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Add Header to System Block Dialog methods (Access = protected) function setupImpl(obj,u) obj.Count = 0; end function y = stepImpl(obj,u) if (u > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function resetImpl(obj) obj.Count = 0; end end end See Also matlab.system.display.Header | getHeaderImpl www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-53 11 Define New System Objects Add Property Groups to System Object and Block Dialog This example shows how to define property sections and section groups for System object display. The sections and section groups display as panels and tabs, respectively, in the MATLAB System block dialog. Define Section of Properties This example shows how to use matlab.system.display.Section and getPropertyGroupsImpl to define two property group sections by specifying their titles and property lists. If you do not specify a property in getPropertyGroupsImpl, the block does not display that property. methods (Static, Access = protected) function groups = getPropertyGroupsImpl valueGroup = matlab.system.display.Section(... 'Title','Value parameters',... 'PropertyList',{'StartValue','EndValue'}); thresholdGroup = matlab.system.display.Section(... 'Title','Threshold parameters',... 'PropertyList',{'Threshold','UseThreshold'}); groups = [valueGroup,thresholdGroup]; end end Define Group of Sections This example shows how to use matlab.system.display.SectionGroup, matlab.system.display.Section, and getPropertyGroupsImpl to define two tabs, each containing specific properties. methods (Static, Access = protected) function groups = getPropertyGroupsImpl upperGroup = matlab.system.display.Section(... 'Title', 'Upper threshold', ... 'PropertyList',{'UpperThreshold'}); lowerGroup = matlab.system.display.Section(... 'Title','Lower threshold', ... 'PropertyList',{'UseLowerThreshold','LowerThreshold'}); thresholdGroup = matlab.system.display.SectionGroup(... 11-54 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Add Property Groups to System Object and Block Dialog 'Title', 'Parameters', ... 'Sections', [upperGroup,lowerGroup]); valuesGroup = matlab.system.display.SectionGroup(... 'Title', 'Initial conditions', ... 'PropertyList', {'StartValue'}); groups = [thresholdGroup, valuesGroup]; end end Complete Class Definition File with Property Group and Separate Tab classdef EnhancedCounter < matlab.System % EnhancedCounter Count values considering thresholds properties UpperThreshold = 1; LowerThreshold = 0; end properties (Nontunable) StartValue = 0; end properties(Logical,Nontunable) % Count values less than lower threshold UseLowerThreshold = true; end properties (DiscreteState) Count; end methods (Static, Access = protected) function groups = getPropertyGroupsImpl upperGroup = matlab.system.display.Section(... 'Title', 'Upper threshold', ... 'PropertyList',{'UpperThreshold'}); lowerGroup = matlab.system.display.Section(... 'Title','Lower threshold', ... 'PropertyList',{'UseLowerThreshold','LowerThreshold'}); thresholdGroup = matlab.system.display.SectionGroup(... 'Title', 'Parameters', ... www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-55 11 Define New System Objects 'Sections', [upperGroup,lowerGroup]); valuesGroup = matlab.system.display.SectionGroup(... 'Title', 'Initial conditions', ... 'PropertyList', {'StartValue'}); groups = [thresholdGroup, valuesGroup]; end end methods (Access = protected) function setupImpl(obj) obj.Count = obj.StartValue; end function y = stepImpl(obj,u) if obj.UseLowerThreshold if (u > obj.UpperThreshold) || ... (u < obj.LowerThreshold) obj.Count = obj.Count + 1; end else if (u > obj.UpperThreshold) obj.Count = obj.Count + 1; end end y = obj.Count; end function resetImpl(obj) obj.Count = obj.StartValue; end function flag = isInactivePropertyImpl(obj, prop) flag = false; switch prop case 'LowerThreshold' flag = ~obj.UseLowerThreshold; end end end 11-56 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Add Property Groups to System Object and Block Dialog end See Also matlab.system.display.Section | matlab.system.display.SectionGroup | getPropertyGroupsImpl More About • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-57 11 Define New System Objects Set Output Size This example shows how to specify the size of a System object output using the getOutputSizeImpl method. Use this method when Simulink cannot infer the output size from the inputs during model compilation. Subclass from both the matlab.System base class and the Propagates mixin class. classdef CounterReset < matlab.System & ... matlab.system.mixin.Propagates Use the getOutputSizeImpl method to specify the output size. methods (Access = protected) function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end end View the method in the complete class definition file. classdef CounterReset < matlab.System & matlab.system.mixin.Propagates % CounterReset Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u1,u2) % Add to count if u1 is above threshold % Reset if u2 is true if (u2) obj.Count = 0; elseif (u1 > obj.Threshold) obj.Count = obj.Count + 1; 11-58 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Set Output Size end y = obj.Count; end function resetImpl(obj) obj.Count = 0; end function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) if strcmp(name,'Count') sz = [1 1]; dt = 'double'; cp = false; else error(['Error: Incorrect State Name: 'name'.']); end end function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end function cplxout = isOutputComplexImpl(~) cplxout = false; end function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end end See Also matlab.system.mixin.Propagates | getOutputSizeImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-59 11 Define New System Objects Set Output Data Type This example shows how to specify the data type of a System object output using the getOutputDataTypeImpl method. Use this method when Simulink cannot infer the data type from the inputs during model compilation. Subclass from both the matlab.System base class and the Propagates mixin class. classdef CounterReset < matlab.System & ... matlab.system.mixin.Propagates Use the getOutputDataTypeImpl method to specify the output data type as a double. methods (Access = protected) function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end end View the method in the complete class definition file. classdef CounterReset < matlab.System & matlab.system.mixin.Propagates % CounterReset Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u1,u2) % Add to count if u1 is above threshold % Reset if u2 is true 11-60 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Set Output Data Type if (u2) obj.Count = 0; elseif (u1 > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) if strcmp(name,'Count') sz = [1 1]; dt = 'double'; cp = false; else error(['Error: Incorrect State Name: 'name'.']); end end function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end function cplxout = isOutputComplexImpl(~) cplxout = false; end function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end end See Also matlab.system.mixin.Propagates | getOutputDataTypeImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-61 11 Define New System Objects Set Output Complexity This example shows how to specify whether a System object output is complex or real using the isOutputComplexImpl method. Use this method when Simulink cannot infer the output complexity from the inputs during model compilation. Subclass from both the matlab.System base class and the Propagates mixin class. classdef CounterReset < matlab.System & ... matlab.system.mixin.Propagates Use the isOutputComplexImpl method to specify that the output is real. methods (Access = protected) function cplxout = isOutputComplexImpl(~) cplxout = false; end end View the method in the complete class definition file. classdef CounterReset < matlab.System & matlab.system.mixin.Propagates % CounterReset Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u1,u2) % Add to count if u1 is above threshold % Reset if u2 is true 11-62 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Set Output Complexity if (u2) obj.Count = 0; elseif (u1 > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) if strcmp(name,'Count') sz = [1 1]; dt = 'double'; cp = false; else error(['Error: Incorrect State Name: 'name'.']); end end function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end function cplxout = isOutputComplexImpl(~) cplxout = false; end function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end end See Also matlab.system.mixin.Propagates | isOutputComplexImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-63 11 Define New System Objects Specify Whether Output Is Fixed- or Variable-Size This example shows how to specify whether a System object output is fixed- or variablesize. Use the isOutputFixedSizeImpl method when Simulink cannot infer the output type from the inputs during model compilation. Subclass from both the matlab.System base class and the Propagates mixin class. classdef CounterReset < matlab.System & ... matlab.system.mixin.Propagates Use the isOutputFixedSizeImpl method to specify that the output is fixed size. methods (Access = protected) function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end View the method in the complete class definition file. classdef CounterReset < matlab.System & matlab.system.mixin.Propagates % CounterReset Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) obj.Count = 0; end function y = stepImpl(obj,u1,u2) % Add to count if u1 is above threshold % Reset if u2 is true 11-64 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Whether Output Is Fixed- or Variable-Size if (u2) obj.Count = 0; elseif (u1 > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) if strcmp(name,'Count') sz = [1 1]; dt = 'double'; cp = false; else error(['Error: Incorrect State Name: 'name'.']); end end function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end function cplxout = isOutputComplexImpl(~) cplxout = false; end function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end end See Also matlab.system.mixin.Propagates | isOutputFixedSizeImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-65 11 Define New System Objects Specify Discrete State Output Specification This example shows how to specify the size, data type, and complexity of a discrete state property using the getDiscreteStateSpecificationImpl method. Use this method when your System object has a property with the DiscreteState attribute and Simulink cannot infer the output specifications during model compilation. Subclass from both the matlab.System base class and from the Propagates mixin class. classdef CounterReset < matlab.System & ... matlab.system.mixin.Propagates Use the getDiscreteStateSpecificationImpl method to specify the size and data type. Also specify the complexity of a discrete state property, which is used in the counter reset example. methods (Access = protected) function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) sz = [1 1]; dt = 'double'; cp = false; end end View the method in the complete class definition file. classdef CounterReset < matlab.System & matlab.system.mixin.Propagates % CounterReset Count values above a threshold properties Threshold = 1 end properties (DiscreteState) Count end methods (Access = protected) function setupImpl(obj) obj.Count = 0; end function resetImpl(obj) 11-66 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Specify Discrete State Output Specification obj.Count = 0; end function y = stepImpl(obj,u1,u2) % Add to count if u1 is above threshold % Reset if u2 is true if (u2) obj.Count = 0; elseif (u1 > obj.Threshold) obj.Count = obj.Count + 1; end y = obj.Count; end function [sz,dt,cp] = getDiscreteStateSpecificationImpl(~,name) sz = [1 1]; dt = 'double'; cp = false; end function dataout = getOutputDataTypeImpl(~) dataout = 'double'; end function sizeout = getOutputSizeImpl(~) sizeout = [1 1]; end function cplxout = isOutputComplexImpl(~) cplxout = false; end function fixedout = isOutputFixedSizeImpl(~) fixedout = true; end end end See Also matlab.system.mixin.Propagates | getDiscreteStateSpecificationImpl More About • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-67 11 Define New System Objects Use Update and Output for Nondirect Feedthrough This example shows how to implement nondirect feedthrough for a System object using the updateImpl, outputImpl and isInputDirectFeedthroughImpl methods. In nondirect feedthrough, the object’s outputs depend only on the internal states and properties of the object, rather than the input at that instant in time. You use these methods to separate the output calculation from the state updates of a System object. This enables you to use that object in a feedback loop and prevent algebraic loops. Subclass from the Nondirect Mixin Class To use the updateImpl, outputImpl, and isInputDirectFeedthroughImpl methods, you must subclass from both the matlab.System base class and the Nondirect mixin class. classdef IntegerDelaySysObj < matlab.System & ... matlab.system.mixin.Nondirect Implement Updates to the Object Implement an updateImpl method to update the object with previous inputs. methods (Access = protected) function updateImpl(obj,u) obj.PreviousInput = [u obj.PreviousInput(1:end-1)]; end end Implement Outputs from Object Implement an outputImpl method to output the previous, not the current input. methods (Access = protected) function [y] = outputImpl(obj,~) y = obj.PreviousInput(end); end end Implement Whether Input Is Direct Feedthrough Implement an isInputDirectFeedthroughImpl method to indicate that the input is nondirect feedthrough. methods (Access = protected) 11-68 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Use Update and Output for Nondirect Feedthrough function flag = isInputDirectFeedthroughImpl(~,~) flag = false; end end Complete Class Definition File with Update and Output classdef intDelaySysObj < matlab.System &... matlab.system.mixin.Nondirect &... matlab.system.mixin.CustomIcon % intDelaySysObj Delay input by specified number of samples. properties InitialOutput = 0; end properties (Nontunable) NumDelays = 1; end properties (DiscreteState) PreviousInput; end methods (Access = protected) function validatePropertiesImpl(obj) if ((numel(obj.NumDelays)>1) || (obj.NumDelays <= 0)) error('Number of delays must be positive non-zero scalar value.'); end if (numel(obj.InitialOutput)>1) error('Initial Output must be scalar value.'); end end function setupImpl(obj) obj.PreviousInput = ones(1,obj.NumDelays)*obj.InitialOutput; end function resetImpl(obj) obj.PreviousInput = ones(1,obj.NumDelays)*obj.InitialOutput; end function [y] = outputImpl(obj,~) y = obj.PreviousInput(end); end function updateImpl(obj, u) obj.PreviousInput = [u obj.PreviousInput(1:end-1)]; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-69 11 Define New System Objects end function flag = isInputDirectFeedthroughImpl(~,~) flag = false; end end end See Also matlab.system.mixin.Nondirect | isInputDirectFeedthroughImpl | outputImpl | updateImpl More About 11-70 • “What Are Mixin Classes?” on page 11-77 • “Subclassing Multiple Classes” • “System Object Input Arguments and ~ in Code Examples” on page 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Enable For Each Subsystem Support Enable For Each Subsystem Support This example shows how to enable using a System object in a Simulink For Each subsystem. Include the supportsMultipleInstanceImpl method in your class definition file. This method applies only when the System object is used in Simulink via the MATLAB System block. Use the supportsMultipleInstanceImpl method and have it return true to indicate that the System object supports multiple calls in a Simulink For Each subsystem. methods (Access = protected) function flag = supportsMultipleInstanceImpl(obj) flag = true; end end View the method in the complete class definition file. classdef RandSeed < matlab.System % RANDSEED Random noise with seed for use in For Each subsystem properties (DiscreteState) count; end properties (Nontunable) seed = 20; end properties (Nontunable,Logical) useSeed = false; end methods (Access = protected) function y = stepImpl(obj,u1) % Initial use after reset/setup % and use the seed if (obj.useSeed && ~obj.count) rng(obj.seed); end obj.count = obj.count + 1; [m,n] = size(u1); % Uses default rng seed y = rand(m,n) + u1; www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-71 11 Define New System Objects end function setupImpl(obj) obj.count = 0; end function resetImpl(obj) obj.count = 0; end function flag = supportsMultipleInstanceImpl(obj) flag = obj.useSeed; end end end See Also matlab.System | supportsMultipleInstanceImpl 11-72 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Methods Timing Methods Timing In this section... “Setup Method Call Sequence” on page 11-73 “Step Method Call Sequence” on page 11-73 “Reset Method Call Sequence” on page 11-74 “Release Method Call Sequence” on page 11-75 Setup Method Call Sequence This hierarchy shows the actions performed when you call the setup method. Step Method Call Sequence This hierarchy shows the actions performed when you call the step method. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-73 11 Define New System Objects Reset Method Call Sequence This hierarchy shows the actions performed when you call the reset method. 11-74 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Methods Timing Release Method Call Sequence This hierarchy shows the actions performed when you call the release method. See Also releaseImpl | resetImpl | setupImpl | stepImpl Related Examples • “Release System Object Resources” on page 11-34 • “Reset Algorithm State” on page 11-21 • “Set Property Values at Construction Time” on page 11-19 • “Define Basic System Objects” on page 11-5 More About • “What Are System Object Methods?” • “The Step Method” • “Common Methods” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-75 11 Define New System Objects System Object Input Arguments and ~ in Code Examples All methods, except static methods, expect the System object handle as the first input argument. You can use any name for your System object handle. In many examples, instead of passing in the object handle, ~ is used to indicate that the object handle is not used in the function. Using ~ instead of an object handle prevents warnings about unused variables. 11-76 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان What Are Mixin Classes? What Are Mixin Classes? Mixin classes are partial classes that you can combine in various combinations to form desired behaviors using multiple inheritance. System objects are composed of a base class, matlab.System and may include one or more mixin classes. You specify the base class and mixin classes on the first line of your class definition file. The following mixin classes are available for use with System objects. • matlab.system.mixin.CustomIcon — Defines a block icon for System objects in the MATLAB System block • matlab.system.mixin.FiniteSource — Adds the isDone method to System objects that are sources • matlab.system.mixin.Nondirect — Allows the System object, when used in the MATLAB System block, to support nondirect feedthrough by making the runtime callback functions, output and update available • matlab.system.mixin.Propagates — Enables System objects to operate in the MATLAB System block using the interpreted execution www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 11-77 11 Define New System Objects Best Practices for Defining System Objects A System object is a specialized kind of MATLAB object that is optimized for iterative processing. Use System objects when you need to call the step method multiple times or process data in a loop. When defining your own System object, use the following suggestions to help your code run efficiently. • Define all one-time calculations in the setupImpl method and cache the results in a private property. Use the stepImpl method for repeated calculations. • For parameters that do not change, define them in a locked object as Nontunable properties. • If the number of System object inputs does not change, do not implement the getNumInputsImpl method. Also do not implement the getNumInputsImpl method when you explicitly list the inputs in the stepImpl method instead of using varargin. The same caveats apply to the outputs, getNumOutputsImpl and varargout. • Variables that do not need to retain their values between calls should have local scope for that method. • If properties are accessed more than once in the stepImpl method, or in the updateImpl and outputImpl methods, cache those properties as local variables inside the method. Iterative calculations using cached local variables run faster than calculations that must access the properties of an object. When the calculations for the method complete, you can save the local cached results back to the properties of that System object. Copy frequently used tunable properties into private properties. • For best practices for including System objects in code generation, see “System Objects in MATLAB Code Generation”. 11-78 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 HDL Code Generation • “What is HDL Code Generation?” on page 12-2 • “Blocks With HDL Support” on page 12-3 • “System Objects With HDL Support” on page 12-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12 HDL Code Generation What is HDL Code Generation? You can use MATLAB and Simulink for rapid prototyping of hardware designs. DSP System Toolbox blocks provide support for HDL code generation when used with HDL Coder™. Using DSP System Toolbox with Filter Design HDL Coder™, you can generate HDL code from digital filter designs and optimize filter implementation for hardware speed or area. The HDL Coder products generate target-independent synthesizable Verilog and VHDL code for FPGA programming or ASIC prototyping and design. 12-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Blocks With HDL Support Blocks With HDL Support Filtering • Biquad Filter • CIC Decimation • CIC Interpolation • DC Blocker • Discrete FIR Filter • FIR Decimation • FIR Interpolation • LMS Filter Math Functions • Complex to Magnitude-Angle HDL Optimized Signal Operations • Delay • Downsample • NCO • NCO HDL Optimized • Repeat • Upsample Signal Management Indexing • Multiport Selector • Selector • Variable Selector www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12-3 12 HDL Code Generation Signal Attributes • Convert 1-D to 2-D • Data Type Conversion • Frame Conversion Sinks These blocks can be used for simulation visibility in models that generate HDL code, but are not included in the hardware implementation. • Display • Matrix Viewer • To Workspace • Spectrum Analyzer • Time Scope • Vector Scope • Waterfall Statistics • Maximum • Minimum Transforms • FFT HDL Optimized • IFFT HDL Optimized 12-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان System Objects With HDL Support System Objects With HDL Support The coder supports the following DSP System Toolbox System objects for HDL code generation: • dsp.BiquadFilter • dsp.Delay • dsp.DCBlocker • dsp.FIRFilter • dsp.HDLComplexToMagnitudeAngle • dsp.HDLFFT, dsp.HDLIFFT • dsp.HDLNCO • dsp.Maximum, dsp.Minimum www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12-5 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 12-6 13 Links to Category Pages • “Signal Management Library” on page 13-2 • “Sinks Library” on page 13-3 • “Math Functions Library” on page 13-4 • “Filtering Library” on page 13-5 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13 Links to Category Pages Signal Management Library You can find the relevant blocks in the following pages: • “Buffers, Switches, and Counters” • “Signal Attributes and Indexing” • “Signal Operations” 13-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Sinks Library Sinks Library You can find the relevant blocks in the following pages: • “Signal Import and Export” • “Scopes and Data Logging” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13-3 13 Links to Category Pages Math Functions Library You can find the relevant blocks in the following pages: • “Array and Matrix Mathematics” • “Linear Algebra” 13-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filtering Library Filtering Library You can find the relevant blocks in the following pages: • “Filter Design” • “Single-Rate Filters” • “Multirate and Multistage Filters” • “Adaptive Filters” www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13-5 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 13-6 14 Designing Lowpass FIR Filters • “Lowpass FIR Filter Design” on page 14-2 • “Controlling Design Specifications in Lowpass FIR Design” on page 14-7 • “Designing Filters with Non-Equiripple Stopband” on page 14-13 • “Minimizing Lowpass FIR Filter Length” on page 14-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14 Designing Lowpass FIR Filters Lowpass FIR Filter Design This example shows how to design a lowpass FIR filter using fdesign . An ideal lowpass filter requires an infinite impulse response. Truncating or windowing the impulse response results in the so-called window method of FIR filter design. A Lowpass FIR Filter Design Using Various Windows FIR filters are widely used due to the powerful design algorithms that exist for them, their inherent stability when implemented in non-recursive form, the ease with which one can attain linear phase, their simple extensibility to multirate cases, and the ample hardware support that exists for them among other reasons. This example showcases functionality in the DSP System Toolbox™ for the design of low pass FIR filters with a variety of characteristics. Many of the concepts presented here can be extended to other responses such as highpass, bandpass, etc. Consider a simple design of a lowpass filter with a cutoff frequency of 0.4*pi radians per sample: Fc = 0.4; N = 100; Hf = fdesign.lowpass('N,Fc',N,Fc); We can design this lowpass filter using the window method. For example, we can use a Hamming window or a Dolph-Chebyshev window: Hd1 = design(Hf,'window','window',@hamming,'systemobject',true); Hd2 = design(Hf,'window','window',{@chebwin,50}, ... 'systemobject',true); hfvt = fvtool(Hd1,Hd2,'Color','White'); legend(hfvt,'Hamming window design', ... 'Dolph-Chebyshev window design') 14-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass FIR Filter Design The choice of filter was arbitrary. Since ideally the order should be infinite, in general, a larger order results in a better approximation to ideal at the expense of a more costly implementation. For instance, with a Dolph-Chebyshev window, we can decrease the transition region by increasing the filter order: Hf.FilterOrder = 200; Hd3 = design(Hf,'window','window',{@chebwin,50},... 'systemobject',true); hfvt2 = fvtool(Hd2,Hd3,'Color','White'); legend(hfvt2,'Dolph-Chebyshev window design. Order = 100',... 'Dolph-Chebyshev window design. Order = 200') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-3 14 Designing Lowpass FIR Filters Minimum Order Lowpass Filter Design In order to determine a suitable filter order, it is necessary to specify the amount of passband ripple and stopband attenuation that will be tolerated. It is also necessary to specify the width of the transition region around the ideal cutoff frequency. The latter is done by setting the passband edge frequency and the stopband edge frequency. The difference between the two determines the transition width. Fp = 0.38; Fst = 0.42; Ap = 0.06; Ast = 60; setspecs(Hf,'Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast); We can still use the window method, along with a Kaiser window, to design the low pass filter. Hd4 = design(Hf,'kaiserwin','systemobject',true); 14-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Lowpass FIR Filter Design measure(Hd4) ans = Sampling Frequency Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : N/A (normalized frequency) 0.38 0.39539 0.4 0.42 0.016058 dB 60.092 dB 0.04 One thing to note is that the transition width as specified is centered around the cutoff frequency of 0.4 pi. This will become the point at which the gain of the lowpass filter is half the passband gain (or the point at which the filter reaches 6 dB of attenuation). Optimal Minimum Order Designs The Kaiser window design is not an optimal design and as a result the filter order required to meet the specifications using this method is larger than it needs to be. Equiripple designs result in the lowpass filter with the smallest possible order to meet a set of specifications. Hd5 = design(Hf,'equiripple','systemobject',true); hfvt3 = fvtool(Hd4,Hd5,'Color','White'); legend(hfvt3,'Kaiser window design','Equiripple design') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-5 14 Designing Lowpass FIR Filters In this case, 146 coefficients are needed by the equiripple design while 183 are needed by the Kaiser window design. 14-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Controlling Design Specifications in Lowpass FIR Design Controlling Design Specifications in Lowpass FIR Design This example shows how to control the filter order, passband ripple, stopband attenuation, and transition region width of a lowpass FIR filter. Controlling the Filter Order and Passband Ripples and Stopband Attenuation When targeting custom hardware, it is common to find cases where the number of coefficients is constrained to a set number. In these cases, minimum order designs are not useful because there is no control over the resulting filter order. As an example, suppose that only 101 coefficients could be used and the passband ripple/stopband attenuation specifications need to be met. We can still use equiripple designs for these specifications. However, we lose control over the transition width which will increase. This is the price to pay for reducing the order while maintaining the passband ripple/ stopband attenuation specifications. Consider a simple design of a lowpass filter with a cutoff frequency of 0.4*pi radians per sample: Ap = 0.06; Ast = 60; Fp = 0.38; Fst = 0.42; Hf=fdesign.lowpass('Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast); Design an equiripple filter: Hd1 = design(Hf,'equiripple','systemobject',true); Set the number of coefficients to 101, which means setting the order to 100: N = 100; % order = 100 -> 101 coefficients Fc = 0.4; setspecs(Hf,'N,Fc,Ap,Ast',N,Fc,Ap,Ast); Design a second equiripple filter with the given constraint: Hd2 = design(Hf,'equiripple','systemobject',true); Measure the filter variables of the second equiripple filter, and compare the graphs of the first and second filters: measure(Hd2) hfvt = fvtool(Hd1,Hd2,'Color','White'); legend(hfvt,'Equiripple design, 146 coeffcients', ... www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-7 14 Designing Lowpass FIR Filters 'Equiripple design, 101 coefficients') Sampling Frequency Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : N/A (normalized frequency) 0.37316 0.39285 0.4 0.43134 0.06 dB 60 dB 0.058177 Notice that the transition has increased by almost 50%. This is not surprising given the almost 50% difference between 101 coefficients and 146 coefficients. Controlling the Transition Region Width Another option when the number of coefficients is set is to maintain the transition width at the expense of control over the passband ripple/stopband attenuation. 14-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Controlling Design Specifications in Lowpass FIR Design setspecs(Hf,'N,Fp,Fst',N,Fp,Fst); Hd3 = design(Hf,'equiripple','systemobject',true); measure(Hd3) hfvt2 = fvtool(Hd1,Hd3,'Color','White'); legend(hfvt2,'Equiripple design, 146 coefficients',... 'Equiripple design, 101 coefficients') Sampling Frequency Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width : : : : : : : : N/A (normalized frequency) 0.38 0.39407 0.4 0.42 0.1651 dB 40.4369 dB 0.04 Note that in this case, the differences between using 146 coefficients and using 101 coefficients is reflected in a larger passband ripple and a smaller stopband attenuation. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-9 14 Designing Lowpass FIR Filters It is possible to increase the attenuation in the stopband while keeping the same filter order and transition width by the use of weights. Weights are a way of specifying the relative importance of the passband ripple versus the stopband attenuation. By default, passband and stopband are equally weighted (a weight of one is assigned to each). If we increase the stopband weight, we can increase the stopband attenuation at the expense of increasing the stopband ripple as well. Hd4 = design(Hf,'equiripple','Wstop',5,'systemobject',true); measure(Hd4) hfvt3 = fvtool(Hd3,Hd4,'Color','White'); legend(hfvt3,'Passband weight = 1, Stopband weight = 1',... 'Passband weight = 1, Stopband weight = 5') Sampling Frequency Passband Edge 3-dB Point 6-dB Point Stopband Edge Passband Ripple Stopband Atten. Transition Width 14-10 : : : : : : : : N/A (normalized frequency) 0.38 0.39143 0.39722 0.42 0.34529 dB 48.0068 dB 0.04 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Controlling Design Specifications in Lowpass FIR Design Another possibility is to specify the exact stopband attenuation desired and lose control over the passband ripple. This is a powerful and very desirable specification. One has control over most parameters of interest. setspecs(Hf,'N,Fp,Fst,Ast',N,Fp,Fst,Ast); Hd5 = design(Hf,'equiripple','systemobject',true); hfvt4 = fvtool(Hd4,Hd5,'Color','White'); legend(hfvt4,'Equiripple design using weights',... 'Equiripple design constraining the stopband') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-11 14 Designing Lowpass FIR Filters 14-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Designing Filters with Non-Equiripple Stopband Designing Filters with Non-Equiripple Stopband This example shows how to design lowpass filters with stopbands that are not equiripple. Optimal Non-Equiripple Lowpass Filters To start, set up the filter parameters and use fdesign to create a constructor for designing the filter. N = 100; Fp = 0.38; Fst = 0.42; Hf = fdesign.lowpass('N,Fp,Fst',N,Fp,Fst); Equiripple designs achieve optimality by distributing the deviation from the ideal response uniformly. This has the advantage of minimizing the maximum deviation (ripple). However, the overall deviation, measured in terms of its energy tends to be large. This may not always be desirable. When low pass filtering a signal, this implies that remnant energy of the signal in the stopband may be relatively large. When this is a concern, least-squares methods provide optimal designs that minimize the energy in the stopband. Hd1 = design(Hf,'equiripple','systemobject',true); Hd2 = design(Hf,'firls','systemobject',true); hfvt = fvtool(Hd1,Hd2,'Color','White'); legend(hfvt,'Equiripple design','Least-squares design') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-13 14 Designing Lowpass FIR Filters Notice how the attenuation in the stopband increases with frequency for the leastsquares designs while it remains constant for the equiripple design. The increased attenuation in the least-squares case minimizes the energy in that band of the signal to be filtered. Equiripple Designs with Increasing Stopband Attenuation An often undesirable effect of least-squares designs is that the ripple in the passband region close to the passband edge tends to be large. For low pass filters in general, it is desirable that passband frequencies of a signal to be filtered are affected as little as possible. To this extent, an equiripple passband is generally preferable. If it is still desirable to have an increasing attenuation in the stopband, we can use design options for equiripple designs to achieve this. Hd3 = design(Hf,'equiripple','StopbandShape','1/f',... 'StopbandDecay',4,'systemobject',true); hfvt2 = fvtool(Hd2,Hd3,'Color','White'); 14-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Designing Filters with Non-Equiripple Stopband legend(hfvt2,'Least-squares design',... 'Equiripple design with stopband decaying as (1/f)^4') Notice that the stopbands are quite similar. However the equiripple design has a significantly smaller passband ripple, mls = measure(Hd2); meq = measure(Hd3); mls.Apass meq.Apass ans = 0.3504 ans = www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-15 14 Designing Lowpass FIR Filters 0.1867 Filters with a stopband that decays as (1/f)^M will decay at 6M dB per octave. Another way of shaping the stopband is using a linear decay. For example given an approximate attenuation of 38 dB at 0.4*pi, if an attenuation of 70 dB is desired at pi, and a linear decay is to be used, the slope of the line is given by (70-38)/(1-0.4) = 53.333. Such a design can be achieved from: Hd4 = design(Hf,'equiripple','StopbandShape','linear',... 'StopbandDecay',53.333,'systemobject',true); hfvt3 = fvtool(Hd3,Hd4,'Color','White'); legend(hfvt3,'Equiripple design with stopband decaying as (1/f)^4',... 'Equiripple design with stopband decaying linearly and a slope of 53.333') Yet another possibility is to use an arbitrary magnitude specification and select two bands (one for the passband and one for the stopband). Then, by using weights for the second band, it is possible to increase the attenuation throughout the band. 14-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Designing Filters with Non-Equiripple Stopband N = 100; B = 2; % number of bands F = [0 .38 .42:.02:1]; A = [1 1 zeros(1,length(F)-2)]; W = linspace(1,100,length(F)-2); Harb = fdesign.arbmag('N,B,F,A',N,B,F(1:2),A(1:2),F(3:end),... A(3:end)); Ha = design(Harb,'equiripple','B2Weights',W,... 'systemobject',true); fvtool(Ha,'Color','White') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-17 14 Designing Lowpass FIR Filters Minimizing Lowpass FIR Filter Length This example shows how to minimize the number coefficients, by designing minimumphase or minimum-order filters. Minimum-Phase Lowpass Filter Design To start, set up the filter parameters and use fdesign to create a constructor for designing the filter. N = 100; Fp = 0.38; Fst = 0.42; Ap = 0.06; Ast = 60; Hf = fdesign.lowpass('Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast); So far, we have only considered linear-phase designs. Linear phase is desirable in many applications. Nevertheless, if linear phase is not a requirement, minimum-phase designs can provide significant improvements over linear phase counterparts. For instance, returning to the minimum order case, a minimum-phase/minimum-order design for the same specifications can be computed with: Hd1 = design(Hf,'equiripple','systemobject',true); Hd2 = design(Hf,'equiripple','minphase',true,... 'systemobject',true); hfvt = fvtool(Hd1,Hd2,'Color','White'); legend(hfvt,'Linear-phase equiripple design',... 'Minimum-phase equiripple design') 14-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Minimizing Lowpass FIR Filter Length Notice that the number of coefficients has been reduced from 146 to 117. As a second example, consider the design with a stopband decaying in linear fashion. Notice the increased stopband attenuation. The passband ripple is also significantly smaller. setspecs(Hf,'N,Fp,Fst',N,Fp,Fst); Hd3 = design(Hf,'equiripple','StopbandShape','linear',... 'StopbandDecay',53.333,'systemobject',true); setspecs(Hf,'Fp,Fst,Ap,Ast',Fp,Fst,Ap,Ast); Hd4 = design(Hf,'equiripple','StopbandShape','linear',... 'StopbandDecay',53.333,'minphase',true,'systemobject',true); hfvt2 = fvtool(Hd3,Hd4,'Color','White'); legend(hfvt2,'Linear-phase equiripple design with linearly decaying stopband',... 'Minimum-phase equiripple design with linearly decaying stopband') www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-19 14 Designing Lowpass FIR Filters Minimum-Order Lowpass Filter Design Using Multistage Techniques A different approach to minimizing the number of coefficients that does not involve minimum-phase designs is to use multistage techniques. Here we show an interpolated FIR (IFIR) approach. Hd5 = ifir(Hf); hfvt3 = fvtool(Hd1,Hd5,'Color','White'); legend(hfvt3,'Linear-phase equirriple design',... 'Linear-phase IFIR design') 14-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Minimizing Lowpass FIR Filter Length The number of nonzero coefficients required in the IFIR case is 111. Less than both the equiripple linear-phase and minimum-phase designs. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-21 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 14-22 15 FDATool: A Filter Design and Analysis GUI • “Overview” on page 15-2 • “Using FDATool” on page 15-6 • “Importing a Filter Design” on page 15-33 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15 FDATool: A Filter Design and Analysis GUI Overview In this section... “FDATool” on page 15-2 “Filter Design Methods” on page 15-2 “Using the Filter Design and Analysis Tool” on page 15-3 “Analyzing Filter Responses” on page 15-4 “Filter Design and Analysis Tool Panels” on page 15-4 “Getting Help” on page 15-5 FDATool The Filter Design and Analysis Tool (FDATool) is a user interface for designing and analyzing filters quickly. FDATool enables you to design digital FIR or IIR filters by setting filter specifications, by importing filters from your MATLAB workspace, or by adding, moving or deleting poles and zeros. FDATool also provides tools for analyzing filters, such as magnitude and phase response and pole-zero plots. Filter Design Methods FDATool gives you access to the following Signal Processing Toolbox filter design methods. 15-2 Design Method Function Butterworth butter Chebyshev Type I cheby1 Chebyshev Type II cheby2 Elliptic ellip Maximally Flat maxflat Equiripple firpm Least-squares firls Constrained least-squares fircls Complex equiripple cfirpm www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Overview Design Method Function Window fir1 When using the window method in FDATool, all Signal Processing Toolbox window functions are available, and you can specify a user-defined window by entering its function name and input parameter. Advanced Filter Design Methods The following advanced filter design methods are available if you have DSP System Toolbox software. Design Method Function Constrained equiripple FIR firceqrip Constrained-band equiripple FIR fircband Generalized remez FIR firgr Equiripple halfband FIR firhalfband Least P-norm optimal FIR firlpnorm Equiripple Nyquist FIR firnyquist Interpolated FIR ifir IIR comb notching or peaking iircomb Allpass filter (given group delay) iirgrpdelay Least P-norm optimal IIR iirlpnorm Constrained least P-norm IIR iirlpnormc Second-order IIR notch iirnotch Second-order IIR peaking (resonator) iirpeak Using the Filter Design and Analysis Tool There are different ways that you can design filters using the Filter Design and Analysis Tool. For example: • You can first choose a response type, such as bandpass, and then choose from the available FIR or IIR filter design methods. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-3 15 FDATool: A Filter Design and Analysis GUI • You can specify the filter by its type alone, along with certain frequency- or timedomain specifications such as passband frequencies and stopband frequencies. The filter you design is then computed using the default filter design method and filter order. Analyzing Filter Responses Once you have designed your filter, you can display the filter coefficients and detailed filter information, export the coefficients to the MATLAB workspace, and create a C header file containing the coefficients, and analyze different filter responses in FDATool or in a separate Filter Visualization Tool (fvtool). The following filter responses are available: • Magnitude response (freqz) • Phase response (phasez) • Group delay (grpdelay) • Phase delay (phasedelay) • Impulse response (impz) • Step response (stepz) • Pole-zero plots (zplane) • Zero-phase response (zerophase) Filter Design and Analysis Tool Panels The Filter Design and Analysis Tool has sidebar buttons that display particular panels in the lower half of the tool. The panels are • Design Filter. See “Choosing a Filter Design Method” on page 15-7 for more information. You use this panel to • Design filters from scratch. • Modify existing filters designed in FDATool. • Analyze filters. • Import filter. You use this panel to • Import previously saved filters or filter coefficients that you have stored in the MATLAB workspace. 15-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Overview • Analyze imported filters. • Pole/Zero Editor. See “Editing the Filter Using the Pole/Zero Editor” on page 15-17. You use this panel to add, delete, and move poles and zeros in your filter design. If you also have DSP System Toolbox product installed, additional panels are available: • Set quantization parameters — Use this panel to quantize double-precision filters that you design in FDATool, quantize double-precision filters that you import into FDATool, and analyze quantized filters. • Transform filter — Use this panel to change a filter from one response type to another. • Multirate filter design — Use this panel to create a multirate filter from your existing FIR design, create CIC filters, and linear and hold interpolators. If you have Simulink installed, this panel is available: • Realize Model — Use this panel to create a Simulink block containing the filter structure. Getting Help At any time, you can right-click or click the What's this? button, , to get information on the different parts of the tool. You can also use the Help menu to see complete Help information. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-5 15 FDATool: A Filter Design and Analysis GUI Using FDATool To open FDATool, type fdatool at the MATLAB command prompt. The Filter Design and Analysis Tool opens with the Design Filter panel displayed. Note that when you open FDATool, Design Filter is not enabled. You must make a change to the default filter design in order to enable Design Filter. This is true each time you want to change the filter design. Changes to radio button items or drop down menu items such as those under Response Type or Filter Order enable Design Filter immediately. Changes to specifications in text boxes such as Fs, Fpass, and Fstop require you to click outside the text box to enable Design Filter. Choosing a Response Type You can choose from several response types: 15-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool • Lowpass • Raised cosine • Highpass • Bandpass • Bandstop • Differentiator • Multiband • Hilbert transformer • Arbitrary magnitude Additional response types are available if you have DSP System Toolbox software installed. To design a bandpass filter, select the radio button next to Bandpass in the Response Type region of the GUI. Note: Not all filter design methods are available for all response types. Once you choose your response type, this may restrict the filter design methods available to you. Filter design methods that are not available for a selected response type are removed from the Design Method region of the GUI. Choosing a Filter Design Method You can use the default filter design method for the response type that you've selected, or you can select a filter design method from the available FIR and IIR methods listed in the GUI. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-7 15 FDATool: A Filter Design and Analysis GUI To select the Remez algorithm to compute FIR filter coefficients, select the FIR radio button and choose Equiripple from the list of methods. Setting the Filter Design Specifications • “Viewing Filter Specifications” on page 15-8 • “Filter Order” on page 15-9 • “Options” on page 15-9 • “Bandpass Filter Frequency Specifications” on page 15-10 • “Bandpass Filter Magnitude Specifications” on page 15-11 Viewing Filter Specifications The filter design specifications that you can set vary according to response type and design method. The display region illustrates filter specifications when you select Analysis > Filter Specifications or when you click the Filter Specifications toolbar button. You can also view the filter specifications on the Magnitude plot of a designed filter by selecting View > Specification Mask. 15-8 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool Filter Order You have two mutually exclusive options for determining the filter order when you design an equiripple filter: • Specify order: You enter the filter order in a text box. • Minimum order: The filter design method determines the minimum order filter. Select the Minimum order radio button for this example. Note that filter order specification options depend on the filter design method you choose. Some filter methods may not have both options available. Options The available options depend on the selected filter design method. Only the FIR Equiripple and FIR Window design methods have settable options. For FIR Equiripple, the option is a Density Factor. See firpm for more information. For FIR Window the options are Scale Passband, Window selection, and for the following windows, a settable parameter: Window Parameter Chebyshev (chebwin) Sidelobe attenuation Gaussian (gausswin) Alpha Kaiser (kaiser) Beta Taylor (taylorwin) Nbar and Sidelobe level Tukey (tukeywin) Alpha User Defined Function Name, Parameter You can view the window in the Window Visualization Tool (wvtool) by clicking the View button. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-9 15 FDATool: A Filter Design and Analysis GUI For this example, set the Density factor to 16. Bandpass Filter Frequency Specifications For a bandpass filter, you can set • Units of frequency: • Hz • kHz • MHz • Normalized (0 to 1) • Sampling frequency • Passband frequencies • Stopband frequencies You specify the passband with two frequencies. The first frequency determines the lower edge of the passband, and the second frequency determines the upper edge of the passband. Similarly, you specify the stopband with two frequencies. The first frequency determines the upper edge of the first stopband, and the second frequency determines the lower edge of the second stopband. For this example: • Keep the units in Hz (default). • Set the sampling frequency (Fs) to 2000 Hz. • Set the end of the first stopband (Fstop1) to 200 Hz. • Set the beginning of the passband (Fpass1) to 300 Hz. • Set the end of the passband (Fpass2) to 700 Hz. 15-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool • Set the beginning of the second stopband (Fstop2) to 800 Hz. Bandpass Filter Magnitude Specifications For a bandpass filter, you can specify the following magnitude response characteristics: • Units for the magnitude response (dB or linear) • Passband ripple • Stopband attenuation For this example: • Keep Units in dB (default). • Set the passband ripple (Apass) to 0.1 dB. • Set the stopband attenuation for both stopbands (Astop1, Astop2) to 75 dB. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-11 15 FDATool: A Filter Design and Analysis GUI Computing the Filter Coefficients Now that you've specified the filter design, click the Design Filter button to compute the filter coefficients. Notice that the Design Filter button is disabled once you've computed the coefficients for your filter design. This button is enabled again once you make any changes to the filter specifications. Analyzing the Filter • “Displaying Filter Responses” on page 15-12 • “Using Data Tips” on page 15-14 • “Drawing Spectral Masks” on page 15-14 • “Changing the Sampling Frequency” on page 15-16 • “Displaying the Response in FVTool” on page 15-16 Displaying Filter Responses You can view the following filter response characteristics in the display region or in a separate window. • Magnitude response • Phase response • Magnitude and Phase responses • Group delay response • Phase delay response • Impulse response • Step response • Pole-zero plot • Zero-phase response — available from the y-axis context menu in a Magnitude or Magnitude and Phase response plot. If you have DSP System Toolbox product installed, two other analyses are available: magnitude response estimate and round-off noise power. These two analyses are the only ones that use filter internals. 15-12 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool For descriptions of the above responses and their associated toolbar buttons and other FDATool toolbar buttons, see fvtool. You can display two responses in the same plot by selecting Analysis > Overlay Analysis and selecting an available response. A second y-axis is added to the right side of the response plot. (Note that not all responses can be overlaid on each other.) You can also display the filter coefficients and detailed filter information in this region. For all the analysis methods, except zero-phase response, you can access them from the Analysis menu, the Analysis Parameters dialog box from the context menu, or by using the toolbar buttons. For zero-phase, right-click the y-axis of the plot and select Zerophase from the context menu. For example, to look at the filter's magnitude response, select the Magnitude Response button on the toolbar. You can also overlay the filter specifications on the Magnitude plot by selecting View > Specification Mask. Note: You can use specification masks in FVTool only if FVTool was launched from FDATool. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-13 15 FDATool: A Filter Design and Analysis GUI Using Data Tips You can click the response to add plot data tips that display information about particular points on the response. For information on using data tips, see “Display Data Values Interactively” in the MATLAB documentation. Drawing Spectral Masks To add spectral masks or rejection area lines to your magnitude plot, click View > Userdefined Spectral Mask. 15-14 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool The mask is defined by a frequency vector and a magnitude vector. These vectors must be the same length. • Enable Mask — Select to turn on the mask display. • Normalized Frequency — Select to normalize the frequency between 0 and 1 across the displayed frequency range. • Frequency Vector — Enter a vector of x-axis frequency values. • Magnitude Units — Select the desired magnitude units. These units should match the units used in the magnitude plot. • Magnitude Vector — Enter a vector of y-axis magnitude values. The magnitude response below shows a spectral mask. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-15 15 FDATool: A Filter Design and Analysis GUI Changing the Sampling Frequency To change the sampling frequency of your filter, right-click any filter response plot and select Sampling Frequency from the context menu. To change the filter name, type the new name in Filter name. (In fvtool, if you have multiple filters, select the desired filter and then enter the new name.) To change the sampling frequency, select the desired unit from Units and enter the sampling frequency in Fs. (For each filter in fvtool, you can specify a different sampling frequency or you can apply the sampling frequency to all filters.) To save the displayed parameters as the default values to use when FDATool or FVTool is opened, click Save as Default. To restore the default values, click Restore Original Defaults. Displaying the Response in FVTool To display the filter response characteristics in a separate window, select View > Filter Visualization Tool (available if any analysis, except the filter specifications, is in the display region) or click the Full View Analysis button: This launches the Filter Visualization Tool (fvtool). Note: If Filter Specifications are shown in the display region, clicking the Full View Analysis toolbar button launches a “ MATLAB figure window” instead of FVTool. The 15-16 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool associated menu item is Print to figure, which is enabled only if the filter specifications are displayed. You can use this tool to annotate your design, view other filter characteristics, and print your filter response. You can link FDATool and FVTool so that changes made in FDATool are immediately reflected in FVTool. See fvtool for more information. Editing the Filter Using the Pole/Zero Editor • “Displaying the Pole-Zero Plot” on page 15-17 • “Changing the Pole-Zero Plot” on page 15-18 Displaying the Pole-Zero Plot You can edit a designed or imported filter's coefficients by moving, deleting, or adding poles and/or zeros using the Pole/Zero Editor panel. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-17 15 FDATool: A Filter Design and Analysis GUI Note: You cannot generate MATLAB code (File > Generate MATLAB code) if your filter was designed or edited with the Pole/Zero Editor. You cannot move quantized poles and zeros. You can only move the reference poles and zeros. Click the Pole/Zero Editor button in the sidebar or select Edit > Pole/Zero Editor to display this panel. Poles are shown using x symbols and zeros are shown using o symbols. Changing the Pole-Zero Plot Plot mode buttons are located to the left of the pole/zero plot. Select one of the buttons to change the mode of the pole/zero plot. The Pole/Zero Editor has these buttons from left to right: move pole, add pole, add zero, and delete pole or zero. 15-18 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool The following plot parameters and controls are located to the left of the pole/zero plot and below the plot mode buttons. • Filter gain — factor to compensate for the filter's pole(s) and zero(s) gains • Coordinates — units (Polar or Rectangular) of the selected pole or zero • Magnitude — if polar coordinates is selected, magnitude of the selected pole or zero • Angle — if polar coordinates is selected, angle of selected pole(s) or zero(s) • Real — if rectangular coordinates is selected, real component of selected pole(s) or zero(s) • Imaginary — if rectangular coordinates is selected, imaginary component of selected pole or zero • Section — for multisection filters, number of the current section • Conjugate — creates a corresponding conjugate pole or zero or automatically selects the conjugate pole or zero if it already exists. • Auto update — immediately updates the displayed magnitude response when poles or zeros are added, moved, or deleted. The Edit > Pole/Zero Editor has items for selecting multiple poles/zeros, for inverting and mirroring poles/zeros, and for deleting, scaling and rotating poles/zeros. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-19 15 FDATool: A Filter Design and Analysis GUI Moving one of the zeros on the vertical axis produces the following result: 15-20 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool • The selected zero pair is shown in green. • When you select one of the zeros from a conjugate pair, the Conjugate check box and the conjugate are automatically selected. • The Magnitude Response plot updates immediately because Auto update is active. Converting the Filter Structure • “Converting to a New Structure” on page 15-21 • “Converting to Second-Order Sections” on page 15-23 Converting to a New Structure You can use Edit > Convert Structure to convert the current filter to a new structure. All filters can be converted to the following representations: • Direct-form I • Direct-form II • Direct-form I transposed www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-21 15 FDATool: A Filter Design and Analysis GUI • Direct-form II transposed • Lattice ARMA Note: If you have DSP System Toolbox product installed, you will see additional structures in the Convert structure dialog box. In addition, the following conversions are available for particular classes of filters: • Minimum phase FIR filters can be converted to Lattice minimum phase • Maximum phase FIR filters can be converted to Lattice maximum phase • Allpass filters can be converted to Lattice allpass • IIR filters can be converted to Lattice ARMA Note: Converting from one filter structure to another may produce a result with different characteristics than the original. This is due to the computer's finite-precision arithmetic and the variations in the conversion's roundoff computations. For example: • Select Edit > Convert Structure to open the Convert structure dialog box. • Select Direct-form I in the list of filter structures. 15-22 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool Converting to Second-Order Sections You can use Edit > Convert to Second-Order Sections to store the converted filter structure as a collection of second-order sections rather than as a monolithic higher-order structure. Note: The following options are also used for Edit > Reorder and Scale Scale SecondOrder Sections, which you use to modify an SOS filter structure. The following Scale options are available when converting a direct-form II structure only: • None (default) • L-2 (L2 norm) • L-infinity (L∞ norm) The Direction (Up or Down) determines the ordering of the second-order sections. The optimal ordering changes depending on the Scale option selected. For example: • Select Edit > Convert to Second-Order Sections to open the Convert to SOS dialog box. • Select L-infinity from the Scale menu for L∞ norm scaling. • Leave Up as the Direction option. Note: To convert from second-order sections back to a single section, use Edit > Convert to Single Section. Exporting a Filter Design • “Exporting Coefficients or Objects to the Workspace” on page 15-24 • “Exporting Coefficients to an ASCII File” on page 15-25 • “Exporting Coefficients or Objects to a MAT-File” on page 15-25 • “Exporting to SPTool” on page 15-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-23 15 FDATool: A Filter Design and Analysis GUI • “Exporting to a Simulink Model” on page 15-26 • “Other Ways to Export a Filter” on page 15-27 Exporting Coefficients or Objects to the Workspace You can save the filter either as filter coefficients variables or as a dfilt or mfilt filter object variable. (Note that you must have DSP System Toolbox product installed to save as an mfilt.) To save the filter to the MATLAB workspace: 1 Select File > Export. The Export dialog box appears. 2 Select Workspace from the Export To menu. 3 Select Coefficients from the Export As menu to save the filter coefficients or select Objects to save the filter in a filter object. 4 For coefficients, assign variable names using the Numerator (for FIR filters) or Numerator and Denominator (for IIR filters), or SOS Matrix and Scale Values (for IIR filters in second-order section form) text boxes in the Variable Names region. For objects, assign the variable name in the Discrete Filter (or Quantized Filter) text box. If you have variables with the same names in your workspace and you want to overwrite them, select the Overwrite Variables check box. 5 15-24 Click the Export button. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool Exporting Coefficients to an ASCII File To save filter coefficients to a text file, 1 Select File > Export. The Export dialog box appears. 2 Select Coefficients File (ASCII) from the Export To menu. 3 Click the Export button. The Export Filter Coefficients to .FCF File dialog box appears. 4 Choose or enter a filename and click the Save button. The coefficients are saved in the text file that you specified, and the MATLAB Editor opens to display the file. The text file also contains comments with the MATLAB version number, the Signal Processing Toolbox version number, and filter information. Exporting Coefficients or Objects to a MAT-File To save filter coefficients or a filter object as variables in a MAT-file: 1 Select File > Export. The Export dialog box appears. 2 Select MAT-file from the Export To menu. 3 Select Coefficients from the Export As menu to save the filter coefficients or select Objects to save the filter in a filter object. 4 For coefficients, assign variable names using the Numerator (for FIR filters) or Numerator and Denominator (for IIR filters), or SOS Matrix and Scale Values (for IIR filters in second-order section form) text boxes in the Variable Names region. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-25 15 FDATool: A Filter Design and Analysis GUI For objects, assign the variable name in the Discrete Filter (or Quantized Filter) text box. If you have variables with the same names in your workspace and you want to overwrite them, select the Overwrite Variables check box. 5 Click the Export button. The Export to a MAT-File dialog box appears. 6 Choose or enter a filename and click the Save button. Exporting to SPTool You may want to use your designed filter in SPTool to do signal processing and analysis. 1 Select File > Export. The Export dialog box appears. 2 Select SPTool from the Export To menu. 3 Assign the variable name in the Discrete Filter (or Quantized Filter) text box. If you have variables with the same names in your workspace and you want to overwrite them, select the Overwrite Variables check box. 4 Click the Export button. SPTool opens and the current FDATool filter appears in the Filter area list as the specified variable name followed by (Imported). Note: If you are using the DSP System Toolbox software and export a quantized filter, only the values of its quantized coefficients are exported. The reference coefficients are not exported. SPTool does not restrict the coefficient values, so if you edit them in SPTool by moving poles or zeros, the filter will no longer be in quantized form. Exporting to a Simulink Model If you have the Simulink product installed, you can export a Simulink block of your filter design and insert it into a new or existing Simulink model. You can export a filter designed using any filter design method available in FDATool. Note: If you have the DSP System Toolbox and Fixed-Point Designer installed, you can export a CIC filter to a Simulink model. 15-26 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool 1 After designing your filter, click the Realize Model sidebar button or select File > Export to Simulink Model. The Realize Model panel is displayed. 2 Specify the name to use for your block in Block name. 3 To insert the block into the current (most recently selected) Simulink model, set the Destination to Current. To inset the block into a new model, select New. To insert the block into a user-defined subsystem, select User defined. 4 If you want to overwrite a block previously created from this panel, check Overwrite generated `Filter' block. 5 6 Set the Input processing parameter to specify whether the generated filter performs sample- or frame-based processing on the input. Depending on the type of filter you design, one or both of the following options may be available: • Columns as channels (frame based) — When you select this option, the block treats each column of the input as a separate channel. • Elements as channels (sample based) — When you select this option, the block treats each element of the input as a separate channel. 7 Click the Realize Model button to create the filter block. When the Build model using basic elements check box is selected, FDATool implements the filter as a subsystem block using Sum, Gain, and Delay blocks. If you double-click the Simulink Filter block, the filter structure is displayed. Other Ways to Export a Filter You can also send your filter to a C header file or generate MATLAB code to construct your filter from the command line. For detailed instructions, see the following sections: www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-27 15 FDATool: A Filter Design and Analysis GUI • “Generating a C Header File” on page 15-28 • “Generating MATLAB Code” on page 15-29 Generating a C Header File You may want to include filter information in an external C program. To create a C header file with variables that contain filter parameter data, follow this procedure: 15-28 1 Select Targets > Generate C Header. The Generate C Header dialog box appears. 2 Enter the variable names to be used in the C header file. The particular filter structure determines the variables that are created in the file Filter Structure Variable Parameter Direct-form I Direct-form II Direct-form I transposed Direct-form II transposed Numerator, Numerator length*, Denominator, Denominator length*, and Number of sections (inactive if filter has only one section) Lattice ARMA Lattice coeffs, Lattice coeffs length*, Ladder coeffs, Ladder coeffs length*, Number of sections (inactive if filter has only one section) www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool Filter Structure Variable Parameter Lattice MA Lattice coeffs, Lattice coeffs length*, and Number of sections (inactive if filter has only one section) Direct-form FIR Direct- Numerator, Numerator length*, and Number of sections form FIR transposed (inactive if filter has only one section) *length variables contain the total number of coefficients of that type. Note: Variable names cannot be C language reserved words, such as “for.” 3 Select Export Suggested to use the suggested data type or select Export As and select the desired data type from the pull-down. Note: If you do not have DSP System Toolbox software installed, selecting any data type other than double-precision floating point results in a filter that does not exactly match the one you designed in the FDATool. This is due to rounding and truncating differences. 4 Click OK to save the file and close the dialog box or click Apply to save the file, but leave the dialog box open for additional C header file definitions. Generating MATLAB Code You can generate MATLAB code that constructs the filter you designed in FDATool from the command line. Select File > Generate MATLAB Code > Filter Design Function and specify the filename in the Generate MATLAB code dialog box. Note: You cannot generate MATLAB code (File > Generate MATLAB Code > Filter Design Function) if your filter was designed or edited with the Pole/Zero Editor. The following is generated MATLAB code for the default lowpass filter in FDATool. function Hd = ExFilter %EXFILTER Returns a discrete-time filter object. % % MATLAB Code % Generated by MATLAB(R) 7.11 and the Signal Processing Toolbox 6.14. % % Generated on: 17-Feb-2010 14:15:37 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-29 15 FDATool: A Filter Design and Analysis GUI % % Equiripple Lowpass filter designed using the FIRPM function. % All frequency values are in Hz. Fs = 48000; % Sampling Frequency Fpass Fstop Dpass Dstop dens = = = = = 9600; 12000; 0.057501127785; 0.0001; 20; % % % % % Passband Frequency Stopband Frequency Passband Ripple Stopband Attenuation Density Factor % Calculate the order from the parameters using FIRPMORD. [N, Fo, Ao, W] = firpmord([Fpass, Fstop]/(Fs/2), [1 0], [Dpass, Dstop]); % Calculate the coefficients using the FIRPM function. b = firpm(N, Fo, Ao, W, {dens}); Hd = dfilt.dffir(b); % [EOF] Managing Filters in the Current Session You can store filters designed in the current FDATool session for cascading together, exporting to FVTool or for recalling later in the same or future FDATool sessions. You store and access saved filters with the Store filter and Filter Manager buttons, respectively, in the Current Filter Information pane. Store Filter — Displays the Store Filter dialog box in which you specify the filter name to use when storing the filter in the Filter Manager. The default name is the type of the filter. 15-30 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Using FDATool Filter Manager — Opens the Filter Manager. The current filter is listed below the listbox. To change the current filter, highlight the desired filter. If you select Edit current filter, FDATool displays the currently selected filter specifications. If you make any changes to the specifications, the stored filter is updated immediately. To cascade two or more filters, highlight the desired filters and press Cascade. A new cascaded filter is added to the Filter Manager. To change the name of a stored filter, press Rename. The Rename filter dialog box is displayed. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-31 15 FDATool: A Filter Design and Analysis GUI To remove a stored filter from the Filter Manager, press Delete. To export one or more filters to FVTool, highlight the filter(s) and press FVTool. Saving and Opening Filter Design Sessions You can save your filter design session as a MAT-file and return to the same session another time. Select the Save session button to save your session as a MAT-file. The first time you save a session, a Save Filter Design File browser opens, prompting you for a session name. For example, save this design session as TestFilter.fda in your current working directory by typing TestFilter in the File name field. The .fda extension is added automatically to all filter design sessions you save. Note: You can also use the File > Save session and File > Save session as to save a session. You can load existing sessions into the Filter Design and Analysis Tool by selecting the Open session button, or File > Open session . A Load Filter Design File browser opens that allows you to select from your previously saved filter design sessions. 15-32 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Importing a Filter Design Importing a Filter Design In this section... “Import Filter Panel” on page 15-33 “Filter Structures” on page 15-34 Import Filter Panel The Import Filter panel allows you to import a filter. You can access this region by clicking the Import Filter button in the sidebar. The imported filter can be in any of the representations listed in the Filter Structure pull-down menu. You can import a filter as second-order sections by selecting the check box. Specify the filter coefficients in Numerator and Denominator, either by entering them explicitly or by referring to variables in the MATLAB workspace. Select the frequency units from the following options in the Units menu, and for any frequency unit other than Normalized, specify the value or MATLAB workspace variable of the sampling frequency in the Fs field. To import the filter, click the Import Filter button. The display region is automatically updated when the new filter has been imported. You can edit the imported filter using the Pole/Zero Editor panel. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-33 15 FDATool: A Filter Design and Analysis GUI Filter Structures The available filter structures are: • Direct Form, which includes direct-form I, direct-form II, direct-form I transposed, direct-form II transposed, and direct-form FIR • Lattice, which includes lattice allpass, lattice MA min phase, lattice MA max phase, and lattice ARMA • Discrete–time Filter (dfilt object) The structure that you choose determines the type of coefficients that you need to specify in the text fields to the right. Direct-form For direct-form I, direct-form II, direct-form I transposed, and direct-form II transposed, specify the filter by its transfer function representation H ( z) = b(1) + b(2) z-1 + b(3) z -2 + º b( m + 1) z- m a(1) + a(2) z -1 + a(3) Z -3 + º a(n + 1) z -n • The Numerator field specifies a variable name or value for the numerator coefficient vector b, which contains m+1 coefficients in descending powers of z. • The Denominator field specifies a variable name or value for the denominator coefficient vector a, which contains n+1 coefficients in descending powers of z. For FIR filters, the Denominator is 1. Filters in transfer function form can be produced by all of the Signal Processing Toolbox filter design functions (such as fir1, fir2, firpm, butter, yulewalk). See “Transfer Function” for more information. Importing as second-order sections For all direct-form structures, except direct-form FIR, you can import the filter in its second-order section representation: L H ( z) = G 15-34 b0k + b1k z -1 + b2k z-2 -1 -2 k=1 a0 k + a1k z + a2k z ’ www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Importing a Filter Design The Gain field specifies a variable name or a value for the gain G, and the SOS Matrix field specifies a variable name or a value for the L-by-6 SOS matrix Ê b01 Á Á b02 SOS = Á · Á Á · Áb Ë 0L b11 b12 · · b1L b21 b22 · · b2L 1 a11 1 a12 · · · · 1 a1L a22 ˆ ˜ a22 ˜ · ˜ ˜ · ˜ a2 L ˜¯ whose rows contain the numerator and denominator coefficients bik and aik of the secondorder sections of H(z). Filters in second-order section form can be produced by functions such as tf2sos, zp2sos, ss2sos, and sosfilt. See “Second-Order Sections (SOS)” for more information. Lattice For lattice allpass, lattice minimum and maximum phase, and lattice ARMA filters, specify the filter by its lattice representation: • For lattice allpass, the Lattice coeff field specifies the lattice (reflection) coefficients, k(1) to k(N), where N is the filter order. • For lattice MA (minimum or maximum phase), the Lattice coeff field specifies the lattice (reflection) coefficients, k(1) to k(N), where N is the filter order. • For lattice ARMA, the Lattice coeff field specifies the lattice (reflection) coefficients, k(1) to k(N), and the Ladder coeff field specifies the ladder coefficients, v(1) to v(N+1), where N is the filter order. Filters in lattice form can be produced by tf2latc. See “Lattice Structure” for more information. Discrete-time Filter (dfilt object) For Discrete-time filter, specify the name of the dfilt object. See dfilt for more information. Multirate Filter (mfilt object) For Multirate filter, specify the name of the mfilt object. See mfilt in the DSP System Toolbox product for more information. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-35 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 15-36 16 Designing a Filter in the Filterbuilder GUI • “Filterbuilder Design Process” on page 16-2 • “Designing a FIR Filter Using filterbuilder” on page 16-11 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16 Designing a Filter in the Filterbuilder GUI Filterbuilder Design Process In this section... “Introduction to Filterbuilder” on page 16-2 “Design a Filter Using Filterbuilder” on page 16-2 “Select a Response” on page 16-2 “Select a Specification” on page 16-5 “Select an Algorithm” on page 16-5 “Customize the Algorithm” on page 16-7 “Analyze the Design” on page 16-9 “Realize or Apply the Filter to Input Data” on page 16-9 Introduction to Filterbuilder The filterbuilder function provides a graphical interface to the fdesign object-object oriented filter design paradigm and is intended to reduce development time during the filter design process. filterbuilder uses a specification-centered approach to find the best algorithm for the desired response. Note: filterbuilder requires the Signal Processing Toolbox. The functionality of filterbuilder is greatly expanded by the DSP System Toolbox. Many of the features described or displayed below are only available if the DSP System Toolbox is installed. You may verify your installation by typing ver at the command prompt. Design a Filter Using Filterbuilder The basic workflow in using filterbuilder is to choose the constraints and specifications of the filter, and to use those as a starting point in the design. Postponing the choice of algorithm for the filter allows the best design method to be determined automatically, based upon the desired performance criteria. The following are the details of each of the steps for designing a filter with filterbuilder. Select a Response When you open the filterbuilder tool by typing: 16-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filterbuilder Design Process filterbuilder at the MATLAB command prompt, the Response Selection dialog box appears, listing all possible filter responses available in DSP System Toolbox. Note This step cannot be skipped because it is not automatically completed for you by the software. You must select a response to initiate the filter design process. After you choose a response, say bandpass, you start the design of the Specifications Object, and the Bandpass Design dialog box appears. This dialog box contains a Main pane, a Data Types pane and a Code Generation pane. The specifications of your filter are generally set in the Main pane of the dialog box. The Data Types pane provides settings for precision and data types, and the Code Generation pane contains options for various implementations of the completed filter design. For the initial design of your filter, you will mostly use the Main pane. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-3 16 16-4 Designing a Filter in the Filterbuilder GUI www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filterbuilder Design Process The Bandpass Design dialog box contains all the parameters you need to determine the specifications of a bandpass filter. The parameters listed in the Main pane depend upon the type of filter you are designing. However, no matter what type of filter you have chosen in the Response Selection dialog box, the filter design dialog box contains the Main, Data Types, and Code Generation panes. Select a Specification To choose the specification for the bandpass filter, you can begin by selecting an Impulse Response, Order Mode, and Filter Type in the Filter Specifications frame of the Main Pane. You can further specify the response of your filter by setting frequency and magnitude specifications in the appropriate frames on the Main Pane. Note Frequency, Magnitude, and Algorithm specifications are interdependent and may change based upon your Filter Specifications selections. When choosing specifications for your filter, select your Filter Specifications first and work your way down the dialog box- this approach ensures that the best settings for dependent specifications display as available in the dialog box. Select an Algorithm The algorithms available for your filter depend upon the filter response and design parameters you have selected in the previous steps. For example, in the case of a bandpass filter, if the impulse response selected is IIR and the Order Mode field is set to Minimum, the design methods available are Butterworth, Chebyshev type I or II, or Elliptic, whereas if the Order Mode field is set to Specify, the design method available is IIR least p-norm. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-5 16 16-6 Designing a Filter in the Filterbuilder GUI www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filterbuilder Design Process Customize the Algorithm By expanding the Design options section of the Algorithm frame, you can further customize the algorithm specified. The options available will depend upon the algorithm and settings that have already been selected in the dialog box. In the case of a bandpass IIR filter using the Butterworth method, design options such as Match Exactly are available, as shown in the following figure. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-7 16 16-8 Designing a Filter in the Filterbuilder GUI www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Filterbuilder Design Process Analyze the Design To analyze the filter response, click on the View Filter Response button. The Filter Visualization Tool opens displaying the magnitude plot of the filter response. Realize or Apply the Filter to Input Data When you have achieved the desired filter response through design iterations and analysis using the Filter Visualization Tool, apply the filter to the input data. Again, this step is never automatically performed for you by the software. To filter your data, you must explicitly execute this step. In the Bandpass Design dialog box, click OK and DSP System Toolbox creates the filter object and exports it to the MATLAB workspace. The filter is then ready to be used to filter actual input data. The basic filter command takes input data x, filters it through the Filter Object, and produces output y: >> y = filter (Hbp, x) To understand how the filtering commands work, type: >> help dfilt/filter www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-9 16 Designing a Filter in the Filterbuilder GUI Tip If you have Simulink, you have the option of exporting this filter to a Simulink block using the realizemdl command. To get help on this command, type: >> help realizemdl 16-10 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Designing a FIR Filter Using filterbuilder Designing a FIR Filter Using filterbuilder FIR Filter Design Example – Using Filterbuilder to Design a Finite Impulse Response (FIR) Filter To design a lowpass FIR filter using filterbuilder: 1 Open the Filterbuilder GUI by typing the following at the MATLAB prompt: filterbuilder The Response Selection dialog box appears. In this dialog box, you can select from a list of filter response types. Select Lowpass in the list box. 2 Hit the OK button. The Lowpass Design dialog box opens. Here you can specify the writable parameters of the Lowpass filter object. The components of the Main frame of this dialog box are described in the section titled Lowpass Filter Design Dialog Box — Main Pane. In the dialog box, make the following changes: • Enter a Fpass value of 0.55. • Enter a Fstop value of 0.65. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-11 16 Designing a Filter in the Filterbuilder GUI 3 Click Apply, and the following message appears at the MATLAB prompt: The variable 'Hlp' has been exported to the command window. 4 16-12 To check your design, click View Filter Response. The Filter Visualization tool appears, showing a plot of the magnitude response of the filter. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Designing a FIR Filter Using filterbuilder You can change the design and click Apply, followed by View Filter Response, as many times as needed until your design specifications are met. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-13 ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان 16-14 A Bibliography ﻣﺘﻠﺐ ﺳﺎﯾﺖ | www.MatlabSite.com ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان A Advanced Filters Advanced Filters [1] Antoniou, A., Digital Filters: Analysis, Design, and Applications, Second Edition, McGraw-Hill, Inc., 1993. [2] Chirlian, P.M., Signals and Filters, Van Nostrand Reinhold, 1994. [3] Fliege, N.J., Multirate Digital Signal Processing, John Wiley and Sons, 1994. [4] Jackson, L., Digital Filtering and Signal Processing with MATLAB Exercises, Third edition, Springer, 1995. [5] Lapsley, P., J. Bier, A. Sholam, and E.A. Lee, DSP Processor Fundamentals: Architectures and Features, IEEE Press, 1997. [6] McClellan, J.H., C.S. Burrus, A.V. Oppenheim, T.W. Parks, R.W. Schafer, and H.W. Schuessler, Computer-Based Exercises for Signal Processing Using MATLAB 5, Prentice-Hall, 1998. [7] Mayer-Baese, U., Digital Signal Processing with Field Programmable Gate Arrays, Springer, 2001, refer to the BiQuad block diagram on pp. 126 and the IIR Butterworth example on pp. 140. [8] Moler, C., “Floating points: IEEE Standard unifies arithmetic model.” Cleve's Corner, The MathWorks, Inc., 1996. See http://www.mathworks.com/company/newsletter/ pdf/Fall96Cleve.pdf. [9] Oppenheim, A.V., and R.W. Schafer, Discrete-Time Signal Processing, Prentice-Hall, 1989. [10] Shajaan, M., and J. Sorensen, “Time-Area Efficient Multiplier-Free Recursive Filter Architectures for FPGA Implementation,” IEEE International Conference on Acoustics, Speech, and Signal Processing, 1996, pp. 3269-3272. A-2 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Adaptive Filters Adaptive Filters [1] Hayes, M.H., Statistical Digital Signal Processing and Modeling, John Wiley and Sons, 1996. [2] Haykin, S., Adaptive Filter Theory, Third Edition, Prentice-Hall, Inc., 1996. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان A-3 A Multirate Filters Multirate Filters [1] Fliege, N.J., Multirate Digital Signal Processing, John Wiley and Sons, 1994. [2] Harris, Fredric J, Multirate Signal Processing for Communication Systems, Prentice Hall PTR, 2004. [3] Hogenauer, E. B., “An Economical Class of Digital Filters for Decimation and Interpolation,” IEEE Transactions on Acoustics, Speech, and Signal Processing, Vol. ASSP-29, No. 2, April 1981, pp. 155-162. [4] Lyons, Richard G., Understanding Digital Signal Processing, Prentice Hall PTR, 2004 [5] Mitra, S.K., Digital Signal Processing, McGraw-Hill, 1998. [6] Orfanidis, S.J., Introduction to Signal Processing, Prentice-Hall, Inc., 1996. A-4 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان Frequency Transformations Frequency Transformations [1] Constantinides, A.G., “Spectral Transformations for Digital Filters,” IEEE Proceedings, Vol. 117, No. 8, pp. 1585-1590, August 1970. [2] Nowrouzian, B., and A.G. Constantinides, “Prototype Reference Transfer Function Parameters in the Discrete-Time Frequency Transformations,” Proceedings 33rd Midwest Symposium on Circuits and Systems, Calgary, Canada, Vol. 2, pp. 1078-1082, August 1990. [3] Feyh, G., J.C. Franchitti, and C.T. Mullis, “Allpass Filter Interpolation and Frequency Transformation Problem,“ Proceedings 20th Asilomar Conference on Signals, Systems and Computers, Pacific Grove, California, pp. 164-168, November 1986. [4] Krukowski, A., G.D. Cain, and I. Kale, “Custom Designed High-Order Frequency Transformations for IIR Filters,” 38th Midwest Symposium on Circuits and Systems (MWSCAS'95), Rio de Janeiro, Brazil, August 1995. www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان A-5 A Fixed-Point Filters Fixed-Point Filters [1] Jackson, L., Digital Filtering and Signal Processing with MATLAB Exercises, Third edition, Springer, 1995, pp.373–422. [2] Dehner, G, “Noise optimized IIR digital filter design: tutorial and some new aspects,” Signal Processing, Vol 83, Issue 8 (August 2003) pp.1565–1582. A-6 www.MatlabSite.com | ﻣﺘﻠﺐ ﺳﺎﯾﺖ ﻣﺮﺟﻊ آﻣﻮزش ﺑﺮﻧﺎﻣﻪﻧﻮﯾﺴﯽ ﻣﺘﻠﺐ در اﯾﺮان معرفی چند منبع در زمینه آموزش برنامه نویسی MATLABیا متلب کتاب های به زبان انگلیسی عنوانMatlab, Third Edition: A Practical Introduction to : Programming and Problem Solving ترجمه عنوان :متلب :مقدمه ای عملی بر برنامه نويسی و حل مساله ،چاپ سوم مولفینStormy Attaway : سال چاپ2013 : انتشاراتButterworth-Heinemann : کتاب های به زبان فارسی عنوان :اصول و مبانی متلب برای علوم مهندسی مولفین :برايان هان ،دانیل تی ،والنتین مترجمین :رامین موالنا پور ،سارا موالناپور ،نینا اسدی پور انتشارات :سها دانش لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB For Dummies : ترجمه عنوان :تلب به زبان ساده مولفینJim Sizemore, John Paul Mueller : سال چاپ2014 : انتشاراتFor Dummies : عنوان :کاربرد MATLABدر علوم مهندسی مولفین :حیدرعلی شايانفر ،حسین شايقی انتشارات :ياوريان لینک دسترسی :لینک لینک دسترسی :لینک عنوانEssential MATLAB for Engineers and Scientists : عنوان :برنامه نويسی MATLABبرای مهندسان ترجمه عنوان :آنچه بايد مهندسین و دانشمندان از متلب بدانند مولفین :محمود کشاورز مهر ،بهزاد عبدی مولفینBrian Hahn, Daniel Valentine: سال چاپ2013 : انتشاراتAcademic Press : انتشارات :نوپردازان لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB: An Introduction with Applications : عنوان :آموزش کاربردی مباحث پیشرفته با MATLAB ترجمه عنوان :مقدمه ای بر متلب و کاربردهای آن مولفین :نیما جمشیدی ،علی ابويی مهريزی ،رسول مواليی مولفAmos Gilat : انتشارات :عابد سال چاپ2014 : انتشاراتWiley : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB For Beginners: A Gentle Approach: عنوان :کاملترين مرجع آموزشی و کاربردی MATLAB ترجمه عنوان :متلب برای افراد مبتدی با يک رويکرد تدريجی مولفین :علی اکبر علمداری ،نسرين علمداری مولفPeter I. Kattan: انتشارات :نگارنده دانش سال چاپ2008 : انتشاراتCreateSpace Independent Publishing Platform : لینک دسترسی :لینک لینک دسترسی :لینک عنوانMATLAB for Engineers : عنوان :برنامه نويسی MATLABبرای مهندسین ترجمه عنوان :متلب برای مهندسین مولف :استفن چاپمن مولفHolly Moore : سال چاپ2011 : انتشاراتPrentice Hall : لینک دسترسی :لینک عنوانMastering MATLAB : ترجمه عنوان :تسلط بر متلب مولفینDuane C. Hanselman, Bruce L. Littlefield : سال چاپ2011 : انتشاراتPrentice Hall : لینک دسترسی :لینک مترجم :سعدان زکائی انتشارات :دانشگاه صنعتی خواجه نصیرالدين طوسی لینک دسترسی :لینک عنوان :آموزش گام به گام محاسبات عددی با متلب مولف :کلیو مولر مترجم :رسول نصیری انتشارات :نشر گستر لینک دسترسی :لینک منابع آموزشی آنالین عنوان :مجموعه فرادرسهای برنامهنويسی متلب مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۹ :ساعت و ۳دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای متلب برای علوم و مهندسی مدرس :دکتر سید مصطفی کالمی هريس مدت زمان 14 :ساعت و 2۲دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوان :مجموعه فرادرسهای برنامه نويسی متلب پیشرفته مدرس :دکتر سید مصطفی کالمی هريس مدت زمان ۲ :ساعت و 12دقیقه زبان :فارسی ارائه دهنده :فرادرس لینک دسترسی :لینک عنوانIntroduction to Programming with MATLAB : ترجمه عنوان :آشنايی با برنامهنويسی متلب مدرسینAkos Ledeczi, Michael Fitzpatrick, Robert Tairas : زبان :انگلیسی ارائه دهندهVanderbilt University : لینک دسترسی :لینک عنوانIntroduction to MATLAB : ترجمه عنوان :مقدمهای بر متلب مدرسDanilo Šćepanović : زبان :انگلیسی ارائه دهندهMIT OCW : لینک دسترسی :لینک عنوانUp and Running with MATLAB : ترجمه عنوان :شروع سريع کار با متلب مدرسPatrick Royal : زبان :انگلیسی ارائه دهندهlynda.com : لینک دسترسی :لینک عنوانModelling and Simulation using MATLAB : ترجمه عنوان :مدلسازی و شبیهسازی با استفاده از متلب مدرسین Prof. Dr.-Ing. Georg Fries :و دیگران زبان :انگلیسی ارائه دهندهiversity.org : لینک دسترسی :لینک

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement