matlab simulink

363
从 Matlab/Simulink 模型 到代码实现 陈永春 编著 清 华 大 学 出 版 社

Upload: saint-tyagi

Post on 18-Jan-2016

275 views

Category:

Documents


1 download

DESCRIPTION

Regarding Matlab Training Simulink

TRANSCRIPT

Page 1: Matlab Simulink

从 Matlab/Simulink 模型

到代码实现

陈永春 编著

清 华 大 学 出 版 社

Page 2: Matlab Simulink

(京)新登字 158号 内 容 简 介

本书是一本易学易用、编排科学、理论与实际密切结合的MATLAB学习用书,它可以使读者全面了

解MATLAB技术,并帮助解决应用中的难题。

本书分为 9个章节。先是介绍了 MATLAB 产品的体系结构、产品开发的流程及 MATLAB 的算法开

发功能,然后阐述了如何利用 MATLAB Complier 把 m 程序转成独立的应用以及系统级的设计工具

Simulink,紧接着介绍了从 Simulink模型生成面向目标代码的工具 Real-Time Workshop以及面向 DSP和

通信行业应用的一些模块的基本特征。本书附光盘一张,以方便读者学习MATLAB的大量实例、程序代

码及图形。

本书特别适用于那些以MATLAB作为开发/仿真/实现工具的科技人员以及广大MATLAB爱好者。本书文字简洁,附有大量直观图形,能有效地节省读者的时间。

版权所有,翻印必究。 本书封面贴有清华大学出版社激光防伪标签,无标签者不得销售。 Administering Apache 或抄袭 本

书 名:从Matlab/Simulink模型到代码实现 作 者:陈永春 编著 出 版 者:清华大学出版社(北京清华大学学研大厦,邮编 100084)

http://www.tup.tsinghua.edu.cn 责任编辑:肖 丽 印 刷 者: 印刷厂 发 行 者:新华书店总店北京发行所 开 本:787×1092 1/16 印张:21 字数:479千字 版 次:2002年 10月第 1版 2002年 10月第 1次印刷 书 号:ISBN 7-900643-63-X 印 数:0001~5000 定 价:34.00元(附光盘)

Page 3: Matlab Simulink

前 言

2001年,我曾在MATLAB中国代理公司北京九州恒润科技有限公司做MATLAB在DSP和通信领域的技术支持工作。现在,我在一家著名的电子通信公司从事 4G关键技术研究,经常要用 MATLAB 编写仿真程序或者建模,将 m 语言程序转成 C/C++代码,经常要考虑如何从 C/C++语言中调用 MATLAB 的科学计算功能函数(即 MATLAB C/C++ Math Library),如何从 VB调用 MATLAB科学计算和可视化功能的问题。本书就是为了告诉读者如何解决这些问题,并且向读者阐述了如何从 Simulink 模型生成面向 TI DSPs/Xilinx FPGA/WindRiver VxWorks的代码,这对于负责硬件实现的开发人员来说,的确是一个福音。

我相信许多以MATLAB作为算法开发、系统仿真和实现工具的科研人员,都会深切关注上述问题。本书的目的一是为了向读者介绍 MATLAB 各个模块在产品开发流程中的作用,让读者对整个 MATLAB 产品的体系结构有一个全面的认识;二是要解决在使用MATLAB 的过程中碰到的上述难题。本书不仅适用于以 MATLAB 作为开发、仿真、实现工具的科研人员,而且适用于广大的 MATLAB 爱好者和正在使用或者将要使用 MATLAB的在校学生。本书力图让读者站在MATLAB之上看MATLAB,而并非局限于MATLAB工具箱内部。本书的内容如下:

第 1章全面论述MATLAB产品的体系结构及使用MATLAB工具进行产品开发的流程。

第 2章介绍 MATLAB的算法开发功能,告诉读者编写 m程序的高级用法,例如如何调用 C/Fortran程序,如何建立自己的函数库,如何编写变参数的 m函数等。

第 3章告诉读者如何利用MATLAB Compiler把 m程序转成独立的应用,如何从VC++中调用 m函数,如何从 VC++/VB中调用MATLAB科学计算及可视化功能等。

第 4 章介绍 MATLAB 系统级设计工具 Simulink,让大家明白 Simulink 的仿真机理和一些重要概念,同时告诉读者如何使用 Simulink模块封装自己的 C算法和 m语言算法,如何定制自己的模块库。

第 5章介绍从 Simulink模型生成面向目标代码的工具 Real-Time Workshop,告诉读者 Real-Time Workshop支持的目标代码和代码的自动生成过程。

第 6章全面介绍面向 TI DSP的自动代码生成工具 Development Kit for TI DSP,告诉读者如何从 Matlab实时或者非实时地访问 TI DSP,如何从 Simulink模型生成面向 TI DSP的 Code Composer Studio工程文件。

第 7章介绍面向 Xilinx FPGA的自动代码生成过程,告诉读者如何从 Simulink模型生成面向 Xilinx FPGA的 VHDL代码。

删除的内容: 引

删除的内容: l

删除的内容:

Page 4: Matlab Simulink

从Matlab/Simulink模型到代码实现 II

第 8 章介绍面向 WindRiver VxWorks 的自动代码生成过程,告诉读者如何从Simulink模型生成面向 VxWorks/Tornado的代码。

第 9章简单介绍了 MATLAB产品中面向 DSP和通信行业应用的一些模块的基本特征。

本书中有一些需要特殊说明的地方: 本书中>>command_name/command_name(arg1,⋯,argN)表示在MATLAB命令窗口输入命令 command_name或者 command_name(arg1,⋯,argN),其中 command_name可以是一个脚本 m文件名或者函数名,>>为默认的MATLAB命令提示符。

本书中大写的MATLAB表示MATLAB整个产品,有时也指MATLAB基本模块,即MATLAB Toolbox;Matlab指由MATLAB产品中的MATLAB基本模块和一些工具箱模块(例如,Image Processing Toolbox)及工具模块(例如 MATLAB Compiler)组成的 m语言开发环境。MATLAB Toolbox是所有MATLAB产品的基础,它只提供 m语言开发的基本环境,不包括各种工具箱函数。

本书中%MATLABROOT%指MATLAB安装目录。 本书中某些命令的输出结果篇幅较长,为了说明问题,书中原样给出。如果不关

心命令的输出,读者可以跳过这些内容。 本书的出版首先要感谢我的导师北京航空航天大学电子工程系的万国龙教授对我的帮

助和教诲;感谢北京九州恒润科技有限公司的总经理吉英存博士在工作中给我的教益和启

发;感谢所有帮助支持过我的同事、朋友以及清华大学出版社的编辑们! 最后还要对我的父亲母亲致以深深谢意! 如果本书的出版,能给使用MATLAB的读者带来一些帮助和启发,我将深感荣幸!欢

迎读者朋友通过 E-mail [email protected]和我交流MATLAB使用经验或者讨论相关问题。读者也可登录北京九州恒润科技有限公司的网址 http://www.hirain.com 或者MathWorks 公司的网址 http://www.mathworks.com 查询有关 MATLAB 的最新信息。有关MATLAB的购买事宜,请与北京九州恒润科技有限公司联系。

陈永春

2002年 7月 30日

删除的内容: …

删除的内容: …

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 5: Matlab Simulink

目 录

第 1章 MATLAB产品的体系结构...................................................................................1 1.1 科研及设计人员的最爱 ...............................................................................................1 1.2 MATLAB产品的体系结构..........................................................................................5 1.3 使用MATLAB工具进行产品开发的流程...............................................................28 1.4 MATLAB的安装 .......................................................................................................29 1.5 MATLAB的工作环境................................................................................................37

第 2章 算法开发 ..........................................................................................................47 2.1 数学方式的程序开发 .................................................................................................47 2.2 脚本 m文件 ................................................................................................................49 2.3 函数 m文件 ................................................................................................................50 2.4 Toolboxes ....................................................................................................................57 2.5 调用 C/Fortran程序....................................................................................................61 2.6 建立自己的函数库 .....................................................................................................83 2.7 算法开发示例 .............................................................................................................84

第 3章 将m程序转换成独立的应用.............................................................................93 3.1 选择 C/C++ compiler ..................................................................................................94 3.2 从 m程序自动生成独立的应用和 C/C++源代码.....................................................97 3.3 不是所有的 m程序都能转换成 C/C++代码...........................................................111 3.4 从 VC++中调用 m函数 ...........................................................................................118 3.5 从 VC++中调用MATLAB C Math Library.............................................................122 3.6 从 VB中调用MATLAB功能 .................................................................................138

第 4章 系统级设计工具 Simulink ...............................................................................143 4.1 图形化建模 ...............................................................................................................143 4.2 基本模块库 ...............................................................................................................144 4.3 Blocksets....................................................................................................................149 4.4 Simulink仿真机理....................................................................................................150 4.5 重要概念 ...................................................................................................................152 4.6 封装自己的 C算法和 m语言算法..........................................................................158

Page 6: Matlab Simulink

从Matlab/Simulink模型到代码实现

IV

4.7 定制自己的 Blockset ................................................................................................165 4.8 系统级设计和仿真 ...................................................................................................172

第 5章 Real-Time Workshop .....................................................................................180 5.1 减轻程序员负担 .......................................................................................................180 5.2 自动代码生成过程 ...................................................................................................181 5.3 RTW支持的目标 .....................................................................................................182 5.4 RTW的价值 .............................................................................................................192

第 6章 面向 TI DSP的自动代码生成 .........................................................................193 6.1 Developer’s Kit for TI DSP 概述 .............................................................................193 6.2 三种接口 ...................................................................................................................193 6.3 Developer’s Kit for TI DSP的安装 ..........................................................................195 6.4 从Matlab访问 TI DSP.............................................................................................196 6.5 从 Simulink模型生成面向 C6701 EVM 的工程文件 ...........................................225

第 7章 面向 Xilinx FPGA的自动代码生成 .................................................................242 7.1 对传统 FPGA设计方式的挑战 ...............................................................................242 7.2 Xilinx Blockset ..........................................................................................................243 7.3 VHDL代码生成 .......................................................................................................247 7.4 浮点仿真与定点仿真 ...............................................................................................256 7.5 未来之路 ...................................................................................................................256

第 8章 面向 VxWorks的代码生成..............................................................................258 8.1 VxWorks/Tornado .....................................................................................................258 8.2 Simulink VxWorks支持库 .......................................................................................258 8.3 Tornado (VxWorks) Real-Time Target运行结构 ....................................................260 8.4 Tornado (VxWorks) Real-Time Target的实现过程 ................................................263

第 9章 面向 DSP和通信行业的应用 ..........................................................................281 9.1 MATLAB R12.1 vs MATLAB 6.1 ...........................................................................281 9.2 MATLAB R12.1中适用于 DSP和通信行业的模块..............................................283 9.3 MATLAB基本模块 .................................................................................................284 9.4 Communications Toolbox..........................................................................................293 9.5 Filter Design Toolbox................................................................................................298 9.6 Image Processing Toolbox.........................................................................................298 9.7 Matlab C/C++ Math/Graphics Library ......................................................................299 9.8 Signal Processing Toolbox ........................................................................................299 9.9 Wavelet Toolbox .......................................................................................................302

Page 7: Matlab Simulink

目 录

V

9.10 Simulink概述..........................................................................................................302 9.11 Stateflow..................................................................................................................303 9.12 CDMA Reference Blockset .....................................................................................304 9.13 Communications Blockset .......................................................................................306 9.14 DSP Blockset ...........................................................................................................307 9.15 Motorola DSP Developer’s Kit................................................................................308 9.16 Xilinx Blockset ........................................................................................................311 9.17 Real-Time Workshop...............................................................................................311 9.18 Developer’s Kit for TI DSP .....................................................................................312 9.19 Real-Time Windows Target.....................................................................................313 9.20 RTW Embedded Coder............................................................................................313 9.21 Stateflow Coder .......................................................................................................313 9.22 Tornado (VxWorks) Real-Time Target ...................................................................320 9.23 Xilinx’s System Generator for Simulink .................................................................320 9.24 xPC Target ............................................................................................................... 320

附录 带命令行参数的独立应用程序 ............................................................................322

Page 8: Matlab Simulink

第 1章 MATLAB 产品的体系结构

1.1 科研及设计人员的最爱

MATLAB 是美国 MathWorks 公司开发的用于教育、工程与科学计算的软件产品。MATLAB 产品家族向用户提供从概念设计、算法开发、建模仿真到实时实现的理想集成环境。无论是进行科学研究和产品开发,还是从事教育事业,MATLAB 产品都是必不可少的工具。MATLAB产品可用来进行:

数据分析和可视化 数值和符号计算 控制系统设计 数字信号处理 图像处理 财务工程 系统建模与仿真 图形用户界面设计 原型与应用开发

MATLAB 产品广泛地应用于信号与图像处理、控制系统设计、通信系统仿真等诸多领域。MATLAB开放的体系结构使得 MATLAB产品很容易针对特定的需求进行扩充。到目前为止,有许多的厂商基于 MATLAB 产品做第三方开发,他们提供的产品是对MATLAB 产品功能的扩充。在网址 http://www.mathworks.com/partners 上,用户可以查询到基于MATLAB产品的所有第三方开发厂商的相关信息。

MATLAB 产品家族的一大特征是具有众多的面向特定应用领域的工具箱和模块库。它不仅提供了完整的函数集用来对数字信号处理、图像处理、控制系统设计、神经网络、

通信系统仿真等特殊应用进行分析和设计,还提供了用于诸如数据采集、报告生成和从

MATLAB语言程序产生独立 C/C++代码等方面的工具模块。在 MATLAB的命令窗口输入命令 ver,可显示用户所安装的MATLAB产品模块的版本信息:

>> ver -------------------------------------------------- MATLAB Version 6.1.0.450 (R12.1) on PCWIN MATLAB License Number: DEMO --------------------------------------------------

Page 9: Matlab Simulink

从Matlab/Simulink模型到代码实现 2

MATLAB Toolbox Version 6.1 (R12.1) 18-May-2001 Simulink Version 4.1 (R12.1) 06-Apr-2001 Stateflow Version 4.1 (R12.1) 21-May-2001 Stateflow Coder Version 4.1 (R12.1) 21-May-2001 Real-Time Windows Target Version 2.1 (R12.1) 02-Feb-2001 Real-Time Workshop Version 4.1 (R12.1) 18-May-2001 CDMA Reference Blockset Version 1.1 (R12.1) 18-May-2001 Communications Blockset Version 2.0.1 (R12.1) 18-May-2001 Communications Toolbox Version 2.0.1 (R12.1) 18-May-2001 Control System Toolbox Version 5.1 (R12.1) 18-May-2001 DSP Blockset Version 4.1 (R12.1) 18-May-2001 Data Acquisition Toolbox Version 2.1 (R12.1) 06-Apr-2001 Database Toolbox Version 2.2 (R12.1) 04-Jan-2001 Datafeed Toolbox Version 1.3 (R12.1) 03-Jan-2001 Developer's Kit for TI(tm) DSP Version 1.1 (R12.1) 08-Jun-2001 Dials & Gauges Blockset Version 1.1.1 (R12.1) 02-Feb-2001 Symbolic Math Toolbox Version 2.1.2 (R12.1) 11-Sep-2000 Filter Design Toolbox Version 2.1 (R12.1) 01-Feb-2001 Financial Derivatives Toolbox Version 1.0 (R12.1) 14-Aug-2000 Financial Time Series Toolbox Version 1.1 (R12.1) 01-Dec-2000 Financial Toolbox Version 2.1.3 (R12.1) 12-Mar-2001 Fixed-Point Blockset Version 3.1 (R12.1) 18-May-2001 Fuzzy Logic Toolbox Version 2.1.1 (R12.1) 18-May-2001 GARCH Toolbox Version 1.0 (R12.1) 01-Jun-1999 Image Processing Toolbox Version 3.1 (R12.1) 18-May-2001 Instrument Control Toolbox Version 1.1 (R12.1) 18-May-2001 LMI Control Toolbox Version 1.0.7 (R12.1) 18-May-2001 MATLAB Compiler Version 2.2 (R12.1) 30-Mar-2001 MATLAB Report Generator Version 1.2 (R12.1) 01-Apr-2001 MATLAB Web Server Version 1.2.1 (R12.1) 23-Apr-2001 Mapping Toolbox Version 1.2 (R12.1) 22-May-2000 Model Predictive Control Toolbox Version 1.0.6 (R12.1) 18-May-2001 Motorola DSP Developer's Kit Version 1.1 (R12.1) 01-Sep-2000 Mu-Analysis and Synthesis Toolbox Version 3.0.6 (R12.1) 18-May-2001 Neural Network Toolbox Version 4.0.1 (R12.1) 02-Feb-2001 Nonlinear Control Design Blockset Version 1.1.5 (R12.1) 18-May-2001 Optimization Toolbox Version 2.1.1 (R12.1) 18-May-2001 Partial Differential Equation Toolbox Version 1.0.4(R12.1) 06-Apr-2001 Power System Blockset Version 2.2 (R12.1) 06-Apr-2001 Real-Time Workshop Ada Coder Version 4.1 (R12.1) 18-May-2001 Real-Time Workshop Embedded Coder Version 2.0 (R12.1) 01-Mar-2001 Requirements Management Interface Version 1.0.2 (R12.1) 30-Nov-2000

Page 10: Matlab Simulink

第 1章 MATLAB产品的体系结构 3

Robust Control Toolbox Version 2.0.8 (R12.1) 18-May-2001 SB2SL (converts SystemBuild to Simu... Version 2.2 (R12.1) 10-Apr-2001 Signal Processing Toolbox Version 5.1 (R12.1) 06-Apr-2001 Simulink Performance Tools Version 1.1 (R12.1) 18-May-2001 Simulink Report Generator Version 1.2 (R12.1) 01-Apr-2001 Spline Toolbox Version 3.0 (R12.1) 13-Mar-2000 Statistics Toolbox Version 3.0 (R12.1) 01-Sep-2000 System Identification Toolbox Version 5.0.1 (R12.1) 18-May-2001 Wavelet Toolbox Version 2.1 (R12.1) 06-Apr-2001 xPC Target Version 1.2 (R12.1) 09-Apr-2001 xPC Target Embedded Option Version 1.2 (R12.1) 09-Apr-2001

如果想单独查询某个模块的版本信息,例如 MATLAB Toolbox 或者 Simulink,可按如下方式进行:

>> ver matlab MATLAB Version 6.1.0.450 (R12.1) on PCWIN MATLAB License Number: DEMO MATLAB Toolbox Version 6.1 (R12.1) 18-May-2001 >> ver Simulink Simulink Version 4.1 (R12.1) 06-Apr-2001

如果想知道所执行的 ver命令位于何处,可以输入: >> which ver D:\MATLAB6p1\toolbox\matlab\general\ver.m

如果想查看或者编辑 ver源文件,可以输入: >> edit ver

ver源文件会显示在MATLAB编辑窗口中,默认情况下如图 1.1所示。 如果想查看有关 ver的帮助,可按如下方式进行: >> help ver VER MATLAB, Simulink, and toolbox version information. VER displays the current MATLAB and toolbox version numbers. VER(TOOLBOX_DIR) displays the current version information for the toolbox specified by the string TOOLBOX_DIR.

Page 11: Matlab Simulink

从Matlab/Simulink模型到代码实现 4

For example, ver control returns the version info for the Control System Toolbox. For tips on how to get VER to display version information about your toolbox, type at the MATLAB prompt more on type ver.m and then type 'more off' when the display of ver.m has finished. See also VERSION, HOSTID, LICENSE, INFO, WHATSNEW. >> helpwin ver

运行结果如图 1.2所示。

图 1.1 ver源文件

图 1.2 输入 helpwin ver运行结果 删除的内容: (图题应该和图在同一页)

Page 12: Matlab Simulink

第 1章 MATLAB产品的体系结构 5

>> doc ver

运行结果如图 1.3所示。

图 1.3 输入 doc ver运行结果

对任何一个MATLAB命令的解析都可以按上述方式进行。

1.2 MATLAB产品的体系结构

MATLAB产品是由多个模块组成的一个家族体系,它的整体结构如图 1.4所示。

图 1.4 MATLAB产品的体系结构 删除的内容: (图题应该和图在同一页)

Page 13: Matlab Simulink

从Matlab/Simulink模型到代码实现 6

MATLAB Toolbox

图 1.4 中的 MATLAB 是指 MATLAB 基本模块,即 MATLAB Toolbox。MATLAB Toolbox提供 m语言开发的基本环境,它是整个 MATLAB产品家族的基础。MATLAB产品的其他模块都需要运行在 MATLAB Toolbox之上。启动 MATLAB后,可以看到类似于图 1.5所示的MATLAB界面。

图 1.5 MATLAB界面

Toolboxes

Toolboxes的意思是工具箱,用 ver命令可以看到 MATLAB产品主要包含如下所列的工具箱:

Communications Toolbox Version 2.0.1 (R12.1) 18-May-2001(comm) Control System Toolbox Version 5.1 (R12.1) 18-May-2001(control) Data Acquisition Toolbox Version 2.1 (R12.1) 06-Apr-2001(daq) Database Toolbox Version 2.2 (R12.1) 04-Jan-2001(database) Datafeed Toolbox Version 1.3 (R12.1) 03-Jan-2001(datafeed) Symbolic Math Toolbox Version 2.1.2 (R12.1) 11-Sep-2000(symbolic) Filter Design Toolbox Version 2.1 (R12.1) 01-Feb-2001(filterdesign) Financial Derivatives Toolbox Version 1.0 (R12.1) 14-Aug-2000(finderiv) Financial Time Series Toolbox Version 1.1 (R12.1) 01-Dec-2000(ftseries) Financial Toolbox Version 2.1.3 (R12.1) 12-Mar-2001(finance) Fuzzy Logic Toolbox Version 2.1.1 (R12.1) 18-May-2001(fuzzy) GARCH Toolbox Version 1.0 (R12.1) 01-Jun-1999(garch) Image Processing Toolbox Version 3.1 (R12.1) 18-May-2001(images) Instrument Control Toolbox Version 1.1 (R12.1) 18-May-2001(instrument)

Page 14: Matlab Simulink

第 1章 MATLAB产品的体系结构 7

LMI Control Toolbox Version 1.0.7 (R12.1) 18-May-2001(lmi) Mapping Toolbox Version 1.2 (R12.1) 22-May-2000(map) Model Predictive Control Toolbox Version 1.0.6 (R12.1) 18-May-2001(mpc)

Mu-Analysis and Synthesis Toolbox Version 3.0.6 (R12.1) 18-May-2001(mutools) Neural Network Toolbox Version 4.0.1 (R12.1) 02-Feb-2001(nnet) Optimization Toolbox Version 2.1.1 (R12.1) 18-May-2001(opt) Partial Differential Equation Toolbox Version 1.0.4 (R12.1) 06-Apr-2001(pde) Robust Control Toolbox Version 2.0.8 (R12.1) 18-May-2001(robust)

Signal Processing Toolbox Version 5.1 (R12.1) 06-Apr-2001(signal) Spline Toolbox Version 3.0 (R12.1) 13-Mar-2000(splines) Statistics Toolbox Version 3.0 (R12.1) 01-Sep-2000(stats) System Identification Toolbox Version 5.0.1 (R12.1) 18-May-2001(ident) Wavelet Toolbox Version 2.1 (R12.1) 06-Apr-2001(wavelet)

工具箱是面向特定应用领域的函数的集合,例如 Signal Processing Toolbox 封装的就是用于模拟/数字信号处理方面的函数,Image Processing Toolbox 封装的是用于数字图像处理的函数。使用 help/what 命令(以上述所列工具箱中的粗体文字作参数)可以查看各工具箱中函数的分类情况。

>> help signal Signal Processing Toolbox. Version 5.1 (R12.1) 06-Apr-2001 Filter analysis. abs - Magnitude. angle - Phase angle. filternorm - Compute the 2-norm or inf-norm of a digital filter. freqs - Laplace transform frequency response. freqspace - Frequency spacing for frequency response. freqz - Z-transform frequency response. freqzplot - Plot frequency response data. fvtool - Filter Visualization Tool (FVTool). grpdelay - Group delay. impz - Discrete impulse response. unwrap - Unwrap phase. zplane - Discrete pole-zero plot. Filter implementation. conv - Convolution. conv2 - 2-D convolution.

删除的内容:

删除的内容: 按照原文应该在同一行上

删除的内容: Toolbox

删除的内容:

删除的内容: 按照原文应该在同一行上

删除的内容:

删除的内容:

删除的内容: 按照原文应该在同一行上

删除的内容:

删除的内容: 按照原文应该在同一行上

删除的内容:

删除的内容: (

删除的内容: 做

删除的内容: )

删除的内容: angle

Page 15: Matlab Simulink

从Matlab/Simulink模型到代码实现 8

deconv - Deconvolution. fftfilt - Overlap-add filter implementation. filter - Filter implementation. filter2 - Two-dimensional digital filtering. filtfilt - Zero-phase version of filter. filtic - Determine filter initial conditions. latcfilt - Lattice filter implementation. medfilt1 - 1-Dimensional median filtering. sgolayfilt - Savitzky-Golay filter implementation. sosfilt - Second-order sections (biquad) filter implementation. upfirdn - Up sample, FIR filter, down sample. FIR filter design. convmtx - Convolution matrix. cremez - Complex and nonlinear phase equiripple FIR filter design. fir1 - Window based FIR filter design - low, high, band, stop, multi. fir2 - FIR arbitrary shape filter design using the frequency sampling method. fircls - Constrained Least Squares filter design – arbitrary response. fircls1 - Constrained Least Squares FIR filter design - low and highpass. firls - Optimal least-squares FIR filter design. firrcos - Raised cosine FIR filter design. intfilt - Interpolation FIR filter design. kaiserord - Kaiser window design based filter order estimation. remez - Optimal Chebyshev-norm FIR filter design. remezord - Remez design based filter order estimation. sgolay - Savitzky-Golay FIR smoothing filter design. IIR digital filter design. butter - Butterworth filter design. cheby1 - Chebyshev Type I filter design (passband ripple). cheby2 - Chebyshev Type II filter design (stopband ripple). ellip - Elliptic filter design. maxflat - Generalized Butterworth lowpass filter design. yulewalk - Yule-Walker filter design. IIR filter order estimation. buttord - Butterworth filter order estimation. cheb1ord - Chebyshev Type I filter order estimation. cheb2ord - Chebyshev Type II filter order estimation. ellipord - Elliptic filter order estimation. Analog lowpass filter prototypes.

删除的内容:

删除的内容:

Page 16: Matlab Simulink

第 1章 MATLAB产品的体系结构 9

besselap - Bessel filter prototype. buttap - Butterworth filter prototype. cheb1ap - Chebyshev Type I filter prototype (passband ripple). cheb2ap - Chebyshev Type II filter prototype (stopband ripple). ellipap - Elliptic filter prototype. Analog filter design. besself - Bessel analog filter design. butter - Butterworth filter design. cheby1 - Chebyshev Type I filter design. cheby2 - Chebyshev Type II filter design. ellip - Elliptic filter design. Analog filter transformation. lp2bp - Lowpass to bandpass analog filter transformation. lp2bs - Lowpass to bandstop analog filter transformation. lp2hp - Lowpass to highpass analog filter transformation. lp2lp - Lowpass to lowpass analog filter transformation. Filter discretization. bilinear - Bilinear transformation with optional prewarping. impinvar - Impulse invariance analog to digital conversion. Linear system transformations. latc2tf - Lattice or lattice ladder to transfer function conversion. polystab - Polynomial stabilization. polyscale - Scale roots of polynomial. residuez - Z-transform partial fraction expansion. sos2ss - Second-order sections to state-space conversion. sos2tf - Second-order sections to transfer function conversion. sos2zp - Second-order sections to zero-pole conversion. ss2sos - State-space to second-order sections conversion. ss2tf - State-space to transfer function conversion. ss2zp - State-space to zero-pole conversion. tf2latc - Transfer function to lattice or lattice ladder conversion. tf2sos - Transfer Function to second-order sections conversion. tf2ss - Transfer function to state-space conversion. tf2zp - Transfer function to zero-pole conversion. zp2sos - Zero-pole to second-order sections conversion. zp2ss - Zero-pole to state-space conversion. zp2tf - Zero-pole to transfer function conversion.

Page 17: Matlab Simulink

从Matlab/Simulink模型到代码实现 10

Windows. bartlett - Bartlett window. barthannwin - Modified Bartlett-Hanning window. blackman - Blackman window. blackmanharris - Minimum 4-term Blackman-Harris window. bohmanwin - Bohman window. chebwin - Chebyshev window. gausswin - Gaussian window. hamming - Hamming window. hann - Hann window. kaiser - Kaiser window. nuttallwin - Nuttall defined minimum 4-term Blackman-Harris window. rectwin - Rectangular window. triang - Triangular window. tukeywin - Tukey window. window - Window function gateway. Transforms. bitrevorder - Permute input into bit-reversed order. czt - Chirp-z transform. dct - Discrete cosine transform. dftmtx - Discrete Fourier transform matrix. fft - Fast Fourier transform. fft2 - 2-D fast Fourier transform. fftshift - Swap vector halves. goertzel - Second-order Goertzel algorithm. hilbert - Discrete-time analytic signal via Hilbert transform. idct - Inverse discrete cosine transform. ifft - Inverse fast Fourier transform. ifft2 - Inverse 2-D fast Fourier transform. Cepstral analysis. cceps - Complex cepstrum. icceps - Inverse Complex cepstrum. rceps - Real cepstrum and minimum phase reconstruction. Statistical signal processing and spectral analysis. cohere - Coherence function estimate. corrcoef - Correlation coefficients. corrmtx - Autocorrelation matrix. cov - Covariance matrix. csd - Cross Spectral Density.

Page 18: Matlab Simulink

第 1章 MATLAB产品的体系结构 11

pburg - Power Spectral Density estimate via Burg's method. pcov - Power Spectral Density estimate via the Covariance method. peig - Power Spectral Density estimate via the Eigenvector method. periodogram - Power Spectral Density estimate via the periodogram method. pmcov - Power Spectral Density estimate via the Modified Covariance method. pmtm - Power Spectral Density estimate via the Thomson multitaper method. pmusic - Power Spectral Density estimate via the MUSIC method. psdplot - Plot Power Spectral Density data. pwelch - Power Spectral Density estimate via Welch's method. pyulear - Power Spectral Density estimate via the Yule-Walker AR Method. rooteig - Sinusoid frequency and power estimation via the eigenvector algorithm. rootmusic - Sinusoid frequency and power estimation via the MUSIC algorithm. tfe - Transfer function estimate. xcorr - Cross-correlation function. xcorr2 - 2-D cross-correlation. xcov - Covariance function. Parametric modeling. arburg - AR parametric modeling via Burg's method. arcov - AR parametric modeling via covariance method. armcov - AR parametric modeling via modified covariance method. aryule - AR parametric modeling via the Yule-Walker method. ident - See the System Identification Toolbox. invfreqs - Analog filter fit to frequency response. invfreqz - Discrete filter fit to frequency response. prony - Prony's discrete filter fit to time response. stmcb - Steiglitz-McBride iteration for ARMA modeling. Linear Prediction. ac2rc - Autocorrelation sequence to reflection coefficients conversion. ac2poly - Autocorrelation sequence to prediction polynomial conversion. is2rc - Inverse sine parameters to reflection coefficients conversion. lar2rc - Log area ratios to reflection coefficients conversion. levinson - Levinson-Durbin recursion. lpc - Linear Predictive Coefficients using autocorrelation method. lsf2poly - Line spectral frequencies to prediction polynomial conversion. poly2ac - Prediction polynomial to autocorrelation sequence conversion. poly2lsf - Prediction polynomial to line spectral frequencies conversion. poly2rc - Prediction polynomial to reflection coefficients conversion. rc2ac - Reflection coefficients to autocorrelation sequence conversion. rc2is - Reflection coefficients to inverse sine parameters conversion. rc2lar - Reflection coefficients to log area ratios conversion.

Page 19: Matlab Simulink

从Matlab/Simulink模型到代码实现 12

rc2poly - Reflection coefficients to prediction polynomial conversion. rlevinson - Reverse Levinson-Durbin recursion. schurrc - Schur algorithm. Multirate signal processing. decimate - Resample data at a lower sample rate. downsample - Downsample input signal. interp - Resample data at a higher sample rate. interp1 - General 1-D interpolation. (MATLAB Toolbox) resample - Resample sequence with new sampling rate. spline - Cubic spline interpolation. upfirdn - Up sample, FIR filter, down sample. upsample - Upsample input signal. Waveform generation. chirp - Swept-frequency cosine generator. diric - Dirichlet (periodic sinc) function. gauspuls - Gaussian RF pulse generator. gmonopuls - Gaussian monopulse generator. pulstran - Pulse train generator. rectpuls - Sampled aperiodic rectangle generator. sawtooth - Sawtooth function. sinc - Sinc or sin(pi*x)/(pi*x) function square - Square wave function. tripuls - Sampled aperiodic triangle generator. vco - Voltage controlled oscillator. Specialized operations. buffer - Buffer a signal vector into a matrix of data frames. cell2sos - Convert cell array to second-order-section matrix. cplxpair - Order vector into complex conjugate pairs. demod - Demodulation for communications simulation. dpss - Discrete prolate spheroidal sequences (Slepian sequences). dpssclear - Remove discrete prolate spheroidal sequences from database. dpssdir - Discrete prolate spheroidal sequence database directory. dpssload - Load discrete prolate spheroidal sequences from database. dpsssave - Save discrete prolate spheroidal sequences in database. eqtflength - Equalize the length of a discrete-time transfer function. modulate - Modulation for communications simulation. seqperiod - Find minimum-length repeating sequence in a vector. sos2cell - Convert second-order-section matrix to cell array. specgram - Spectrogram, for speech signals.

Page 20: Matlab Simulink

第 1章 MATLAB产品的体系结构 13

stem - Plot discrete data sequence. strips - Strip plot. udecode - Uniform decoding of the input. uencode - Uniform quantization and encoding of the input into N-bits. Graphical User Interfaces fdatool - Filter Design and Analysis Tool. sptool - Signal Processing Tool. See also SIGDEMOS, AUDIO, and, in the Filter Design Toolbox, FILTERDESIGN. >> help images Image Processing Toolbox. Version 3.1 (R12.1) 18-May-2001 Release information. images/Readme - Display information about current and previous versions. Image display. colorbar - Display colorbar (MATLAB Toolbox). getimage - Get image data from axes. image - Create and display image object (MATLAB Toolbox). imagesc - Scale data and display as image (MATLAB Toolbox). immovie - Make movie from multiframe image. imshow - Display image. montage - Display multiple image frames as rectangular montage. movie - Play recorded movie frames. subimage - Display multiple images in single figure. truesize - Adjust display size of image. warp - Display image as texture-mapped surface. Image file I/O. dicominfo - Read metadata from a DICOM message. dicomread - Read a DICOM image. dicom-dict.txt - Text file containing DICOM data dictionary. imfinfo - Return information about image file (MATLAB Toolbox). imread - Read image file (MATLAB Toolbox). imwrite - Write image file (MATLAB Toolbox). Image arithmetic. imabsdiff - Compute absolute difference of two images.

Page 21: Matlab Simulink

从Matlab/Simulink模型到代码实现 14

imadd - Add two images, or add constant to image. imcomplement - Complement image. imdivide - Divide two images, or divide image by constant. imlincomb - Compute linear combination of images. immultiply - Multiply two images, or multiply image by constant. imsubtract - Subtract two images, or subtract constant from image. Geometric transformations. checkerboard - Create checkerboard image. findbounds - Find output bounds for geometric transformation. fliptform - Flip the input and output roles of a TFORM struct. imcrop - Crop image. imresize - Resize image. imrotate - Rotate image. imtransform - Apply geometric transformation to image. makeresampler - Create resampler structure. maketform - Create geometric transformation structure (TFORM). tformarray - Apply geometric transformation to N-D array. tformfwd - Apply forward geometric transformation. tforminv - Apply inverse geometric transformation. Image registration. cpstruct2pairs - Convert CPSTRUCT to valid pairs of control points. cp2tform - Infer geometric transformation from control point pairs. cpcorr - Tune control point locations using cross-correlation. cpselect - Control point selection tool. normxcorr2 - Normalized two-dimensional cross-correlation. Pixel values and statistics. corr2 - Compute 2-D correlation coefficient. imcontour - Create contour plot of image data. imhist - Display histogram of image data. impixel - Determine pixel color values. improfile - Compute pixel-value cross-sections along line segments. mean2 - Compute mean of matrix elements. pixval - Display information about image pixels. regionprops - Measure properties of image regions. std2 - Compute standard deviation of matrix elements. Image analysis. edge - Find edges in intensity image. qtdecomp - Perform quadtree decomposition.

Page 22: Matlab Simulink

第 1章 MATLAB产品的体系结构 15

qtgetblk - Get block values in quadtree decomposition. qtsetblk - Set block values in quadtree decomposition. Image enhancement. histeq - Enhance contrast using histogram equalization. imadjust - Adjust image intensity values or colormap. imnoise - Add noise to an image. medfilt2 - Perform 2-D median filtering. ordfilt2 - Perform 2-D order-statistic filtering. stretchlim - Find limits to contrast stretch an image. wiener2 - Perform 2-D adaptive noise-removal filtering. Linear filtering. convmtx2 - Compute 2-D convolution matrix. fspecial - Create predefined filters. imfilter - Filter 2-D and N-D images. Linear 2-D filter design. freqspace - Determine 2-D frequency response spacing (MATLAB Toolbox). freqz2 - Compute 2-D frequency response. fsamp2 - Design 2-D FIR filter using frequency sampling. ftrans2 - Design 2-D FIR filter using frequency transformation. fwind1 - Design 2-D FIR filter using 1-D window method. fwind2 - Design 2-D FIR filter using 2-D window method. Image deblurring. deconvblind - Deblur image using blind deconvolution. deconvlucy - Deblur image using Lucy-Richardson method. deconvreg - Deblur image using regularized filter. deconvwnr - Deblur image using Wiener filter. edgetaper - Taper edges using point-spread function. otf2psf - Optical transfer function to point-spread function. psf2otf - Point-spread function to optical transfer function. Image transforms. dct2 - 2-D discrete cosine transform. dctmtx - Discrete cosine transform matrix. fft2 - 2-D fast Fourier transform (MATLAB Toolbox). fftn - N-D fast Fourier transform (MATLAB Toolbox). fftshift - Reverse quadrants of output of FFT (MATLAB Toolbox). idct2 - 2-D inverse discrete cosine transform. ifft2 - 2-D inverse fast Fourier transform (MATLAB Toolbox).

删除的内容: -

Page 23: Matlab Simulink

从Matlab/Simulink模型到代码实现 16

ifftn N-D inverse fast Fourier transform (MATLAB Toolbox). iradon - Compute inverse Radon transform. phantom - Generate a head phantom image. radon - Compute Radon transform. Neighborhood and block processing. bestblk - Choose block size for block processing. blkproc - Implement distinct block processing for image. col2im - Rearrange matrix columns into blocks. colfilt - Columnwise neighborhood operations. im2col - Rearrange image blocks into columns. nlfilter - Perform general sliding-neighborhood operations. Morphological operations (intensity and binary images). conndef - Default connectivity. imbothat - Perform bottom-hat filtering. imclearborder - Suppress light structures connected to image border. imclose - Close image. imdilate - Dilate image. imerode - Erode image. imextendedmax - Extended-maxima transform. imextendedmin - Extended-minima transform. imfill - Fill image regions and holes. imhmax - H-maxima transform. imhmin - H-minima transform. imimposemin - Impose minima. imopen - Open image. imreconstruct - Morphological reconstruction. imregionalmax - Regional maxima. imregionalmin - Regional minima. imtophat - Perform tophat filtering. watershed - Watershed transform. Morphological operations (binary images) applylut - Perform neighborhood operations using lookup tables. bwarea - Compute area of objects in binary image. bwareaopen - Binary area open (remove small objects). bwdist - Compute distance transform of binary image. bweuler - Compute Euler number of binary image. bwhitmiss - Binary hit-miss operation. bwlabel - Label connected components in 2-D binary image. bwlabeln - Label connected components in N-D binary image.

删除的内容: -

删除的内容:

Page 24: Matlab Simulink

第 1章 MATLAB产品的体系结构 17

bwmorph - Perform morphological operations on binary image. bwpack - Pack binary image. bwperim - Determine perimeter of objects in binary image. bwselect - Select objects in binary image. bwulterode - Ultimate erosion. bwunpack - Unpack binary image. makelut - Construct lookup table for use with applylut. Structuring element (STREL) creation and manipulation. getheight - Get strel height. getneighbors - Get offset location and height of strel neighbors getnhood - Get strel neighborhood. getsequence - Get sequence of decomposed strels. isflat - Return true for flat strels. reflect - Reflect strel about its center. strel - Create morphological structuring element. translate - Translate strel. Region-based processing. roicolor - Select region of interest, based on color. roifill - Smoothly interpolate within arbitrary region. roifilt2 - Filter a region of interest. roipoly - Select polygonal region of interest. Colormap manipulation. brighten - Brighten or darken colormap (MATLAB Toolbox). cmpermute - Rearrange colors in colormap. cmunique - Find unique colormap colors and corresponding image. colormap - Set or get color lookup table (MATLAB Toolbox). imapprox - Approximate indexed image by one with fewer colors. rgbplot - Plot RGB colormap components (MATLAB Toolbox). Color space conversions. hsv2rgb - Convert HSV values to RGB color space (MATLAB Toolbox). ntsc2rgb - Convert NTSC values to RGB color space. rgb2hsv - Convert RGB values to HSV color space (MATLAB Toolbox). rgb2ntsc - Convert RGB values to NTSC color space. rgb2ycbcr - Convert RGB values to YCBCR color space. ycbcr2rgb - Convert YCBCR values to RGB color space. Array operations. circshift - Shift array circularly.

删除的内容:

Page 25: Matlab Simulink

从Matlab/Simulink模型到代码实现 18

padarray - Pad array. Image types and type conversions. dither - Convert image using dithering. gray2ind - Convert intensity image to indexed image. grayslice - Create indexed image from intensity image by thresholding. graythresh - Compute global image threshold using Otsu's method. im2bw - Convert image to binary image by thresholding. im2double - Convert image array to double precision. im2uint8 - Convert image array to 8-bit unsigned integers. im2uint16 - Convert image array to 16-bit unsigned integers. ind2gray - Convert indexed image to intensity image. im2mis - Convert image to Java MemoryImageSource. ind2rgb - Convert indexed image to RGB image (MATLAB Toolbox). isbw - Return true for binary image. isgray - Return true for intensity image. isind - Return true for indexed image. isrgb - Return true for RGB image. label2rgb - Convert label matrix to RGB image. mat2gray - Convert matrix to intensity image. rgb2gray - Convert RGB image or colormap to grayscale. rgb2ind - Convert RGB image to indexed image. Toolbox preferences. iptgetpref - Get value of Image Processing Toolbox preference. iptsetpref - Set value of Image Processing Toolbox preference. Demos. dctdemo - 2-D DCT image compression demo. edgedemo - Edge detection demo. firdemo - 2-D FIR filtering and filter design demo. imadjdemo - Intensity adjustment and histogram equalization demo. landsatdemo - Landsat color composite demo. nrfiltdemo - Noise reduction filtering demo. qtdemo - Quadtree decomposition demo. roidemo - Region-of-interest processing demo. Slide shows. ipss001 - Region labeling of steel grains. ipss002 - Feature-based logic. ipss003 - Correction of nonuniform illumination.

删除的内容: -

Page 26: Matlab Simulink

第 1章 MATLAB产品的体系结构 19

Extended-examples. ipexindex - Index of extended examples. ipexsegmicro - Segmentation to detect microstructures. ipexsegcell - Segmentation to detect cells. ipexsegwatershed - Watershed segmentation. ipexgranulometry - Granulometry of stars. ipexdeconvwnr - Wiener deblurring. ipexdeconvreg - Regularized deblurring. ipexdeconvlucy - Lucy-Richardson deblurring. ipexdeconvblind - Blind deblurring. ipextform - Image transform gallery. ipexshear - Image padding and shearing. ipexmri - 3-D MRI slices. ipexconformal - Conformal mapping. ipexnormxcorr2 - Normalized cross-correlation. ipexrotate - Rotation and scale recovery.

ipexregaerial - Aerial photo registration. >> what signal M-files in directory D:\MATLAB6p1\toolbox\signal\signal Contents fir2 psdplot aboutsignaltbx fircls pulstran ac2poly fircls1 pwelch ac2rc firls pyulear arburg firrcos rc2ac arcov freqs rc2is armcov freqz rc2lar aryule freqzplot rc2poly barthannwin gauspuls rceps bartlett gausswin rectpuls besselap gmonopuls rectwin besself goertzel remez bilinear grpdelay remezord bitrevorder hamming resample blackman hann residuez blackmanharris hanning rlevinson bohmanwin hilbert rooteig boxcar icceps rootmusic bscost idct sawtooth buffer impinvar schurrc

删除的内容: Contents

删除的内容: fir2

删除的内容: aboutsignaltbx

删除的内容: fircls

删除的内容: ac2poly

删除的内容: fircls1

删除的内容: ac2rc

删除的内容: firls

删除的内容: arburg

删除的内容: firrcos

删除的内容: arcov

删除的内容: freqs

删除的内容: armcov

删除的内容: freqz

删除的内容: aryule

删除的内容: freqzplot

删除的内容: barthannwin

删除的内容: gauspuls

删除的内容: bartlett

删除的内容: gausswin

删除的内容: besselap

删除的内容: gmonopuls

删除的内容: besself

删除的内容: goertzel

删除的内容: bilinear

删除的内容: grpdelay

删除的内容: bitrevorder

删除的内容: hamming

删除的内容:

删除的内容: hann

删除的内容: blackmanharris

删除的内容: hanning

删除的内容: bohmanwin

Page 27: Matlab Simulink

从Matlab/Simulink模型到代码实现 20

buttap impz seqperiod butter impzlength sgolay buttord interp sgolayfilt cceps intfilt signalpolyutils cell2sos invfreqs sigprivate cheb1ap invfreqz sinc cheb1ord is2rc sos2cell cheb2ap kaiser sos2ss cheb2ord kaiserord sos2tf chebwin kratio sos2zp cheby1 lar2rc sosfilt cheby2 latc2tf specgram chirp latcfilt specplot cohere levinson spectrum convmtx lp2bp square corrmtx lp2bs ss2sos cremez lp2hp stmcb csd lp2lp strips czt lpc tf2latc datawrap lsf2poly tf2sos dct maxflat tfe decimate medfilt1 triang demod modulate tripuls dftmtx nuttallwin tukeywin diric pburg udecode downsample pcov uencode dpss peig upfirdn dpssclear periodogram upsample dpssdir pmcov vco dpssload pmem vratio dpsssave pmtm window ellip pmusic xcorr ellipap poly2ac xcorr2 ellipord poly2lsf xcov eqtflength poly2rc yulewalk fftfilt polyscale zp2sos filternorm polystab zplane filtfilt prony filtic psd fir1 psdoptions MAT-files in directory D:\MATLAB6p1\toolbox\signal\signal

Page 28: Matlab Simulink

第 1章 MATLAB产品的体系结构 21

mtlb vcosig MEX-files in directory D:\MATLAB6p1\toolbox\signal\signal buffer levinson upfirdn latcfilt seqperiod >> what images M-files in directory D:\MATLAB6p1\toolbox\images\images Contents imdilate Readme imdivide applylut imerode bestblk imextendedmax blkproc imextendedmin bmpread imfeature bmpwrite imfill bwarea imfilter bwareaopen imhist bwdist imhmax bweuler imhmin bwfill imimposemin bwhitmiss imlincomb bwlabel immovie bwlabeln immultiply bwmorph imnoise bwpack imopen bwperim impixel bwselect improfile bwulterode imreconstruct bwunpack imregionalmax checkerboard imregionalmin circshift imresize cmgamdef imrotate cmgamma imshow cmpermute imslice cmunique imsubtract col2im imtophat colfilt imtransform conndef imzoom

删除的内容: Contents

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 29: Matlab Simulink

从Matlab/Simulink模型到代码实现 22

convmtx2 ind2gray corr2 iptgetpref cp2tform iptsetpref cpcorr iradon cpselect isbw cpselectswitchyard isgray cpstruct2pairs isind dct2 isrgb dctmtx label2rgb dctmtx2 makelut deconvblind makeresampler deconvlucy maketform deconvreg mat2gray deconvwnr mean2 dicominfo medfilt2 dicomread mfilter2 dilate montage dither nlfilter edge normxcorr2 edgetaper ntsc2rgb erode ordfilt2 findbounds otf2psf fliptform padarray freqz2 pcxread fsamp2 pcxwrite fspecial phantom ftrans2 pixval fwind1 psf2otf fwind2 qtdecomp getimage qtgetblk getline qtsetblk getpts radon getrect regionprops gifread rgb2gray gifwrite rgb2ind gray2ind rgb2ntsc grayslice rgb2ycbcr graythresh roicolor hdfpeek roifill hdfwrite roifilt2 histeq roipoly idct2 std2

删除的内容: convmtx2

删除的内容: fliptform

删除的内容:

Page 30: Matlab Simulink

第 1章 MATLAB产品的体系结构 23

im2bw stretchlim im2col subimage im2double tformarray im2mis tformfwd im2uint16 tforminv im2uint8 tiffread imabsdiff tiffwrite imadd truesize imadjust warp imapprox watershed imbothat wiener2 imclearborder xwdread imclose xwdwrite imcomplement ycbcr2rgb imcontour imcrop MAT-files in directory D:\MATLAB6p1\toolbox\images\images dicom-dict MEX-files in directory D:\MATLAB6p1\toolbox\images\images applylut imabsdiff imregionalmax bwpack imlincomb bwunpack imreconstruct Classes in directory D:\MATLAB6p1\toolbox\images\images strel

工具箱可以帮助用户加速特定应用领域的研发过程,让用户把主要精力放在构思自己

的想法,而不是编程上面。用户可以根据自己的应用领域有选择地购买工具箱模块。

Compiler

MATLAB Compiler 可以将 MATLAB m 程序编译成 C/C++源代码和独立的应用。用户也可以在 Borland C/C++、VC++环境中调用该源代码,或是直接调用 MathWorks 公司提供的 C/C++数学库。结合 MathWorks 公司提供的 C/C++数学库和图形库,用户可以利用 Matlab 快速地开发出功能强大的独立应用。此外,许多第三方的编译器也可将 m 程序编译成 C/C++源代码或是独立的应用。比较好的有 MATCOM,用户可以在网址

删除的内容: (为何空一片??)

分页符

Page 31: Matlab Simulink

从Matlab/Simulink模型到代码实现 24

http://www.google.com上使用MATCOM关键字搜索相关信息。

Simulink

图 1.4中的 Simulink是指建立在 Matlab之上的系统建模仿真基本环境,它提供了一个图形化的编辑界面。图 1.6所示是 Simulink基本环境。

图 1.6 Simulink基本环境

在这个界面环境中,用户可以用 Simulink提供的模块,或是自己封装的模块来搭建自己的系统。在 Simulink所建立的系统中,用户可以集成自己用 m语言或者 C语言开发的算法。系统建模完成之后,用户可以用 Simulink 或者 Matlab 产生各种各样的信源来测试所建立的系统的性能。Simulink 和 Matlab 是高度集成的,用户可以选择使用 Matlab 强大的数据分析功能来分析系统的性能。

Blocksets

Blocksets 是基于 Simulink 提供的面向不同应用领域的模块库。针对不同的应用领域,MathWorks 公司为用户提供了不同的专业模块库,主要是为了方便用户的系统建模过程。例如 DSP Blockset 提供了面向数字信号处理的专业模块库,内容包括滤波、FFT/FCT、参数估计、功率谱估计等数字信号处理的各个方面,如图 1.7 所示。图 1.8 和图 1.9 所示分别是 MathWorks 公司提供的 Power System Blockset 和 Communications

Page 32: Matlab Simulink

第 1章 MATLAB产品的体系结构 25

Blockset。Blocksets是 Simulink基本功能的扩展,在 Simulink Library Browser中可以看到已安装的所有模块库。基于 MATLAB 产品的第三方厂商也可以开发自己的模块库,如图1.10所示。

图 1.7 DSP模块库

图 1.8 电力系统模块库

图 1.9 通信模块库

Page 33: Matlab Simulink

从Matlab/Simulink模型到代码实现 26

图 1.10 已安装的所有 Simulink模块库

Real-Time Workshop(RTW)

Real-Time Workshop(RTW)是基于 Simulink 的目标代码生成工具。通过 RTW,用户可由 Simulink模型生成面向不同目标的实现代码。RTW支持的目标如图 1.11所示。

图 1.11 Real-Time Workshop支持的目标

删除的内容: .

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 34: Matlab Simulink

第 1章 MATLAB产品的体系结构 27

Real-Time Workshop 生成的代码可以用于实现快速仿真、快速原型及产品的实时 实现。

Stateflow

Stateflow 是基于 Simulink 的有限状态机建模工具,主要用于实现由有限个状态构成的控制逻辑和管理逻辑。一个典型的有限状态机的例子是上海地铁出入口处的转门,这个

设备可看作是由一个简单的有限状态机来管理的。图 1.12显示了这个有限状态机。

图 1.12 有限状态机:上海地铁出入口处的转门

这个转门有两个状态:Locked(上锁)和 Unlocked(开锁)。当转门锁上时,乘客可以在它的控制槽中插入一张地铁票,如果地铁票有效,转门就会自动开锁,转移到开锁

的状态,这个人就可以通过。图 1.12 中箭头指示状态的转移,它描述了转门从一种状态迁移到另一种状态的情形。

转移的标签文本被一个斜线分成两部分:左面部分是触发转移的事件名和转移发生的

条件,右面部分是转移被触发后所执行的动作的名称。如果转门处于 Locked 状态,并且发生了插入地铁票的事件且地铁票是有效的,那么转门就会转移到 Unlocked 状态,并且执行开锁的动作。如果转门处于 Unlocked 状态,并且发生了乘客通过的事件,转门就会转移到 Locked状态,并且执行上锁的动作。图 1.12还定义了 Locked为转门的默认状态,即转门开始工作时处于上锁状态,这是实际情况的真实反映。

用 Stateflow 搭建的有限状态机模型框图和 Simulink 是高度集成的,用户可以在该框图和 Simulink之间交换数据。

Stateflow Coder

Stateflow Coder可以将 Stateflow搭建的有限状态机模型单独地转成 C代码,用户也可以集成自己手写的 C代码。

用户通常要用 MATLAB Toolbox 结合各种工具箱来开发自己的算法;用 Simulink 基

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 35: Matlab Simulink

从Matlab/Simulink模型到代码实现 28

本环境,结合各种 Blocksets 和 Stateflow 实现系统建模。Matlab 和 Simulink 是高度集成的,相互间可以传递数据,即 Matlab 可为 Simulink 提供仿真数据,Simulink 也可产生数据,供Matlab来处理。

1.3 使用MATLAB工具进行产品开发的流程

使用MATLAB工具进行产品开发的流程如图 1.13所示。

图 1.13 使用MATLAB工具进行产品开发的流程

用户使用 Matlab 来开发和分析自己的算法,包括集成自己的 C 语言算法。算法完成之后,要将它集成到整个系统中来进行系统级的设计和仿真。如果仿真结果不符合系统要

求,则需要修改系统模型,或是回到 Matlab 中修改算法。如此不断地迭代,直到满足系统要求为止。在 Simulink中,用户既可以设计和测试整个系统,也可以仿真系统组件接口之间的相互作用,如测试模拟/混合信号、DSP 与控制逻辑之间的相互作用、优化性能、权衡组件的性能和代价。

Simulink 的思想是在系统的设计初期做尽可能多的测试,这样,在产品设计初期尽可能地发现设计中的错误,降低风险,缩短产品上市时间,有利于用户取得竞争优势。一旦

Simulink模型符合系统要求,用户可通过 Real-Time Workshop生成面向不同目标的代码,例如面向 TI DSP/CCS IDE的 C代码、面向WindRiver VxWorks/Tornado的 C代码。Real-Time Workshop支持的目标代码如图 1.11 所示。用户也可以通过 Xilinx 和 MathWorks 公司联合开发的基于 Matlab/Simulink的工具包 System Generator for Simulink将 Simulink模型生成面向 Xilinx FPGA的 VHDL代码,或者通过 Altera和 MathWorks公司联合开发的

删除的内容: 比

删除的内容: 。

Page 36: Matlab Simulink

第 1章 MATLAB产品的体系结构 29

基于 Matlab/Simulink 的工具包 DSPBuilder 将 Simulink 模型生成面向 Altera FPGA 的VHDL代码。

图 1.13所示是用 MATLAB工具来进行产品的研发、设计和实现的流程。MathWorks公司的MATLAB产品为客户的产品研发提供了自上而下的解决方案,可以帮助用户:

实现自上而下的设计; 获得清晰的系统设计规范; 仿真系统组件间的行为; 设计和测试整个系统; 尽早发现设计中的瑕疵; 降低设计风险缩短产品上市时间。

1.4 MATLAB的安装

MATLAB R12.1 的安装盘是两张光盘,一张为 Product,主要是 MATLAB 软件模块;另一张为 Document,主要是 MATLAB 的帮助文档。MATLAB 的安装过程如下(以Windows操作系统平台为例):

步骤 1. 在光驱(假定盘符为 F:)中插入 MATLAB R12.1的 Product盘,或通过网络共享MATLAB R12.1的 Product盘,假定共享名为\\YoungSun\matlabr12p1。

步骤 2. 如果没有自动弹出如图 1.14 所示的界面,在资源管理器中用鼠标双击F:\setup.exe 或者\\YoungSun\matlabr12p1\setup.exe,将弹出如图 1.14 所示的界面,提示将安装MATLAB产品。

步骤 3. 若要查看有关如何安装的帮助文档,单击 Help按钮,将弹出如图 1.15所示的帮助界面,在此可以查看相关主题。若要退出安装,单击 Cancel 按钮,将弹出如图 1.16所示的界面,在图 1.16中单击 Yes按钮,退出安装过程,单击 No按钮,继续安装过程。若要继续安装过程,单击 Next按钮,将进入如图 1.17所示界面。

步骤 4. 在图 1.17中输入购买 MATLAB产品时 MathWorks公司发的 Personal License Password(PLP)。如果没有得到 PLP,请同 MATLAB 代理商联系。当然,也可以单击Get my PLP按钮,通过 Internet来索取自己的 PLP信息。此时需要输入用户在MathWorks公司客户数据库中注册的 Last Name 和 Access Number 信息,若不知道这些信息,请与MATLAB 代理商联系。在填写正确的 PLP 后,单击 Next 按钮,就进入如图 1.18 所示的安装界面。

删除的内容: 上面

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 请

删除的内容: 你

删除的内容: 请

删除的内容: 请

删除的内容: 请

删除的内容: (

删除的内容: )

删除的内容: 同时

删除的内容: 网

删除的内容: 你的

Page 37: Matlab Simulink

从Matlab/Simulink模型到代码实现 30

图 1.14 Welcome to The MathWorks Installer

图 1.15 MATLAB安装指南

图 1.16 退出安装对话框

Page 38: Matlab Simulink

第 1章 MATLAB产品的体系结构 31

图 1.17 Personal License Password

图 1.18 License Agreement

步骤 5. 图 1.18显示的是 MathWorks公司的软件许可证协议,只有单击 Yes按钮,表示同意此协议,才能继续安装过程,进入如图 1.19所示的界面。

步骤 6. 在如图 1.19所示界面中输入用户名和公司名,然后单击 Next按钮,继续安装过程,进入图 1.20 所示界面。单击 Yes 按钮,安装程序将通过 Internet 检查相关MATLAB产品的更新和升级信息;单击 No按钮,进入图 1.21所示的安装界面。

删除的内容: 选择

删除的内容: 8

删除的内容: 19

删除的内容: 网

Page 39: Matlab Simulink

从Matlab/Simulink模型到代码实现 32

图 1.19 Customer Information

图 1.20 Check for Updates and New Releases

步骤 7. 在图 1.21所示的界面中,用户需要: 指定安装目录,目录名不能含有空格字符,所以不能将 MATLAB 安装到

Windows系统目录 Program Files中; 安装产品和对应的帮助文档,选择仅安装产品,还是仅安装帮助文档,或者两者

全部安装; 选择帮助文档的不同的语言版本;

带格式的: 项目符号和编号

Page 40: Matlab Simulink

第 1章 MATLAB产品的体系结构 33

图 1.21 Product List

选择想要安装的 MATLAB 产品模块和/或相应的帮助文档。只有已经购买了的(也即用户的 PLP 允许使用的)MATLAB 产品模块才会显示出来,并且默认选中。用户也可通过单击鼠标来选中或不选某个模块。值得注意的是某些模块之间

有一定的依赖关系,例如:MATLAB 模块是其他 MATLAB 产品的基础,要安装其他模块,必须要选中或目标目录中已安装了 MATLAB 模块。MATLAB 各个模块之间的相互关系,相信 MATLAB代理商会代为处理,所以对用户来讲,默认选择或是全选即可(如果磁盘空间足够的话)。在图 1.21 的右侧显示的是有效磁盘空间、MATLAB 产品需要的磁盘空间、MATLAB 帮助文档需要的磁盘空间和总共需要的磁盘空间信息。

单击 Next按钮开始安装,如图 1.22所示。当然,如果在图 1.21中指定的安装目录不存在,会提示创建此目录。

图 1.22 Installation Status

带格式的: 项目符号和编号

删除的内容: 22

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 41: Matlab Simulink

从Matlab/Simulink模型到代码实现 34

步骤 8. 在安装快要完成时会弹出如图 1.23所示的对话框,提示是否愿意将MATLAB软件和 MATLAB 文件类型相关联起来。然后安装过程将进入图 1.24 所示界面,若在图1.21所示界面中选择了安装 Real-Time Windows Target模块(否则直接进入图 1.25),将提示用户如何配置 Real-Time Windows Target,单击 Next按钮,进入图 1.25所示界面。

图 1.23 File Extension Warning

图 1.24 Product Configuration Notes

删除的内容: (

删除的内容: )

删除的内容: 它

Page 42: Matlab Simulink

第 1章 MATLAB产品的体系结构 35

步骤 9. 图 1.25所示意味着安装过程即将结束,用户可以选择启动 MATLAB,或者通过 Internet注册为MATLAB用户。

图 1.25 Installation Complete

安装完成之后,MATLAB安装目录中将包含如下文件和目录: 文本文件 license.txt,它是MATLAB软件的许可证协议; MATLAB执行文件的快捷方式; 如下的子目录:

\BIN\WIN32 包含MATLAB二进制文件和相关文件: LICENSE.DAT 客户端系统的 License文件 MATLAB.EXE MATLAB可执行文件 *.DLL,*.EXE,*.BAT 杂项文件

\DEMOS 包含MATLAB示例程序; \EXTERN 包含MATLAB外部接口的支持文件和一些例子程序:

\EXAMPLES MATLAB和 C、Fortran的接口程序示例 \INCLUDE MATLAB外部接口库的头文件 \LIB 编译外部接口程序时需要的库文件 \SRC 编译MEX文件时需要的 C源文件

\FLEXLM 包含 FLEXlm许可证管理器、许可证管理工具程序; \HELP 包含MATLAB帮助文件——HTML 文档和 PDF文档; \JA 包含MATLAB国际化文件; \JAVA 包含MATLAB Java文件; \NOTEBOOK 包含MATLAB Notebook;

删除的内容: :

Page 43: Matlab Simulink

从Matlab/Simulink模型到代码实现 36

\SYS 包含MATLAB工具和操作系统库: \GHOSTSCRIPT\BIN GhostScript执行文件 \GHOSTSCRIPT\FONTS PostScript 字体的 GhostScript版本 \GHOSTSCRIPT\PS_FILES PostScript初始化和配置文件 \PERL\WIN32 ActiveState Perl的完全版

\RTW Real-Time Workshop相关文件; \Simulink Simulink相关文件和 S-函数实例程序; \STATEFLOW Stateflow相关文件; \TOOLBOX 包含MATLAB产品工具箱:

\LOCAL 配置和查看本机Matlab环境的文件 \MATLAB

\AUDIO 声卡 I/O命令 \DATAFUN 数据分析和 Fourier变换函数 \DATATYPES 有关数据类型和结构的函数 \DEMOS 示例程序 \ELFUN 基本的数学函数 \ELMAT 基本的矩阵操作函数 \FUNFUN 函数的函数 \GENERAL 常用命令 \GRAPH2D 二维图形函数 \GRAPH3D 三维图形函数 \GRAPHICS 常用图形命令 \IOFUN 低级文件 I/O函数 \LANG m语言结构和调试命令 \MATFUN 矩阵函数——数值线性代数方法 \OPS 操作符和特殊字符 \POLYFUN 多项式和插值函数 \SPARFUN 稀疏矩阵函数 \SPECFUN 特殊数学函数 \SPECGRAPH 特殊图形函数 \STRFUN 字符串函数 \TIMEFUN 时间、日期和日历函数 \UITOOLS 用户界面函数 \VERCTRL 版本控制函数 \WINFUN Window函数

其他工具箱和模块库目录 \UNINSTALL 包含MATLAB Uninstaller程序; \WORK 默认的初始当前目录。

删除的内容: Matalb

删除的内容:

删除的内容:

删除的内容: —

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 44: Matlab Simulink

第 1章 MATLAB产品的体系结构 37

当然,在各位的安装目录中不一定包含上述所有目录。

1.5 MATLAB的工作环境

在安装 MATLAB的过程中,如果遇到问题,请参阅 MATLAB Product盘根目录下的PDF文档 install_guide.pdf,在文档中可以查到安装 MATLAB所需的系统软硬件要求;登录网址 http://www.mathworks.com 的产品区可以查到有关系统要求的最新信息。安装好MATLAB 后,在 Windows 桌面上会产生一个 MATLAB 图标,双击该图标即会弹出MATLAB 默认的工作界面,如图 1.26 所示 (为叙述方便,本书后续章节均假定MATLAB R12.1 的安装目录%MATLABROOT%为 d:\MATLAB6p1,MATLAB6p1 为MATLAB R12.1的默认安装目录名,意思是MATLAB 6 plus 1,即MATLAB 6.1)。

在MATLAB的命令窗口运行 matlabroot命令,可查看到MATLAB的安装路径。 >> matlabroot ans = D:\MATLAB6p1

图 1.26 MATLAB默认的工作界面

删除的内容: (

删除的内容: )

Page 45: Matlab Simulink

从Matlab/Simulink模型到代码实现 38

默认的MATLAB工作界面除了菜单和工具条之外,主要包括如下几部分: Command Window,即MATLAB的命令窗口 在该窗口中,可以运行 MATLAB 的各种命令,包括 MATLAB 内建函数、m 文件脚

本、m文件函数等。 Launch Pad

Launch Pad是查询 MATLAB各模块帮助文档、示例程序和启动相关工具命令的快捷面板。

Workspace,即MATLAB工作空间 MATLAB工作空间对应计算机中的一条内存,在 MATLAB命令窗口生成的变量几乎

都存储在该工作空间中。 Command History,即MATLAB命令的历史记录窗口 在MATLAB命令窗口输入的命令会记录在此窗口,以供再次使用或者生成 m文件。

Current Diretory,即MATLAB的当前工作目录 当前工作目录是 MATLAB中非常重要的选项,默认情况下,MATLAB将生成的代码

或数据文件保存在当前目录中。 由图 1.26 可以看出,此时 MATLAB 的当前目录为 d:\MATLAB6p1\work。如果想让

MATLAB 启动后的当前工作路径自动设置为其他目录,例如 e:\material\study,请打开桌面上 MATLAB 快捷方式的属性对话框,如图 1.27 所示。修改其中的起始位置为e:\material\study,然后双击该快捷方式重新启动 MATLAB即可。如果想让启动 MATLAB后的默认工作界面类似于 MATLAB 5.3,请打开桌面上 MATLAB 快捷方式的属性对话框,修改其中的目标为 D:\MATLAB6p1\bin\win32\matlab.exe /nodesktop,如图 1.28所示,然后双击该快捷方式重新启动 MATLAB,即可弹出如图 1.29 所示的 MATLAB 工作 界面。

图 1.27 MATLAB快捷方式的属性对话框

Page 46: Matlab Simulink

第 1章 MATLAB产品的体系结构 39

图 1.28 MATLAB快捷方式的属性对话框

图 1.29 类似于MATLAB 5.3的工作界面

MATLAB 启动过程中执行的最后一个文件为%MATLABROOT%\toolbox\local\ matlabrc.m。如果想在 MATLAB 启动的过程中修改某些对象的属性,或者作一些设置,或者修改默认的提示信息,请用文本编辑器修改 matlabrc.m,或者在目录%MATLABROOT%\toolbox\local 中创建一个 startup.m 文件,因为在 matlabrc 执行的过程中会检测 startup.m是否存在,如果存在则执行它,如图 1.30所示。例如,如图 1.31所示修改 matlabrc.m后,启动MATLAB显示的提示信息如图 1.32所示。

删除的内容:

Page 47: Matlab Simulink

从Matlab/Simulink模型到代码实现 40

图 1.30 %MATLABROOT%\toolbox\local\matlabrc.m

图 1.31 修改%MATLABROOT%\toolbox\local\matlabrc.m

要退出 MATLAB 工作界面,只需在 MATLAB 命令窗口运行 exit 或者 quit 命令即可。如果在目录%MATLABROOT%\toolbox\local 中存在 finish.m 脚本文件(当然,finish.m 也可以是不带参数的函数文件,但最好是脚本文件。在目录%MATLABROOT%\ toolbox\local中,有两个 m脚本文件 finishsav.m和 finishdlg.m可作为用户创建 finish.m文件的模板),则在使用 exit或者 quit命令退出 MATLAB时,将执行该文件。可以在该文件中使用 save命令,在退出MATLAB工作界面时保存MATLAB工作空间中的变量。

删除的内容: (

删除的内容: )

Page 48: Matlab Simulink

第 1章 MATLAB产品的体系结构 41

图 1.32 提示信息被修改后的MATLAB启动界面

可以通过在目录%MATLABROOT%\toolbox\local 中修改或者创建 matlabrc.m、startup.m 和 finish.m 文件来定制启动或者退出 MATLAB 时所要执行的命令,如图 1.33 所示。

图 1.33 目录%MATLABROOT%\toolbox\local中的文件

例如,对于特定的计算机系统,如对于 PIII600+Windows 2000+1024X768的显示器分辨率+32 位真彩色的系统,可以注释掉默认 matlabrc.m 中的某些部分(例如以下所列程序的阴影部分),以使MATLAB的启动速度更快。

%MATLABRC Master startup M-file. % MATLABRC is automatically executed by MATLAB during startup. % It establishes the MATLAB path, sets the default figure size, % and sets a few uicontrol defaults.

删除的内容: 我们

删除的内容: +

Page 49: Matlab Simulink

从Matlab/Simulink模型到代码实现 42

% % On multi-user or networked systems, the system manager can put % any messages, definitions, etc. that apply to all users here. % % MATLABRC also invokes a STARTUP command if the file 'startup.m' % exists on the MATLAB path. % Copyright 1984-2000 The MathWorks, Inc. % $Revision: 1.142 $ $Date: 2001/04/27 17:29:20 $ % Set up path. if exist('pathdef','file') ptime0 = []; if exist([matlabroot '/toolbox/local/toolbox_cache.mat'], 'file') &... strcmpi(system_dependent('getpref','GeneralUseToolboxCache'),... 'BTrue') disp(' MATLAB Toolbox Path being initialized using Toolbox Path Cache.') if strcmpi(system_dependent('getpref','GeneralUseToolboxCacheDiag'),... 'BTrue') ptime0 = clock; end end matlabpath(pathdef); if ~isempty(ptime0) disp(sprintf(' MATLAB Path initialized in %.2f seconds.', etime(clock, ptime0))); end end % Display helpful hints. % If the MATLAB Desktop is not running, then use the old message, since % the Help menu will be unavailable. if usejava('Desktop') disp(' ') disp(' To get started, select "MATLAB Help" from the Help menu.') disp(' ') else disp(' ') disp(' To get started, type one of these: helpwin, helpdesk, or demo.') disp(' For product information, visit www.mathworks.com.') disp(' ') end

Page 50: Matlab Simulink

第 1章 MATLAB产品的体系结构 43

% Set default warning level to WARNING BACKTRACE. See help warning. warning backtrace % Enable MEX-file backwards compatibility mode feature('MEXFileCompat',1); % The RecursionLimit forces MATLAB to throw an error when the specified % function call depth is hit. This protects you from blowing your stack % frame (which can cause MATLAB and/or your computer to crash). Set the % value to inf if you don't want this protection. cname = computer; if strncmp(cname,'GLNX',4) set(0,'RecursionLimit',100) elseif strncmp(cname,'ALPHA',5) set(0,'RecursionLimit',200) else set(0,'RecursionLimit',500) end % Set the default figure position, in pixels. % On small screens, make figure smaller, with same aspect ratio. screen = get(0, 'ScreenSize'); width = screen(3); height = screen(4); if screen(3:4) ~= [1 1] % don't change default if screensize == [1 1] if all(cname(1:2) == 'PC') if height >= 500 mwwidth = 560; mwheight = 420; if(get(0,'screenpixelsperinch') == 116) % large fonts mwwidth = mwwidth * 1.2; mwheight = mwheight * 1.2; end else mwwidth = 560; mwheight = 375; end left = (width - mwwidth)/2; bottom = height - mwheight -90; else if height > 768 mwwidth = 560; mwheight = 420; left = (width-mwwidth)/2; bottom = height-mwheight-90;

Page 51: Matlab Simulink

从Matlab/Simulink模型到代码实现 44

else % for screens that aren't so high mwwidth = 512; mwheight = 384; left = (width-mwwidth)/2; bottom = height-mwheight-76; end end rect = [ left bottom mwwidth mwheight ]; set(0, 'defaultfigureposition',rect); end colordef(0,'white') % Set up for white defaults % Make uicontrols, uimenus and lines look better on monochrome displays. if get(0,'ScreenDepth')==1, set(0,'DefaultUIControlBackgroundColor','white'); set(0,'DefaultAxesLineStyleOrder','-|--|:|-.'); set(0,'DefaultAxesColorOrder',[0 0 0]); set(0,'DefaultFigureColor',[1 1 1]); end %% Uncomment the next line to use Letter paper and inches %defaultpaper = 'usletter'; defaultunits = 'inches'; %% Uncomment the next line to use A4 paper and centimeters %defaultpaper = 'A4'; defaultunits = 'centimeters'; %% If neither of the above lines are uncommented then guess %% which papertype and paperunits to use based on ISO 3166 country code. if usejava('jvm') & ~exist('defaultpaper','var') if any(strncmpi(char(java.util.Locale.getDefault.getCountry), ... {'gb','uk','fr','de','es','ch','nl','it','ru',... 'jp','kr','tw','cn'},2)) defaultpaper = 'A4'; defaultunits = 'centimeters'; end end %% Set the default if requested if exist('defaultpaper','var') & exist('defaultunits','var') % Handle Graphics defaults set(0,'DefaultFigurePaperType',defaultpaper); set(0,'DefaultFigurePaperUnits',defaultunits); % Simulink defaults

带格式的

删除的内容: 底色

Page 52: Matlab Simulink

第 1章 MATLAB产品的体系结构 45

set_param(0,'PaperType',defaultpaper); set_param(0,'PaperUnits',defaultunits); end %% For Japan, set default fonts lang = lower(get(0,'language')); if strncmp(lang, 'ja', 2) if strncmp(cname,'PC',2) set(0,'defaultuicontrolfontname',get(0,'factoryuicontrolfontname')); set(0,'defaultuicontrolfontsize',get(0,'factoryuicontrolfontsize')); set(0,'defaultaxesfontname',get(0,'factoryuicontrolfontname')); set(0,'defaultaxesfontsize',get(0,'factoryuicontrolfontsize')); set(0,'defaulttextfontname',get(0,'factoryuicontrolfontname')); set(0,'defaulttextfontsize',get(0,'factoryuicontrolfontsize')); %% You can control the fixed-width font %% with the following command % set(0,'fixedwidthfontname','MS Gothic'); end end %% For the 'edit' command, to use an editor defined in the $EDITOR %% environment variable, the following line should be uncommented %% (UNIX only) %system_dependent('builtinEditor','off') %% CONTROL OVER FIGURE TOOLBARS: %% The new figure toolbars are visible when appropriate, %% by default, but that behavior is controllable %% by users. By default, they're visible in figures %% whose MenuBar property is 'figure', when there are %% no uicontrols present in the figure. This behavior %% is selected by the figure ToolBar property being %% set to its default value of 'auto'. %% to have toolbars always on, uncomment this: %set(0,'defaultfiguretoolbar','figure') %% to have toolbars always off, uncomment this: %set(0,'defaultfiguretoolbar','none') %% init java prefs system if java is present

Page 53: Matlab Simulink

从Matlab/Simulink模型到代码实现 46

if usejava('mwt') initprefs end %% Text-based preferences NumericFormat = system_dependent('getpref','GeneralNumFormat'); if ~isempty(NumericFormat) eval(['format ' NumericFormat(2:end)]); end NumericDisplay = system_dependent('getpref','GeneralNumDisplay'); if ~isempty(NumericDisplay) format(NumericDisplay(2:end)); end MaxTab = system_dependent('getpref','CommandWindowMaxCompletions'); if ~isempty(MaxTab) & MaxTab(1) == 'I' EnableTab = system_dependent('getpref','CommandWindowTabCompletion'); TabSetting = strcmpi(EnableTab,'BTrue') * str2num(MaxTab(2:end)); system_dependent('TabCompletion', TabSetting); end if (strcmpi(system_dependent('getpref','GeneralEightyColumns'),'BTrue')) feature('EightyColumns',1); end % Clean up workspace. clear % Execute startup M-file, if it exists. if (exist('startup','file') == 2) startup end % Defer echo until startup is complete if strcmpi(system_dependent('getpref','GeneralEchoOn'),'BTrue') echo on end

删除的内容: %MATLABRC Master startup M-file.% MATLABRC is automatically executed by MATLAB during startup.% It establishes the MATLAB path, sets the default figure size,% and sets a few uicontrol defaults.%% On multi-user or networked systems, the system manager can put% any messages, definitions, etc. that apply to all users here.%% MATLABRC also invokes a STARTUP command if the file 'startup.m'% exists on the MATLAB path.

% Copyright 1984-2000 The MathWorks, Inc.% $Revision: 1.142 $ $Date: 2001/04/27 17:29:20 $

% Set up path.if exist('pathdef','file') ptime0 = []; if exist([matlabroot '/toolbox/local/toolbox_cache.mat'], 'file') &... strcmpi(system_dependent('getpref','GeneralUseToolboxCache'),... 'BTrue') disp(' MATLAB Toolbox Path being initialized using Toolbox Path Cache.') if strcmpi(system_dependent('getpref','GeneralUseToolboxCacheDiag'),... 'BTrue') ptime0 = clock; end end matlabpath(pathdef); if ~isempty(ptime0) disp(sprintf(' MATLAB Path initialized in %.2f seconds.', etime(clock, ptime0)));... [1]

Page 54: Matlab Simulink

页 46: [1] 删除的内容 fcr 2002-9-16 17:38:00

%MATLABRC Master startup M-file. % MATLABRC is automatically executed by MATLAB during startup. % It establishes the MATLAB path, sets the default figure size, % and sets a few uicontrol defaults. % % On multi-user or networked systems, the system manager can put % any messages, definitions, etc. that apply to all users here. % % MATLABRC also invokes a STARTUP command if the file 'startup.m' % exists on the MATLAB path. % Copyright 1984-2000 The MathWorks, Inc. % $Revision: 1.142 $ $Date: 2001/04/27 17:29:20 $ % Set up path. if exist('pathdef','file') ptime0 = []; if exist([matlabroot '/toolbox/local/toolbox_cache.mat'], 'file') &... strcmpi(system_dependent('getpref','GeneralUseToolboxCache'),... 'BTrue') disp(' MATLAB Toolbox Path being initialized using Toolbox Path

Cache.') if strcmpi(system_dependent('getpref','GeneralUseToolboxCacheDiag'),... 'BTrue') ptime0 = clock; end end matlabpath(pathdef); if ~isempty(ptime0) disp(sprintf(' MATLAB Path initialized in %.2f seconds.',

etime(clock, ptime0))); end end % Display helpful hints. % If the MATLAB Desktop is not running, then use the old message, since % the Help menu will be unavailable. if usejava('Desktop') disp(' ') disp(' To get started, select "MATLAB Help" from the Help menu.') disp(' ') else disp(' ') disp(' To get started, type one of these: helpwin, helpdesk, or

demo.') disp(' For product information, visit www.mathworks.com.') disp(' ') end

Page 55: Matlab Simulink

% Set default warning level to WARNING BACKTRACE. See help warning. warning backtrace % Enable MEX-file backwards compatibility mode feature('MEXFileCompat',1); % The RecursionLimit forces MATLAB to throw an error when the specified % function call depth is hit. This protects you from blowing your stack % frame (which can cause MATLAB and/or your computer to crash). Set the % value to inf if you don't want this protection. cname = computer; if strncmp(cname,'GLNX',4) set(0,'RecursionLimit',100) elseif strncmp(cname,'ALPHA',5) set(0,'RecursionLimit',200) else set(0,'RecursionLimit',500) end % Set the default figure position, in pixels. % On small screens, make figure smaller, with same aspect ratio. screen = get(0, 'ScreenSize'); width = screen(3); height = screen(4); if screen(3:4) ~= [1 1] % don't change default if screensize == [1 1] if all(cname(1:2) == 'PC') if height >= 500 mwwidth = 560; mwheight = 420; if(get(0,'screenpixelsperinch') == 116) % large fonts mwwidth = mwwidth * 1.2; mwheight = mwheight * 1.2; end else mwwidth = 560; mwheight = 375; end left = (width - mwwidth)/2; bottom = height - mwheight -90; else if height > 768 mwwidth = 560; mwheight = 420; left = (width-mwwidth)/2; bottom = height-mwheight-90; else % for screens that aren't so high mwwidth = 512; mwheight = 384; left = (width-mwwidth)/2; bottom = height-mwheight-76; end end

Page 56: Matlab Simulink

rect = [ left bottom mwwidth mwheight ]; set(0, 'defaultfigureposition',rect); end colordef(0,'white') % Set up for white defaults % Make uicontrols, uimenus and lines look better on monochrome displays. if get(0,'ScreenDepth')==1, set(0,'DefaultUIControlBackgroundColor','white'); set(0,'DefaultAxesLineStyleOrder','-|--|:|-.'); set(0,'DefaultAxesColorOrder',[0 0 0]); set(0,'DefaultFigureColor',[1 1 1]); end %% Uncomment the next line to use Letter paper and inches %defaultpaper = 'usletter'; defaultunits = 'inches'; %% Uncomment the next line to use A4 paper and centimeters %defaultpaper = 'A4'; defaultunits = 'centimeters'; %% If neither of the above lines are uncommented then guess %% which papertype and paperunits to use based on ISO 3166 country code. if usejava('jvm') & ~exist('defaultpaper','var') if any(strncmpi(char(java.util.Locale.getDefault.getCountry), ... {'gb','uk','fr','de','es','ch','nl','it','ru',... 'jp','kr','tw','cn'},2)) defaultpaper = 'A4'; defaultunits = 'centimeters'; end end %% Set the default if requested if exist('defaultpaper','var') & exist('defaultunits','var') % Handle Graphics defaults set(0,'DefaultFigurePaperType',defaultpaper); set(0,'DefaultFigurePaperUnits',defaultunits); % Simulink defaults set_param(0,'PaperType',defaultpaper); set_param(0,'PaperUnits',defaultunits); end %% For Japan, set default fonts lang = lower(get(0,'language')); if strncmp(lang, 'ja', 2) if strncmp(cname,'PC',2) set(0,'defaultuicontrolfontname',get(0,'factoryuicontrolfontname')); set(0,'defaultuicontrolfontsize',get(0,'factoryuicontrolfontsize')); set(0,'defaultaxesfontname',get(0,'factoryuicontrolfontname')); set(0,'defaultaxesfontsize',get(0,'factoryuicontrolfontsize')); set(0,'defaulttextfontname',get(0,'factoryuicontrolfontname'));

Page 57: Matlab Simulink

set(0,'defaulttextfontsize',get(0,'factoryuicontrolfontsize')); %% You can control the fixed-width font %% with the following command % set(0,'fixedwidthfontname','MS Gothic'); end end %% For the 'edit' command, to use an editor defined in the $EDITOR %% environment variable, the following line should be uncommented %% (UNIX only) %system_dependent('builtinEditor','off') %% CONTROL OVER FIGURE TOOLBARS: %% The new figure toolbars are visible when appropriate, %% by default, but that behavior is controllable %% by users. By default, they're visible in figures %% whose MenuBar property is 'figure', when there are %% no uicontrols present in the figure. This behavior %% is selected by the figure ToolBar property being %% set to its default value of 'auto'. %% to have toolbars always on, uncomment this: %set(0,'defaultfiguretoolbar','figure') %% to have toolbars always off, uncomment this: %set(0,'defaultfiguretoolbar','none') %% init java prefs system if java is present if usejava('mwt') initprefs end %% Text-based preferences NumericFormat = system_dependent('getpref','GeneralNumFormat'); if ~isempty(NumericFormat) eval(['format ' NumericFormat(2:end)]); end NumericDisplay = system_dependent('getpref','GeneralNumDisplay'); if ~isempty(NumericDisplay) format(NumericDisplay(2:end)); end MaxTab = system_dependent('getpref','CommandWindowMaxCompletions'); if ~isempty(MaxTab) & MaxTab(1) == 'I' EnableTab = system_dependent('getpref','CommandWindowTabCompletion'); TabSetting = strcmpi(EnableTab,'BTrue') * str2num(MaxTab(2:end)); system_dependent('TabCompletion', TabSetting); end if (strcmpi(system_dependent('getpref','GeneralEightyColumns'),'BTrue'))

Page 58: Matlab Simulink

feature('EightyColumns',1); end % Clean up workspace. clear % Execute startup M-file, if it exists. if (exist('startup','file') == 2) startup end % Defer echo until startup is complete if strcmpi(system_dependent('getpref','GeneralEchoOn'),'BTrue') echo on end

Page 59: Matlab Simulink

第 2章 算 法 开 发

MathWorks 公司一直致力于提高工程师与科研人员的研发效率,加速产品的开发过程。为了达到这个目标,MathWorks公司的MATLAB产品向用户提供了:

Matlab:具有世界领先水准的工程计算、算法开发和数据可视化的软件; Simulink:交互式的用于系统级设计和仿真的模块框图环境。 本章介绍Matlab,在第 4章中将介绍 Simulink。

2.1 数学方式的程序开发

使用 Matlab进行算法开发就像平时书写数学表达式一样,在很多关于 MATLAB编程的参考书中都有论述。一旦算法经过编写、调试、仿真和优化,MATLAB Compiler 和MATLAB C/C++ Math Library 及许多第三方的工具,如 MATCOM,就提供了将用户的Matlab应用自动转换成 C、C++代码和独立应用的手段。

对于信号处理、控制系统设计、图像处理和其他众多的应用领域,MATLAB 提供了一系列工具箱函数,帮助工程师、科研人员把主要的精力放在算法的构思,而不是编程

上。因为 MATLAB提供了一个类似于写数学公式的高级语言,即众所周知的 m语言的编程环境。在 Matlab 环境中,用户很容易实现自己构思的算法,很容易进行数据的分析和可视化,而不需要像 C语言那样花大量的时间来编程。通过一个简单的例子,可以很容易看出这一点。

【例 1】下面这个例子是要解一个联立方程组:

⎪⎩

⎪⎨

=++−=+−

=++−

83523153213

5.232215.1

xxxxxx

xxx

用Matlab来解这个方程组,只需在MATLAB命令窗口中,依次输入如下命令: >> A=[-1.5 1 2;3 -1 1;-1 3 5]; >> b=[2.5;5;8]; >> x=A\b x =

删除的内容: 多

删除的内容: 象

Page 60: Matlab Simulink

从 M atlab/Sim ulink模型到代码实现

0.7500 -0.6250

2.1250

即可求得方程组的解。 用 C语言(使用 Microsoft Visual C/C++ version 6.0编译环境)编写的一个求解算法

如下: //solver.c //used to solve A*X=b, //where A=[-1.5 1 2;3 -1 1;-1 3 5], b=[2.5;5;8]. #include "stdio.h" void main() { double A[3][3]={{-1.5,1,2},{3,-1,1},{-1,3,5}}; double b[3]={2.5,5,8}; double invA[3][3],X[3]; int i; // the determinant of A double deltaA=A[0][0]*A[1][1]*A[2][2]+A[1][0]*A[2][1]*A[0][2]+

A[2][0]*A[1][2]*A[0][1]-(A[0][2]*A[1][1]*A[2][0]+ A[0][0]*A[2][1]*A[1][2]+A[0][1]*A[1][0]*A[2][2]);

//the inversion of A invA[0][0]=1/deltaA*(A[1][1]*A[2][2]-A[1][2]*A[2][1]); invA[1][0]=-1/deltaA*(A[1][0]*A[2][2]-A[1][2]*A[2][0]); invA[2][0]=1/deltaA*(A[1][0]*A[2][1]-A[1][1]*A[2][0]); invA[0][1]=-1/deltaA*(A[0][1]*A[2][2]-A[2][1]*A[0][2]); invA[1][1]=1/deltaA*(A[0][0]*A[2][2]-A[2][0]*A[0][2]); invA[2][1]=-1/deltaA*(A[0][0]*A[2][1]-A[0][1]*A[2][0]); invA[0][2]=1/deltaA*(A[0][1]*A[1][2]-A[0][2]*A[1][1]); invA[1][2]=-1/deltaA*(A[0][0]*A[1][2]-A[0][2]*A[1][0]); invA[2][2]=1/deltaA*(A[0][0]*A[1][1]-A[0][1]*A[1][0]); printf("The solution X is\n"); for(i=0;i<3;i++) { X[i]=invA[i][0]*b[0]+invA[i][1]*b[1]+invA[i][2]*b[2]; printf("%f\n",X[i]); }

删除的内容: (

删除的内容: )

删除的内容:

Page 61: Matlab Simulink

第 2章 算法开发 49

}

对比 Matlab 的求解算法和 C 语言求解算法,Matlab 是如何帮助科研人员减轻编程

负担的就显而易见了。如果 A是任意的 m×n维矩阵,b是任意的 m×p维矩阵,X是待求的 n×p 维矩阵,则上述的 C 程序需要做很大的改动,编程难度和工作量将大大增加,而 m 语言程序基本不需要改变。m 语言的源程序有两种格式:脚本 m 文件和函数m文件。

2.2 脚本 m文件

脚本 m 文件是用 m 语言写成的、MATLAB 命令窗口中可以执行的命令的批处理文本,即按照 m语言语法写成的 MATLAB命令的集合。【例 1】中求解方程组的脚本 m文件可以写成:

%solver.m %used to solve A*X=b %where A=[-1.5 1 2;3 -1 1;-1 3 5], b=[2.5;5;8]. A=[-1.5 1 2;3 -1 1;-1 3 5]; b=[2.5;5;8]; X=A\b

以%开头的行,在 m 语言中表示注释行。将上述脚本 m 文件保存为 solver.m 后,在

MATLAB的命令窗口中,执行 solver命令,即可求出方程组的解: >> solver X = 0.7500 -0.6250

2.1250

执行脚本 m文件时,生成的变量保存在 MATLAB的工作空间。例如执行 solver命令后,在 MATLAB的命令窗口执行 whos命令,可以看到在 MATLAB的工作空间中生成了三个变量 A、b和 X:

>> whos

删除的内容: 地

删除的内容: 工程师及

删除的内容: 我们的

Page 62: Matlab Simulink

从Matlab/Simulink模型到代码实现 50

Name Size Bytes Class A 3×3 72 double array X 3×1 24 double array b 3×1 24 double array Grand total is 15 elements using 120 bytes

2.3 函数 m文件

函数 m文件是由 function关键字定义的MATLAB函数,它的编写格式如图 2.1所示。

图 2.1 MATLAB函数文件格式

关键字

定义 MATLAB 函数的关键字是 function,它是 MATLAB 的一个保留字,不能用作MATLAB变量名或者函数名:

>> function=100 ??? function=100 | Error: Illegal use of reserved keyword "function". >> which function function is a built-in function.

删除的内容:

删除的内容:

Page 63: Matlab Simulink

第 2章 算法开发 51

函数名

函数 m 文件的文件名一般应与函数名相同,如果不相同,则以文件名标识该函数。也就是说,如果 m 函数的函数名和文件名不相同,MATLAB 命令窗口或者其他函数要通过文件名来调用该函数,而不是用函数名。函数 m 文件的文件名要以字母开头,由字母、数字、下划线组成,中间不能有空格,且长度不超过 31 个字符。函数名是以字母开头,由字母、数字、下划线组成的字符串,中间不能有空格,长度不宜超过 31 个字符。请用户尽量让 m函数的函数名和它的文件名一致,以免混乱。

输入变量

输入变量是用()括起来的 m 函数的输入形参,多个输入变量之间用逗号分开,m函数可以定义可变个数的输入变量。

输出变量

输出变量是用 [] 括起来的 m 函数的返回形参,多个输出变量之间用逗号分开,m 函数可以定义可变个数的输出变量。

在线帮助

在线帮助是执行 help或者 helpwin命令后显示的关于该函数的帮助文档。在线帮助应该从 m 函数定义行的下一行开始,在线帮助和 m 函数定义行之间可以有空行,但在线帮助的各行之间不应有空行,因为空行之后的注释不再是在线帮助。对图 2.1所示的 m函数使用 help和 helpwin命令:

>> help mymean MYMEAN Average or mean value. For vectors, MYMEAN(X) is the mean value. For matrices, MYMEAN(X) is a row vector containing the mean value of each column. >> helpwin mymean

运行结果如图 2.2所示。 将 mymean.m改写成如图 2.3所示,再使用 help和 helpwin命令,得到的是不一样的

结果: >> help mymean

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: []

Page 64: Matlab Simulink

从Matlab/Simulink模型到代码实现 52

MYMEAN Average or mean value. For vectors, MYMEAN(X) is the mean value. For matrices, MYMEAN(X) is a row vector >> helpwin mymean

结果如图 2.4所示。

图 2.2 输入 helpwin mymean的运行结果

图 2.3 在线帮助各行之间不应有空格

图 2.4 修改 mymean.m后输入 helpwin mymean的运行结果

删除的内容:

删除的内容:

删除的内容:

删除的内容: 将 mymean.m改写成如图 2.3所示,再使用help和 helpwin命令,得到的是不一样的结果:

删除的内容:

删除的内容:

Page 65: Matlab Simulink

第 2章 算法开发 53

H1 help line

在线帮助的第一行称为 H1 help line,用 lookfor 命令可以查询位于该行中的单词。Lookfor命令可用于搜索 H1 help line中带有特定单词的函数:

>> lookfor 'average or mean' MYMEAN Average or mean value. MEAN Average or mean value. MOT563_MEAN Average or mean value. MOT566_MEAN Average or mean value. NANMEAN Average or mean ignoring NaNs.

函数代码体

函数代码是实现函数功能的 m 语言代码,代码体的任何地方都可添加注释。带有多个输入输出变量的 m函数的格式如图 2.5所示。

图 2.5 带有多个输入输出变量的函数

【例 2】输入参数可变的 m函数。如图 2.6所示是一个输入参数可变的 m函数。编写输入参数可变的函数,要注意的几点是:

输入参数可变的函数的最后一个输入参数一定要是 varargin; 使用 nargin命令或者 length(varargin)来检测到底输入了多少个参数; 使用元胞数组内容提取符 {} 来提取可变输入参数中的输入内容。 图 2.6所示的函数,目的是要接收可变个数据点(x,y),然后将其依次连接成线。

第 1 行是函数定义行,如果输入参数中部分是不可变的(例如 N 个固定的输入参数),部分是可变的,函数定义可改写为:

删除的内容: >> help mymean

MYMEAN Average or mean value. For vectors, MYMEAN(X) is the mean value.For matrices, MYMEAN(X) is a row vector>> helpwin mymean

结果如图 2.4所示。

图 2.4 修改 mymean.m后输入 helpwin mymean的运行结果

删除的内容: ,

删除的内容:

删除的内容:

删除的内容: (应该和图在同一页)

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 有一

删除的内容: (

删除的内容: )

Page 66: Matlab Simulink

从Matlab/Simulink模型到代码实现 54

function myvarin(p1,p2,…,pN,varargin)

第 2~4行是在线帮助,删除之后并不会影响函数的功能,但不利于他人使用。 第 6~11 行是检查输入参数的个数是否大于 1,如果不大于 1,则提示函数至少输入两个点。当然在此这只是为了说明问题,并没有对参数的数据形式作严格 检查。

第 13~17行是从输入的数据点中,提取出 x坐标和相应的 y坐标。

图 2.6 输入参数可变的 m函数

第 19~20行是获得输入的数据点中 x坐标和 0的最小值,y坐标和 0的最小值。 第 22行是作出输入数据点的连线图。 第 23行是调节坐标轴的范围。

>> myvarin([0 1],[2 3],[3 10])

运行结果如图 2.7所示。

>> myvarin([0 1],[2 3],[3 10],[-1 -16])

运行结果如图 2.8所示。 >> myvarin([0 1]) Usage:myvarin([x1,y1],[x2,y2],...,[xN,yN]),where N>=2 Input more than one points,Please! >> myvarin Usage:myvarin([x1,y1],[x2,y2],...,[xN,yN]),where N>=2 Input more than one points,Please!

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: 分页符

删除的内容:

删除的内容:

删除的内容: ─

Page 67: Matlab Simulink

第 2章 算法开发 55

图 2.7 输入 myvarin([0 1],[2 3],[3 10])的运行结果

图 2.8 输入 myvarin([0 1],[2 3],[3 10],[-1 -16])的运行结果

【例 3】输出参数可变的 m函数。图 2.9所示是一个输出参数可变的函数。编写输出参数可变的函数,要注意的几点是:

输出参数可变的函数的最后一个输出参数一定要是 varargout; 使用 nargout命令或者 length(varargout)来检测到底有多少个输出参数; 使用元胞数组内容提取符 {} 来对可变输出参数赋值。

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: >> myvarin([0 1],[2 3],[3 10],[-1 -16])运行结果如图 2.8所示。

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: >> myvarin([0 1])Usage:myvarin([x1,y1],[x2,y2],...,[xN,yN]),where N>=2Input more than one points,Please!>> myvarinUsage:myvarin([x1,y1],[x2,y2],...,[xN,yN]),where N>=2Input more than one points,Please!

删除的内容: )

Page 68: Matlab Simulink

从Matlab/Simulink模型到代码实现 56

图 2.9所示的函数,目的是要产生可变个随机数据点(x,y)。 第 1 行是函数定义行,如果输出参数中有部分是不可变的(例如 N 个固定的输出参数),部分是可变的,函数定义可改写为:

function [p1,p2,…,pN,varargout]=myvarout

第 2~4行是在线帮助,删除之后并不会影响函数的功能,但不利于他人使用。 第 6~11 行是检查输出参数的个数是否大于 0,如果不大于 0,则提示函数至少要有一个输出参数。

图 2.9 输出参数可变的 m函数

第 13~17行是产生坐标在[0 9]间均匀分布的随机整型数据点,返回(x,y)坐标。 >> p1=myvarout p1 = 6 2 >> [p1 p2 p3]=myvarout p1 = 4 0 p2 = 9 5

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: ─

删除的内容: ─

删除的内容: 分页符

删除的内容:

删除的内容:

删除的内容: ─

删除的内容: (

删除的内容: )

Page 69: Matlab Simulink

第 2章 算法开发 57

p3 = 4 5 >> myvarout Usage:[p1,p2,...pN]=myvarout,where N>=1 Input output points more than zero,Please!

2.4 Toolboxes

MATLAB产品中包含有许多面向特定领域应用的 Toolboxes,即工具箱,它们封装了大量的专业函数,用来满足用户面向特定领域应用的需要。工具箱是 MATLAB 基本模块(即 MATLAB Toolbox)功能的扩展。用户在解决实际工程问题时,常常需要将MATLAB 基本模块和几个工具箱结合起来运用,才能达到完美的效果。例如,如果用户想用MATLAB做图像处理的工作,则可能需要如下几个MATLAB模块:

MATLAB基本模块 Signal Processing Toolbox Image Processing Toolbox Wavelet Toolbox 如果用户需要把用 Matlab 开发的图像处理程序转成独立的应用或者 C/C++源代码,

则还需要如下几个模块: MATLAB Compiler MATLAB C/C++ Math Library MATLAB C/C++ Graphics Library

MATLAB 提供的主要工具箱在第 1 章中已经列举出来了。如有用户需要查看某个工具箱中封装的函数的信息,只要把上一章中各个工具箱的缩写当作参数来使用 help、helpwin和 doc命令即可。以 Data Acquisition Toolbox(数据采集工具)为例:

>> help daq Data Acquisition Toolbox. Version 2.1 (R12.1) 06-April-2001 Data acquisition object construction. daq/analoginput - Construct analog input object. daq/analogoutput - Construct analog output object. daq/digitalio - Construct digital input/output object.

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: 用

删除的内容: 图 1.6

删除的内容: (

删除的内容: )

Page 70: Matlab Simulink

从Matlab/Simulink模型到代码实现 58

Getting and setting parameters. daqdevice/get - Get value of data acquisition object property. daqdevice/set - Set value of data acquisition object property. setverify - Set and return value of data acquisition object property. Execution. daqdevice/start - Start object running. stop - Stop object running and logging/sending. trigger - Manually initiate logging/sending for running object. waittilstop - Wait for the object to stop running. Analog input functions. addchannel - Add channels to analog input object. addmuxchannel - Add mux'd channels to analog input object. flushdata - Remove data from engine. getdata - Return acquired data samples. getsample - Immediately acquire a single sample. muxchanidx - Return scan channel index associated with mux board. peekdata - Preview most recent acquired data. Analog output functions. addchannel - Add channels to analog output object. putdata - Queue data samples for output. putsample - Immediately output single sample to object. Digital input/output functions. addline - Add lines to digital input/output object. getvalue - Read line values. putvalue - Write line values. General. binvec2dec - Convert binary vector to decimal number. daq/private/clear - Clear data acquisition object from the workspace. daqcallback - Display event information for specified event. daqfind - Find specified data acquisition objects. daqmem - Allocate or display memory for one or more device objects. daqread - Read Data Acquisition Toolbox (.daq) data file. daqregister - Register or unregister adaptor DLLs. daqreset - Delete and unload all data acquisition objects and DLLs. daqdevice/delete - Remove data acquisition objects from workspace and engine. dec2binvec - Convert decimal number to binary vector.

删除的内容:

删除的内容:

删除的内容: property.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 71: Matlab Simulink

第 2章 算法开发 59

ischannel - Determine if object is a channel. isdioline - Determine if object is a line. isvalid - Determine if object is associated with hardware. length - Determine length of data acquisition object. daq/private/load - Load data acquisition objects from disk into MATLAB workspace. makenames - Generate cell array of names for naming channels/lines. obj2mfile - Convert data acquisition object to MATLAB code. daq/private/save - Save data acquisition objects to disk. showdaqevents - Display summary of event log. size - Determine size of data acquisition object. Information and help. daqhelp - Data acquisition property and function help. daqhwinfo - Information on available hardware. daqpropedit - Data acquisition property editor. daqsupport - Data acquisition technical support tool. propinfo - Property information for data acquisition objects. Data acquisition demos. daqschool - Launch command line Data Acquisition Toolbox tutorials. demodaq_callback - Introduction to data acquisition callback functions. demodaq_intro - Introduction to Data Acquisition Toolbox. demodaq_save - Methods for saving and loading data acquisition objects. daqtimerplot - Example callback function which plots the data acquired. Analog input demos. daqrecord - Record data from the specified adaptor. demoai_channel - Introduction to analog input channels. demoai_fft - FFT display of an incoming analog input signal. demoai_intro - Introduction to analog input objects. demoai_logging - Demonstrate data logging. demoai_trig - Demonstrate the use of immediate, manual and software triggers. daqscope - Example oscilloscope for the Data Acquisition Toolbox. Analog output demos. daqplay - Output data to the specified adaptor. daqsong - Output data from HANDEL.MAT to a sound card. demoao_channel - Introduction to analog output channels. demoao_intro - Introduction to analog output objects. demoao_trig - Demonstrate the use of immediate and manual triggers. daqfcngen - Example function generator for the Data Acquisition Toolbox.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: -

删除的内容:

删除的内容:

删除的内容:

Page 72: Matlab Simulink

从Matlab/Simulink模型到代码实现 60

Digital I/O demos. demodio_intro - Introduction to digital I/O objects. demodio_line - Introduction to digital I/O lines. diopanel - Display digital I/O panel. See also ANALOGINPUT, ANALOGOUTPUT, DIGITALIO, DAQHELP. >> helpwin daq 运行结果如图 2.10所示。

图 2.10 输入 helpwin daq的运行结果

>> doc daq

运行结果如图 2.11所示。

图 2.11 输入 doc daq的运行结果

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 73: Matlab Simulink

第 2章 算法开发 61

2.5 调用 C/Fortran程序

在 MATLAB 中,只要按照 MATLAB 规定的语法,编写一个适当的 MexFunction 函数作为接口,就可以调用 C或者 Fortran编写的算法函数。

图 2.12 %MATLABROOT%\extern\examples\mex\yprime.m

图 2.12所示是一个描述微分方程组

( ) ( ) ( )( ) ( ) ( ) ( )( )( ) ( ) ( )( ) ( ) ( )( )

⎪⎪

⎪⎪

µ−=µ=µ

′′+µ−′′µ−′′+µ+′′µ−′′+′−=

′′+µ−µ−µ−′′+µ+µ+µ−+′′′=′′

154.821

***2

***23

223

224

322

322

s

ysyyyyysyyy

ysysyyyysyyy

的 m语言函数。输入参数 t表示求解的时间段 [ ]10 ,tt 或者时间向量 [ ]Nttt L10 ,输入参

数 y 表示微分方程组对应时刻 0t 的初值 [ ]yyyy ′′′′′′ ,,, ,返回参数表示 ( )[ ]4,,, yyyy ′′′′′′ 。要得

到描述上述微分方程组的对应的 m 语言函数的函数体,只要令 yp(1)= y′,yp(2)

= y ′′ ,yp(3)= y ′′′ ,yp(4)= ( )4y ,y(1)= y ,y(2)= y′,y(3)= y ′′ ,y(4)= y ′′′ 即可。图 2.12 所示的描述微分方程组的 m 语言格式是利用 MATLAB 的 ODE

(Ordinary Differential Equation)求解器求解微分方程组时要求的特定格式,详情请查看MATLAB HTML帮助文档MATLAB\Using MATLAB\Mathematics\Differential Equations一章(使用 doc命令)。

若要求解上述微分方程,只需在 MATLAB的命令窗口中使用 MATLAB的 ODE求解器函数,例如 ode45、ode23等等,调用图 2.12所示的 yprime函数即可。

>> [t y]=ode45(@yprime,[0 10],[1 2 3 4]) t =

带格式的

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 74: Matlab Simulink

从Matlab/Simulink模型到代码实现 62

0 0.0112 0.0224 0.0336 0.0448 0.1008 0.1568 0.2129 0.2689 0.4124 0.5559 0.6995 0.8430 0.9933 1.1435 1.2938 1.4441 1.6004 1.7567 1.9130 2.0694 2.2485 2.4276 2.6068 2.7859 2.9653 3.1446 3.3239 3.5032 3.6956 3.8880 4.0804 4.2729 4.4644 4.6559 4.8474 5.0389 5.2380 5.4371 5.6362 5.8353 6.0365

Page 75: Matlab Simulink

第 2章 算法开发 63

6.2378 6.4391 6.6403 6.8428 7.0452 7.2477 7.4501 7.6605 7.8710 8.0814 8.2918 8.4960 8.7001 8.9043 9.1085 9.3314 9.5543 9.7771 10.0000 y = 1.0000 2.0000 3.0000 4.0000 1.0230 2.1005 3.0447 3.9869 1.0471 2.2009 3.0893 3.9720 1.0723 2.3012 3.1337 3.9555 1.0986 2.4015 3.1779 3.9372 1.2471 2.9005 3.3954 3.8200 1.4234 3.3931 3.6051 3.6597 1.6271 3.8761 3.8046 3.4568 1.8575 4.3463 3.9916 3.2117 2.5633 5.4706 4.3978 2.3975 3.4198 6.4371 4.6686 1.3328 4.4011 7.1970 4.7696 0.0468 5.4744 7.7088 4.6725 -1.4214 6.6545 7.9415 4.3348 -3.1032 7.8440 7.8325 3.7366 -4.8735 8.9900 7.3614 2.8689 -6.6666 10.0378 6.5223 1.7343 -8.4134 10.9650 5.2663 0.2850 -10.1060 11.6660 3.6395 -1.4137 -11.5930

Page 76: Matlab Simulink

从Matlab/Simulink模型到代码实现 64

12.0850 1.6771 -3.3247 -12.7992 12.1744 -0.5697 -5.3983 -13.6582 11.8233 -3.4110 -7.8972 -14.1436 10.9449 -6.4287 -10.4293 -14.0270 9.5167 -9.4963 -12.8832 -13.2615 7.5446 -12.4765 -15.1414 -11.8321 5.0571 -15.2306 -17.0877 -9.7509 2.1070 -17.6139 -18.6040 -7.0565 -1.2294 -19.4934 -19.5850 -3.8166 -4.8498 -20.7537 -19.9439 -0.1309 -8.9108 -21.3100 -19.5624 4.1771 -12.9906 -20.9498 -18.3293 8.6785 -16.9088 -19.6186 -16.2225 13.1777 -20.4782 -17.3129 -13.2666 17.4659 -23.5026 -14.0922 -9.5463 21.3159 -25.8258 -10.0245 -5.1455 24.5444 -27.2947 -5.2305 -0.1973 26.9653 -27.7897 0.1229 5.1260 28.4244 -27.1825 6.0641 10.8429 28.7947 -25.3735 12.1409 16.5067 27.8990 -22.3572 18.0824 21.8622 25.6956 -18.1940 23.6084 26.6527 22.2135 -12.9390 28.4927 30.6718 17.4864 -6.7958 32.4000 33.6260 11.6873 0.0200 35.0924 35.3159 5.0173 7.2418 36.3862 35.5982 -2.2623 14.6129 36.1492 34.3756 -9.8934 21.7698 34.2898 31.6032 -17.5030 28.3836 30.8027 27.3137 -24.7444 34.1356 25.7723 21.6234 -31.2728 38.8860 19.0811 14.4251 -36.9532 42.0882 11.1392 6.1816 -41.1706 43.5058 2.2633 -2.7758 -43.6436 42.9919 -7.1578 -12.0561 -44.1792 40.5900 -16.4111 -20.9672 -42.7464 36.3221 -25.3578 -29.3822 -39.3578 30.2849 -33.5815 -36.9065 -34.0730 22.6743 -40.6868 -43.1742 -27.0574 12.8965 -46.7482 -48.2049 -17.7219 2.0066 -50.6367 -50.9909 -7.0354 -9.4849 -52.0404 -51.2747 4.5031 -21.0015 -50.7935 -48.9455 16.3134

Page 77: Matlab Simulink

第 2章 算法开发 65

[t y]=ode45(@yprime,[0 10],[1 2 3 4])表示积分时段为[0 10], [ ]yyyy ′′′′′′ ,,, 的初值为

[1 2 3 4],返回值 t包含积分时刻,返回值 y为对应积分时刻 t的 [ ]yyyy ′′′′′′ ,,, 值。如果我

们想作出微分方程组的解(t,y)的曲线可用如下命令:

>> plot(t,y(:,1))

运行结果如图 2.13所示。

图 2.13 输入 plot(t,y(:,1))的运行结果

>> t=0:0.1:10; >> [t y]=ode45(@yprime,t,[1 2 3 4]) t = 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000

删除的内容:

删除的内容: (

删除的内容: ,

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

Page 78: Matlab Simulink

从Matlab/Simulink模型到代码实现 66

1.8000 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000 2.6000 2.7000 2.8000 2.9000 3.0000 3.1000 3.2000 3.3000 3.4000 3.5000 3.6000 3.7000 3.8000 3.9000 4.0000 4.1000 4.2000 4.3000 4.4000 4.5000 4.6000 4.7000 4.8000 4.9000 5.0000 5.1000 5.2000 5.3000 5.4000 5.5000 5.6000 5.7000 5.8000 5.9000

Page 79: Matlab Simulink

第 2章 算法开发 67

6.0000 6.1000 6.2000 6.3000 6.4000 6.5000 6.6000 6.7000 6.8000 6.9000 7.0000 7.1000 7.2000 7.3000 7.4000 7.5000 7.6000 7.7000 7.8000 7.9000 8.0000 8.1000 8.2000 8.3000 8.4000 8.5000 8.6000 8.7000 8.8000 8.9000 9.0000 9.1000 9.2000 9.3000 9.4000 9.5000 9.6000 9.7000 9.8000 9.9000 10.0000

Page 80: Matlab Simulink

从Matlab/Simulink模型到代码实现 68

y = 1.0000 2.0000 3.0000 4.0000 1.2447 2.8931 3.3922 3.8220 1.5780 3.7662 3.7598 3.5071 1.9967 4.6008 4.0892 3.0576 2.4961 5.3790 4.3675 2.4781 3.0696 6.0825 4.5815 1.7759 3.7092 6.6944 4.7191 0.9599 4.4050 7.1994 4.7696 0.0417 5.1455 7.5837 4.7238 -0.9652 5.9177 7.8354 4.5740 -2.0450 6.7081 7.9441 4.3136 -3.1812 7.5016 7.9006 3.9374 -4.3554 8.2827 7.6985 3.4422 -5.5484 9.0356 7.3340 2.8272 -6.7402 9.7440 6.8062 2.0939 -7.9103 10.3917 6.1170 1.2461 -9.0377 10.9629 5.2698 0.2889 -10.1021 11.4415 4.2706 -0.7707 -11.0822 11.8124 3.1278 -1.9235 -11.9581 12.0620 1.8524 -3.1583 -12.7110 12.1781 0.4584 -4.4619 -13.3238 12.1499 -1.0380 -5.8187 -13.7809 11.9688 -2.6192 -7.2128 -14.0688 11.6264 -4.2657 -8.6264 -14.1744 11.1162 -5.9564 -10.0407 -14.0866 10.4346 -7.6691 -11.4362 -13.7976 9.5809 -9.3807 -12.7930 -13.3026 8.5570 -11.0670 -14.0903 -12.6003 7.3675 -12.7026 -15.3069 -11.6920 6.0191 -14.2638 -16.4232 -10.5818 4.5197 -15.7257 -17.4186 -9.2751 2.8799 -17.0636 -18.2733 -7.7805 1.1129 -18.2543 -18.9687 -6.1094 -0.7658 -19.2763 -19.4885 -4.2767 -2.7379 -20.1100 -19.8177 -2.3000 -4.7829 -20.7371 -19.9434 -0.2004 -6.8790 -21.1426 -19.8553 2.0000 -9.0039 -21.3122 -19.5440 4.2779 -11.1329 -21.2330 -19.0017 6.6070

Page 81: Matlab Simulink

第 2章 算法开发 69

-13.2408 -20.8957 -18.2238 8.9603 -15.3021 -20.2947 -17.2091 11.3099 -17.2906 -19.4284 -15.9601 13.6267 -19.1798 -18.2987 -14.4822 15.8808 -20.9429 -16.9112 -12.7847 18.0415 -22.5557 -15.2740 -10.8783 20.0810 -23.9928 -13.3968 -8.7759 21.9695 -25.2298 -11.2931 -6.4932 23.6779 -26.2446 -8.9797 -4.0489 25.1795 -27.0176 -6.4768 -1.4648 26.4500 -27.5318 -3.8083 1.2350 27.4674 -27.7726 -1.0013 4.0229 28.2120 -27.7283 1.9147 6.8697 28.6672 -27.3901 4.9107 9.7473 28.8193 -26.7498 7.9539 12.6238 28.6549 -25.8029 11.0104 15.4668 28.1648 -24.5495 14.0458 18.2441 27.3442 -22.9933 17.0251 20.9233 26.1930 -21.1428 19.9127 23.4716 24.7153 -19.0103 22.6725 25.8567 22.9200 -16.6118 25.2692 28.0471 20.8199 -13.9644 27.6709 30.0146 18.4290 -11.0885 29.8426 31.7288 15.7652 -8.0081 31.7523 33.1623 12.8498 -4.7499 33.3713 34.2910 9.7081 -1.3439 34.6742 35.0943 6.3687 2.1768 35.6386 35.5551 2.8643 5.7763 36.2460 35.6594 -0.7690 9.4165 36.4811 35.3975 -4.4928 13.0617 36.3326 34.7626 -8.2708 16.6719 35.7900 33.7493 -12.0614 20.2066 34.8476 32.3566 -15.8228 23.6264 33.5050 30.5890 -19.5131 26.8922 31.7673 28.4555 -23.0907 29.9657 29.6449 25.9705 -26.5141 32.8090 27.1533 23.1530 -29.7419 35.3860 24.3133 20.0267 -32.7337 37.6653 21.1463 16.6160 -35.4544 39.6129 17.6782 12.9494 -37.8654 41.1980 13.9388 9.0588 -39.9312 42.3944 9.9615 4.9794 -41.6210 43.1806 5.7833 0.7492 -42.9083

Page 82: Matlab Simulink

从Matlab/Simulink模型到代码实现 70

43.5397 1.4451 -3.5905 -43.7713 43.4593 -3.0087 -7.9955 -44.1926 42.9317 -7.5301 -12.4186 -44.1591 41.9536 -12.0737 -16.8152 -43.6632 40.5237 -16.5921 -21.1394 -42.6985 38.6449 -21.0345 -25.3421 -41.2630 36.3258 -25.3515 -29.3764 -39.3609 33.5808 -29.4949 -33.1966 -37.0024 30.4300 -33.4175 -36.7590 -34.2036 26.8989 -37.0735 -40.0212 -30.9870 23.0191 -40.4182 -42.9428 -27.3808 18.8247 -43.4120 -45.4885 -23.4169 14.3513 -46.0173 -47.6247 -19.1284 9.6396 -48.1944 -49.3167 -14.5539 4.7334 -49.9096 -50.5358 -9.7355 -0.3210 -51.1351 -51.2590 -4.7186 -5.4748 -51.8493 -51.4696 0.4483 -10.6761 -52.0360 -51.1565 5.7133 -15.8707 -51.6854 -50.3148 11.0211 -21.0015 -50.7935 -48.9455 16.3134 >> yprime([0 10],[1 2 3 4]) ans = 2.0000 8.9685 4.0000

-1.0947

对于图 2.12中的 m语言函数 yprime,可以编写相应的 C或 Fortran函数。以下程序即是对应的 C 代码函数(相应的 Fortran 代码函数在文件%MATLABROOT%\extern\ examples\mex\yprimef.f和 yprimefg.f中,编译过程和 C程序类似,只不过要用 mex –setup命令选择 Fortran的编译器)。

1 /*=================================================================

2 *

3 * YPRIME.C Sample .MEX file corresponding to YPRIME.M

4 *

5 The calling syntax is:

6 *

带格式的: 项目符号和编号

删除的内容: (

删除的内容: )

删除的内容: [yp] = yprime

删除的内容: (

删除的内容: (t, y

删除的内容: )

删除的内容: )

Page 83: Matlab Simulink

第 2章 算法开发 71

7 [ yp] = yprime(t, y)

8 *

9 You may also want to look at the corresponding M-code, yprime.m.

10 *=================================================================*/

11

12 #include <math.h>

13 #include "mex.h"

14

15 /* Input Arguments */

16

17 #define T_IN prhs[0]

18 #define Y_IN prhs[1]

19

20

21 /* Output Arguments */

22

23 #define YP_OUT plhs[0]

24 25 #if !defined(MAX)

26 #define MAX(A, B) ((A) > (B) ? (A) : (B))

27 #endif

28

29 #if !defined(MIN)

30 #define MIN(A, B) ((A) < (B) ? (A) : (B))

31 #endif

32

33 #define PI 3.14159265

34

35 static double mu = 1/82.45;

36 static double mus = 1 - 1/82.45;

37

38 39 static void yprime(

40 double yp[],

41 double *t,

42 double y[]

43 ) 44 {

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容: *

删除的内容: <#>

删除的内容: (

删除的内容: (MAX

删除的内容: )

删除的内容: )

删除的内容: #define MAX

删除的内容: (A

删除的内容: )

删除的内容: (

删除的内容: (A, B

删除的内容: )

删除的内容: )

删除的内容: (

删除的内容: (

删除的内容: (

删除的内容: ) >

删除的内容: (

删除的内容: (B

删除的内容: )

删除的内容: ) ?

删除的内容: (

删除的内容: (A

删除的内容: )

删除的内容: ) :

删除的内容: (

删除的内容: (B

删除的内容: )

删除的内容: )

删除的内容: )

删除的内容: )

删除的内容: #if !defined

删除的内容: (

删除的内容: (MIN

删除的内容: )

删除的内容: )

删除的内容: (

删除的内容: (A, B

删除的内容: )

删除的内容: )

删除的内容: (

删除的内容: (

删除的内容: (

删除的内容: (A

删除的内容: )

删除的内容: ) <

删除的内容: (

删除的内容: (B

删除的内容: )

删除的内容: ) ?

删除的内容: (

... [2]

... [3]

... [1]

Page 84: Matlab Simulink

从Matlab/Simulink模型到代码实现 72

45 double r1,r2;

46

47 r1 = sqrt((y[0]+mu)*(y[0]+mu) + y[2]*y[2]);

48 r2 = sqrt((y[0]-mus)*(y[0]-mus) + y[2]*y[2]);

49

50 /* Print warning if dividing by zero. */

51 if (r1 == 0.0 || r2 == 0.0 ){ 52 mexWarnMsgTxt("Division by zero!\n");

53 }

54

55 yp[0] = y[1];

56 yp[1] = 2*y[3]+y[0]-mus*(y[0]+mu)/(r1*r1*r1)-mu*(y[0]-mus)/(r2*r2*r2);

57 yp[2] = y[3];

58 yp[3] = -2*y[1] + y[2] - mus*y[2]/(r1*r1*r1) - mu*y[2]/(r2*r2*r2);

59 return;

60 }

61

62 void mexFunction( int nlhs, mxArray *plhs[],

63 int nrhs, const mxArray*prhs[] )

64

65 {

66 double *yp;

67 double *t,*y;

68 unsigned int m,n;

69

70 /* Check for proper number of arguments */

71

72 if (nrhs != 2) {

73 mexErrMsgTxt("Two input arguments required.");

74 } else if (nlhs > 1) {

75 mexErrMsgTxt("Too many output arguments.");

76 }

77

78 /* Check the dimensions of Y. Y can be 4 X 1 or 1 X 4. */

79

80 m = mxGetM(Y_IN);

81 n = mxGetN(Y_IN);

82 if (!mxIsDouble(Y_IN) || mxIsComplex(Y_IN) ||

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容: r1 = sqrt

删除的内容: (

删除的内容: (

删除的内容: (

删除的内容: (y[0]+mu

删除的内容: )

删除的内容: )*

删除的内容: (

删除的内容: (y[0]+mu

删除的内容: )

删除的内容: ) + y[2]*y[2]

删除的内容: )

删除的内容: );

删除的内容: (

删除的内容: (y[0]-mus

删除的内容: (

删除的内容: (

删除的内容: )

删除的内容: )*

删除的内容: (

删除的内容: (y[0]-mus

删除的内容: )

删除的内容: ) + y[2]*y[2]

删除的内容: )

删除的内容: );

删除的内容: if

删除的内容: (

删除的内容: (r1 == 0.0 || r2

删除的内容: )

删除的内容: ){

删除的内容: mexWarnMsgTx

删除的内容: (

删除的内容: ("Division by

删除的内容: )

删除的内容: );

删除的内容: yp[1] =

删除的内容: (

删除的内容: (y[0]+mu

删除的内容: )

删除的内容: )/

删除的内容: (

删除的内容: (r1*r1*r1

删除的内容: )

删除的内容: )-mu*

删除的内容: (

删除的内容: (y[0]-mus

删除的内容: )

删除的内容: )/

... [8]

... [9]

... [7]

... [6]

... [11]

... [10]

... [5]

Page 85: Matlab Simulink

第 2章 算法开发 73

83 (MAX(m,n) != 4) || (MIN(m,n) != 1)) {

84 mexErrMsgTxt("YPRIME requires that Y be a 4 x 1 vector.");

85 }

86

87 /* Create a matrix for the return argument */

88 YP_OUT = mxCreateDoubleMatrix(4, 1, mxREAL);

89

90 /* Assign pointers to the various parameters */

91 yp = mxGetPr(YP_OUT);

92

93 t = mxGetPr(T_IN);

94 y = mxGetPr(Y_IN);

95

96 /* Do the actual computations in a subroutine */

97 yprime(yp,t,y);

98 return;

99

100 }

程序说明如下:

第 12~36行,头文件、宏定义和数据定义。 第 39~60行,C算法函数 yprime。 第 62~100 行,Matlab 调用 C 算法的接口函数 mexFunction。关于如何编写该函数,请参考 MATLAB HTML 帮助 MATLAB\Using MATLAB\External Interfaces/ API\Calling C and Fortran Programs from MATLAB一节。

要在 MATLAB 中调用该函数,首先要用 mex 命令将其编译为动态链接库。过程 如下:

>> mex -setup Please choose your compiler for building external interface (MEX) files: Would you like mex to locate installed compilers [y]/n? y Select a compiler: [1] Digital Visual Fortran version 6.0 in C:\Program Files\Microsoft Visual Studio [2] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc [3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio [0] None

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容: YP_OUT = mxCreateDoubleMatrix

删除的内容: (

删除的内容: (4, 1, mxREAL

删除的内容: )

删除的内容: );

删除的内容: yp = mxGetPr

删除的内容: (

删除的内容: (YP_OUT

删除的内容: )

删除的内容: );

删除的内容: t = mxGetPr

删除的内容: (

删除的内容: (T_IN

删除的内容: )

删除的内容: ); y = mxGetPr

删除的内容: (

删除的内容: (Y_IN

删除的内容: )

删除的内容: );

删除的内容: yprime

删除的内容: (

删除的内容: (yp,t,y

删除的内容: )

删除的内容: );

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容:

删除的内容:

Page 86: Matlab Simulink

从Matlab/Simulink模型到代码实现 74

Compiler: 3 Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: C:\Program Files\Microsoft Visual Studio Are these correct?([y]/n): y The default options file:

"C:\Documents and Settings\Michael\Application Data\MathWorks\MATLAB\R12\mexopts.bat" is being updated from D:\MATLAB6P1\BIN\WIN32\mexopts\msvc60opts.bat... Installing the MATLAB Visual Studio add-in ... Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\ template\MATLABWizard.awx from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.awx

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.hlp from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.hlp

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\addins\MATLABAddin.dll from D:\MATLAB6P1\BIN\WIN32\MATLABAddin.dll Merged D:\MATLAB6P1\BIN\WIN32\usertype.dat

with C:\Program Files\Microsoft Visual Studio\common\msdev98\bin\usertype.dat Note: If you want to use the MATLAB Visual Studio add-in with the MATLAB C/C++ Compiler, you must start MATLAB and run the following commands: cd(prefdir); mccsavepath; (You only have to do this configuration step once.) >> mex yprime.c

使用 dir命令可以看到已经生成 yprime.dll。 >> dir yprime.dll yprime.dll

编译成动态库后,不再需要 yprime.c,即可像使用图 2.12 中的 m 语言函数一样使用C语言编写的 yprime函数。

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 87: Matlab Simulink

第 2章 算法开发 75

>> [t y]=ode45(@yprime,[0 10],[1 2 3 4]) t = 0 0.0112 0.0224 0.0336 0.0448 0.1008 0.1568 0.2129 0.2689 0.4124 0.5559 0.6995 0.8430 0.9933 1.1435 1.2938 1.4441 1.6004 1.7567 1.9130 2.0694 2.2485 2.4276 2.6068 2.7859 2.9653 3.1446 3.3239 3.5032 3.6956 3.8880 4.0804 4.2729 4.4644 4.6559 4.8474 5.0389 5.2380

删除的内容:

Page 88: Matlab Simulink

从Matlab/Simulink模型到代码实现 76

5.4371 5.6362 5.8353 6.0365 6.2378 6.4391 6.6403 6.8428 7.0452 7.2477 7.4501 7.6605 7.8710 8.0814 8.2918 8.4960 8.7001 8.9043 9.1085 9.3314 9.5543 9.7771 10.0000 y = 1.0000 2.0000 3.0000 4.0000 1.0230 2.1005 3.0447 3.9869 1.0471 2.2009 3.0893 3.9720 1.0723 2.3012 3.1337 3.9555 1.0986 2.4015 3.1779 3.9372 1.2471 2.9005 3.3954 3.8200 1.4234 3.3931 3.6051 3.6597 1.6271 3.8761 3.8046 3.4568 1.8575 4.3463 3.9916 3.2117 2.5633 5.4706 4.3978 2.3975 3.4198 6.4371 4.6686 1.3328 4.4011 7.1970 4.7696 0.0468 5.4744 7.7088 4.6725 -1.4214 6.6545 7.9415 4.3348 -3.1032 7.8440 7.8325 3.7366 -4.8735

Page 89: Matlab Simulink

第 2章 算法开发 77

8.9900 7.3614 2.8689 -6.6666 10.0378 6.5223 1.7343 -8.4134 10.9650 5.2663 0.2850 -10.1060 11.6660 3.6395 -1.4137 -11.5930 12.0850 1.6771 -3.3247 -12.7992 12.1744 -0.5697 -5.3983 -13.6582 11.8233 -3.4110 -7.8972 -14.1436 10.9449 -6.4287 -10.4293 -14.0270 9.5167 -9.4963 -12.8832 -13.2615 7.5446 -12.4765 -15.1414 -11.8321 5.0571 -15.2306 -17.0877 -9.7509 2.1070 -17.6139 -18.6040 -7.0565 -1.2294 -19.4934 -19.5850 -3.8166 -4.8498 -20.7537 -19.9439 -0.1309 -8.9108 -21.3100 -19.5624 4.1771 -12.9906 -20.9498 -18.3293 8.6785 -16.9088 -19.6186 -16.2225 13.1777 -20.4782 -17.3129 -13.2666 17.4659 -23.5026 -14.0922 -9.5463 21.3159 -25.8258 -10.0245 -5.1455 24.5444 -27.2947 -5.2305 -0.1973 26.9653 -27.7897 0.1229 5.1260 28.4244 -27.1825 6.0641 10.8429 28.7947 -25.3735 12.1409 16.5067 27.8990 -22.3572 18.0824 21.8622 25.6956 -18.1940 23.6084 26.6527 22.2135 -12.9390 28.4927 30.6718 17.4864 -6.7958 32.4000 33.6260 11.6873 0.0200 35.0924 35.3159 5.0173 7.2418 36.3862 35.5982 -2.2623 14.6129 36.1492 34.3756 -9.8934 21.7698 34.2898 31.6032 -17.5030 28.3836 30.8027 27.3137 -24.7444 34.1356 25.7723 21.6234 -31.2728 38.8860 19.0811 14.4251 -36.9532 42.0882 11.1392 6.1816 -41.1706 43.5058 2.2633 -2.7758 -43.6436 42.9919 -7.1578 -12.0561 -44.1792 40.5900 -16.4111 -20.9672 -42.7464 36.3221 -25.3578 -29.3822 -39.3578 30.2849 -33.5815 -36.9065 -34.0730 22.6743 -40.6868 -43.1742 -27.0574

Page 90: Matlab Simulink

从Matlab/Simulink模型到代码实现 78

12.8965 -46.7482 -48.2049 -17.7219 2.0066 -50.6367 -50.9909 -7.0354 -9.4849 -52.0404 -51.2747 4.5031 -21.0015 -50.7935 -48.9455 16.3134 >> t=0:0.1:10; >> [t y]=ode45(@yprime,t,[1 2 3 4]) t = 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000 2.6000 2.7000 2.8000 2.9000 3.0000 3.1000 3.2000

Page 91: Matlab Simulink

第 2章 算法开发 79

3.3000 3.4000 3.5000 3.6000 3.7000 3.8000 3.9000 4.0000 4.1000 4.2000 4.3000 4.4000 4.5000 4.6000 4.7000 4.8000 4.9000 5.0000 5.1000 5.2000 5.3000 5.4000 5.5000 5.6000 5.7000 5.8000 5.9000 6.0000 6.1000 6.2000 6.3000 6.4000 6.5000 6.6000 6.7000 6.8000 6.9000 7.0000 7.1000 7.2000 7.3000 7.4000

Page 92: Matlab Simulink

从Matlab/Simulink模型到代码实现 80

7.5000 7.6000 7.7000 7.8000 7.9000 8.0000 8.1000 8.2000 8.3000 8.4000 8.5000 8.6000 8.7000 8.8000 8.9000 9.0000 9.1000 9.2000 9.3000 9.4000 9.5000 9.6000 9.7000 9.8000 9.9000 10.0000 y = 1.0000 2.0000 3.0000 4.0000 1.2447 2.8931 3.3922 3.8220 1.5780 3.7662 3.7598 3.5071 1.9967 4.6008 4.0892 3.0576 2.4961 5.3790 4.3675 2.4781 3.0696 6.0825 4.5815 1.7759 3.7092 6.6944 4.7191 0.9599 4.4050 7.1994 4.7696 0.0417 5.1455 7.5837 4.7238 -0.9652 5.9177 7.8354 4.5740 -2.0450 6.7081 7.9441 4.3136 -3.1812 7.5016 7.9006 3.9374 -4.3554

Page 93: Matlab Simulink

第 2章 算法开发 81

8.2827 7.6985 3.4422 -5.5484 9.0356 7.3340 2.8272 -6.7402 9.7440 6.8062 2.0939 -7.9103 10.3917 6.1170 1.2461 -9.0377 10.9629 5.2698 0.2889 -10.1021 11.4415 4.2706 -0.7707 -11.0822 11.8124 3.1278 -1.9235 -11.9581 12.0620 1.8524 -3.1583 -12.7110 12.1781 0.4584 -4.4619 -13.3238 12.1499 -1.0380 -5.8187 -13.7809 11.9688 -2.6192 -7.2128 -14.0688 11.6264 -4.2657 -8.6264 -14.1744 11.1162 -5.9564 -10.0407 -14.0866 10.4346 -7.6691 -11.4362 -13.7976 9.5809 -9.3807 -12.7930 -13.3026 8.5570 -11.0670 -14.0903 -12.6003 7.3675 -12.7026 -15.3069 -11.6920 6.0191 -14.2638 -16.4232 -10.5818 4.5197 -15.7257 -17.4186 -9.2751 2.8799 -17.0636 -18.2733 -7.7805 1.1129 -18.2543 -18.9687 -6.1094 -0.7658 -19.2763 -19.4885 -4.2767 -2.7379 -20.1100 -19.8177 -2.3000 -4.7829 -20.7371 -19.9434 -0.2004 -6.8790 -21.1426 -19.8553 2.0000 -9.0039 -21.3122 -19.5440 4.2779 -11.1329 -21.2330 -19.0017 6.6070 -13.2408 -20.8957 -18.2238 8.9603 -15.3021 -20.2947 -17.2091 11.3099 -17.2906 -19.4284 -15.9601 13.6267 -19.1798 -18.2987 -14.4822 15.8808 -20.9429 -16.9112 -12.7847 18.0415 -22.5557 -15.2740 -10.8783 20.0810 -23.9928 -13.3968 -8.7759 21.9695 -25.2298 -11.2931 -6.4932 23.6779 -26.2446 -8.9797 -4.0489 25.1795 -27.0176 -6.4768 -1.4648 26.4500 -27.5318 -3.8083 1.2350 27.4674 -27.7726 -1.0013 4.0229 28.2120 -27.7283 1.9147 6.8697 28.6672 -27.3901 4.9107 9.7473 28.8193 -26.7498 7.9539 12.6238 28.6549

Page 94: Matlab Simulink

从Matlab/Simulink模型到代码实现 82

-25.8029 11.0104 15.4668 28.1648 -24.5495 14.0458 18.2441 27.3442 -22.9933 17.0251 20.9233 26.1930 -21.1428 19.9127 23.4716 24.7153 -19.0103 22.6725 25.8567 22.9200 -16.6118 25.2692 28.0471 20.8199 -13.9644 27.6709 30.0146 18.4290 -11.0885 29.8426 31.7288 15.7652 -8.0081 31.7523 33.1623 12.8498 -4.7499 33.3713 34.2910 9.7081 -1.3439 34.6742 35.0943 6.3687 2.1768 35.6386 35.5551 2.8643 5.7763 36.2460 35.6594 -0.7690 9.4165 36.4811 35.3975 -4.4928 13.0617 36.3326 34.7626 -8.2708 16.6719 35.7900 33.7493 -12.0614 20.2066 34.8476 32.3566 -15.8228 23.6264 33.5050 30.5890 -19.5131 26.8922 31.7673 28.4555 -23.0907 29.9657 29.6449 25.9705 -26.5141 32.8090 27.1533 23.1530 -29.7419 35.3860 24.3133 20.0267 -32.7337 37.6653 21.1463 16.6160 -35.4544 39.6129 17.6782 12.9494 -37.8654 41.1980 13.9388 9.0588 -39.9312 42.3944 9.9615 4.9794 -41.6210 43.1806 5.7833 0.7492 -42.9083 43.5397 1.4451 -3.5905 -43.7713 43.4593 -3.0087 -7.9955 -44.1926 42.9317 -7.5301 -12.4186 -44.1591 41.9536 -12.0737 -16.8152 -43.6632 40.5237 -16.5921 -21.1394 -42.6985 38.6449 -21.0345 -25.3421 -41.2630 36.3258 -25.3515 -29.3764 -39.3609 33.5808 -29.4949 -33.1966 -37.0024 30.4300 -33.4175 -36.7590 -34.2036 26.8989 -37.0735 -40.0212 -30.9870 23.0191 -40.4182 -42.9428 -27.3808 18.8247 -43.4120 -45.4885 -23.4169 14.3513 -46.0173 -47.6247 -19.1284 9.6396 -48.1944 -49.3167 -14.5539 4.7334 -49.9096 -50.5358 -9.7355

Page 95: Matlab Simulink

第 2章 算法开发 83

-0.3210 -51.1351 -51.2590 -4.7186 -5.4748 -51.8493 -51.4696 0.4483 -10.6761 -52.0360 -51.1565 5.7133 -15.8707 -51.6854 -50.3148 11.0211 -21.0015 -50.7935 -48.9455 16.3134 >> yprime([0 10],[1 2 3 4]) ans = 2.0000 8.9685 4.0000 -1.0947

2.6 建立自己的函数库

MATLAB 产品有一个开放的体系结构,用户很容易在 MATLAB 基本模块和各种工具箱提供的大量函数的基础上,扩展自己的函数库。用户只需编写自己的 m 函数,或者像2.5节中论述的用 C或者 Fortran开发自己的算法函数,再用 mex命令将其编译成MATLAB可以调用的动态库。然后,用户可以将这些 m 函数或者动态库放在某个目录 (例如e:\material\mytoolbox)下,再将 e:\material\mytoolbox 添加到 MATLAB 的搜索路径列表中,如图 2.14所示。这样,用户就可像调用Matlab标准函数一样调用自己的函数。

图 2.14 MATLAB搜索路径设置对话框

删除的内容:

删除的内容: 分页符

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

删除的内容:

Page 96: Matlab Simulink

从Matlab/Simulink模型到代码实现 84

2.7 算法开发示例

Matlab环境中的算法开发主要是指用 m语言编程的方式(可以调用 C/Fortran算法函数)来解决科学计算、数据分析和可视化等问题。MATLAB 提供了各种各样的工具箱,帮助用户实现不同专业领域的算法开发工作。

【例 4】产生按给定概率分布的随机整数矩阵。产生一个 10×10的 0,1,2,3按概率 0.5,0.1,0.15,0.25分布的随机矩阵,可使用 Communications Toolbox提供的 m函数randsrc。

>> which randsrc D:\MATLAB6p1\toolbox\comm\comm\randsrc.m >> type randsrc function out = randsrc(varargin); %RANDSRC Generate random matrix using prescribed alphabet. % OUT = RANDSRC generates a "-1" or "1" with equal probability. % % OUT = RANDSRC(M) generates an M-by-M random bipolar matrix. % "-1" and "1" occur with equal probability. % % OUT = RANDSRC(M,N) generates an M-by-N random bipolar matrix. % "-1" and "1" occur with equal probability. % % OUT = RANDSRC(M,N,ALPHABET) generates an M-by-N random matrix, using the % alphabet specified in ALPHABET. % % ALPHABET can be either a row vector or a two-row matrix: % Row : If ALPHABET is a row vector then the contents of ALPHABET define % Vector which possible elements RANDSRC can output. The elements of % ALPHABET may be either real or complex. If all entries of % ALPHABET are distinct, then the probability distribution is % uniform. % Two-Row : If ALPHABET is a two-row matrix, the first row defines the % Matrix possible outputs (as above). The second row of ALPHABET % specifies the probability for each corresponding element. The % elements of the second row must sum to one. % % OUT = RANDSRC(M,N,ALPHABET,STATE) resets the state of RAND to STATE.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: the

删除的内容: of

删除的内容: of

删除的内容: is

删除的内容: The

Page 97: Matlab Simulink

第 2章 算法开发 85

% % Examples: % �out = randsrc(2,3) �out = randsrc(2,3,[3 4]) % out = out = % 1 -1 -1 4 4 3 % -1 -1 1 3 3 4 % % �out = randsrc(2,3,[3 4;0 1]) �out = randsrc(2,3,[3 4;0.8 0.2]) % out = out = % 4 4 4 3 3 3 % 4 4 4 3 4 3 % % See also RAND, RANDINT, RANDERR. % Copyright 1996-2001 The MathWorks, Inc. % $Revision: 1.6 $ $Date: 2001/04/23 15:32:46 $ % Basic function setup. error(nargchk(0,4,nargin)); % --- Placeholder for the signature string. sigStr = ''; m = []; n = []; alpha = []; state = []; % --- Identify string and numeric arguments for i=1:nargin if(i>1) sigStr(size(sigStr,2)+1) = '/'; end; % --- Assign the string and numeric flags if(isnumeric(varargin{i})) sigStr(size(sigStr,2)+1) = 'n'; else error('Only numeric arguments are accepted.'); end; end; % --- Identify parameter signitures and assign values to variables switch sigStr

删除的内容: =

删除的内容:

Page 98: Matlab Simulink

从Matlab/Simulink模型到代码实现 86

% --- randsrc case '' % --- randsrc(m) case 'n' m = varargin{1}; % --- randsrc(m, n) case 'n/n' m = varargin{1}; n = varargin{2}; % --- randsrc(m, n, alpha) case 'n/n/n' m = varargin{1}; n = varargin{2}; alpha = varargin{3}; % --- randsrc(m, n, alpha, state) case 'n/n/n/n' m = varargin{1}; n = varargin{2}; alpha = varargin{3}; state = varargin{4}; % --- If the parameter list does not match one of these signatures. otherwise error('Syntax error.'); end; if isempty(m) m = 1; end if isempty(n) n = m; end if isempty(alpha) alpha = [-1, 1]; end % Typical error-checking. if (~isfinite(m)) | (~isfinite(n))

Page 99: Matlab Simulink

第 2章 算法开发 87

error('Matrix dimensions must be finite.'); elseif (floor(m) ~= m) | (floor(n) ~= n) | (~isreal(m)) | (~isreal(n)) error('Matrix dimensions must be real integers.'); elseif (m < 0) | (n < 0) error('Matrix dimensions must be positive.'); elseif (length(m) > 1) | (length(n) > 1) error('Matrix dimensions must be scalars.'); end ar = size(alpha,1); ac = size(alpha,2); if ar > 2 error('The ALPHABET parameter cannot contain more than two rows.'); % If the alphabet probabilities are explicitly defined. elseif ar == 2 aprob = alpha(2,:); % Error-check the probabilities. if (~isreal(aprob)) | (~isfinite(aprob)) | max(aprob < 0) | max(aprob > 1) error('The ALPHABET probability elements must be real numbers between zero and one.'); elseif (abs(sum(aprob) - 1) > sqrt(eps)) error('Sum of ALPHABET probability elements must equal one.'); end % 'prob' is used to facilitate assigning the random elements to the output. % Ex: if the second row of the alphabet input parameter % is [0.3 0.4 0.3] then 'prob' would be set to [0.3 0.7 1.0]. prob = cumsum(aprob); else % Define the 'prob' vector if the probabilities are not given in the function call. prob = (1:ac) / ac; end % Set the initial state if specified. if ~isempty(state) 带格式的

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 100: Matlab Simulink

从Matlab/Simulink模型到代码实现 88

rand('state', state); end % Generate the random matrix. r = rand(m,n); % 'idx' is used to place the alphabet elements in the output matrix. idx = ones(m,n); % Use the random matrix 'r' to determine which alphabet element to use % in the output matrix. % Ex: if the alphabet parameter is {'a' 'b' 'c' 'd'}, the 'idx' matrix % will contain integers from one to four after this loop has run. for i = 1:ac idx = idx + (r >= prob(i)); end alphabet = alpha(1,:); % Assign alphabet elements to the output matrix as specified by 'idx'. out = alphabet(idx); % A special case, if the m and n parameters specify a column vector. if n == 1 out = out(:); end % [EOF] randsrc.m >> randsrc(10,10,[0 1 2 3;0.5 0.1 0.15 0.25]) ans = 3 3 0 1 0 0 2 1 0 0 0 1 3 1 3 2 2 0 0 3 3 0 3 3 2 2 3 3 0 3 3 0 0 3 0 0 1 2 2 3 3 0 0 0 2 3 0 1 2 3 3 3 0 0 0 2 3 3 3 0 3 3 0 0 1 0 0 0 0 0 3 3 0 2 0 2 3 0 0 1 3 3 0 3 3 2 2 1 1 2

0 0 0 0 3 1 3 1 0 0

Page 101: Matlab Simulink

第 2章 算法开发 89

【例 5】作出传递函数 ( )21

1

32121

−−

+++

=zz

zzH 的零极点分布图,可使用如下的脚本 m

文件 plotpz.m。 %plotpz.m - plot the zero and pole plane from %transfer function % -1 -2 % b(1)+b(2)*z +b(3)*z %H(z)=------------------------- % -1 -2 % a(1)+a(2)*z +a(3)*z b=[1 2 0]; a=[1 2 3]; [z,p,k]=tf2zp(b,a); zplane(z,p); >> plotpz

运行结果如图 2.15所示。

图 2.15 输入 plotpz的运行结果

【例 6】边缘检测算法。用 Sobel和 Canny方法来检测灰度图像的边缘,相应的函数m文件 edge_detect.m如下所示:

function [BW1 BW2]=edge_detect(filename) %EDGE_DETECT Detect the edge of input image %This function takes an intensity image I as its input, %and plots and return two binary images BW of the same %size as I,with 1's where the function finds edges in %I and 0's elsewhere with Sobel and Canny method.

删除的内容:

删除的内容:

删除的内容:

删除的内容: :

Page 102: Matlab Simulink

从Matlab/Simulink模型到代码实现 90

I = imread(filename); %The Sobel method finds edges using the Sobel approximation %to the derivative. It returns edges at those points where %the gradient of I is maximum. BW1 = edge(I,'sobel'); %The Canny method finds edges by looking for local maxima of %the gradient of I. The gradient is calculated using the %derivative of a Gaussian filter. The method uses two thresholds, %to detect strong and weak edges, and includes the weak edges %in the output only if they are connected to strong edges. This %method is therefore less likely than the others to be "fooled" %by noise, and more likely to detect true weak edges. BW2 = edge(I,'canny'); figure; subplot(1,2,1); imshow(I); title(['original ',filename]); subplot(1,2,2); imshow(BW1); title(['edge\_detected ',filename,' with ''soble'' method']); figure; subplot(1,2,1); imshow(I); title(['original ',filename]); subplot(1,2,2); imshow(BW2); title(['edge\_detected ',filename,' with ''canny'' method']); >> which blood1.tif D:\MATLAB6p1\toolbox\images\imdemos\blood1.tif >> [sobel canny]=edge_detect('blood1.tif');

运行结果如图 2.16和图 2.17所示。 >> which rice.tif D:\MATLAB6p1\toolbox\images\imdemos\rice.tif >> [sobel canny]=edge_detect('rice.tif');

Page 103: Matlab Simulink

第 2章 算法开发 91

运行结果如图 2.18和图 2.19所示。

图 2.16 edge_detect('blood1.tif')运行结果(1)

图 2.17 edge_detect('blood1.tif')运行结果(2)

删除的内容: 分页符

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 104: Matlab Simulink

从Matlab/Simulink模型到代码实现 92

图 2.18 edge_detect('rice.tif')运行结果(1)

图 2.19 edge_detect('rice.tif')运行结果(2)

>> whos Name Size Bytes Class canny 256x256 65536 uint8 array (logical) sobel 256x256 65536 uint8 array (logical) Grand total is 131072 elements using 131072 bytes

删除的内容:

删除的内容:

删除的内容: 3

删除的内容:

删除的内容:

删除的内容: 4

Page 105: Matlab Simulink

页 71: [1] 删除的内容 xiao 2002-10-4 12:06:00

#if !defined

页 71: [2] 删除的内容 xiao 2002-10-4 12:06:00

)

页 71: [2] 删除的内容 xiao 2002-10-4 12:09:00

#endif

页 71: [3] 删除的内容 xiao 2002-10-4 12:08:00

) #define MIN

页 71: [4] 删除的内容 xiao 2002-10-4 12:10:00

#define PI 3.14159265

页 72: [5] 删除的内容 xiao 2002-10-4 12:13:00

); r2 = sqrt

页 72: [6] 删除的内容 xiao 2002-10-4 12:13:00

);

页 72: [7] 删除的内容 xiao 2002-10-4 12:14:00

(r1 == 0.0 || r2 == 0.0

页 72: [8] 删除的内容 xiao 2002-10-4 12:14:00

mexWarnMsgTxt

页 72: [9] 删除的内容 xiao 2002-10-4 12:14:00

("Division by zero!\n"

页 72: [10] 删除的内容 xiao 2002-10-4 12:16:00

yp[1] = 2*y[3]+y[0]-mus*

页 72: [11] 删除的内容 xiao 2002-10-4 12:17:00

yp[3] = -2*y[1] + y[2] - mus*y[2]/

Page 106: Matlab Simulink

第 3章 将 m 程序转换成独立的应用

MATLAB Compiler可以将开发出来的 m程序自动转成独立的应用。这种转换需要的MATLAB产品模块包括:

MATLAB Compiler MATLAB C/C++ Math Library 如果 m程序中包含图形功能,则还需要

MATLAB C/C++ Graphics Library 转换过程如图 3.1所示。

m程序(可以包含图形功能)

MATLAB Compiler

m程序生成的C/C++源代码

C/C++编译器

目标文件

连接器

独立应用

MATLAB C/C++ Graphics LibraryMATLAB Math m-file LibraryMATLAB Math Built-in LibraryMATLAB API LibraryMATLAB MAT-file LibraryANSI C/C++ Library

图 3.1 m程序转成独立应用的过程

MATLAB Compiler的作用是将 m程序转成 C/C++源代码,这种源代码需要用 C/C++编译器编译连接成独立应用。在将 m 程序转成独立应用的过程中生成的 C/C++源代码,

删除的内容: ,

删除的内容: (不需要缩进)

删除的内容: (不需要缩进)

Page 107: Matlab Simulink

从Matlab/Simulink模型到代码实现 94

原则上是可以被其他的 C/C++程序调用的,但不推荐用户这样做。如果用户确实需要在自己的 C/C++程序中调用 MATLAB 的功能,应该选择在 C/C++程序中直接调用 MATLAB C/C++ Math Library(它是MathWorks公司提供的 C/C++数学库,用于提供实现MATLAB函数功能的 C/C++函数,在 C/C++程序中可直接调用。例如相应于 MATLAB 函数 fft,MATLAB C/C++ Math Library中有 mlfFft函数来实现 FFT的功能)中的函数,用来实现类似于MATLAB的强大的科学计算和数据分析的功能。

在将 m 程序转换成独立应用和 C/C++源代码之前,首先要选择适当的 C/C++编 译器。

3.1 选择 C/C++ compiler

编译器的选择是通过在MATLAB命令窗口中运行 mex和 mbuild命令来实现的: >> mex -setup Please choose your compiler for building external interface (MEX) files: Would you like mex to locate installed compilers [y]/n? y Select a compiler: [1] Digital Visual Fortran version 6.0 in C:\Program Files\Microsoft Visual Studio [2] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc [3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio [0] None Compiler: 3 Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: C:\Program Files\Microsoft Visual Studio Are these correct?([y]/n): y The default options file: "C:\Documents and Settings\Yongchun\Application Data\MathWorks\MATLAB\R12\mexopts.bat" is being updated from D:\MATLAB6P1\BIN\WIN32\mexopts\msvc60opts.bat...

删除的内容: (

删除的内容: )

删除的内容: 1

删除的内容:

删除的内容:

删除的内容:

Page 108: Matlab Simulink

第 3章 将 m程序转换成独立的应用 95

Installing the MATLAB Visual Studio add-in ...

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.awx from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.awx

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.hlp from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.hlp

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\addins\MATLABAddin.dll from D:\MATLAB6P1\BIN\WIN32\MATLABAddin.dll Merged D:\MATLAB6P1\BIN\WIN32\usertype.dat

with C:\Program Files\Microsoft Visual Studio\common\msdev98\bin\usertype.dat Note: If you want to use the MATLAB Visual Studio add-in with the MATLAB C/C++Compiler, you must start MATLAB and run the following commands: cd(prefdir); mccsavepath; (You only have to do this configuration step once.)

编译器只需选择一次,除非用户想选择其他的编译器。MATLAB R12.1支持的 C/C++编译器有很多种,对于Windows 95/98/2000/NT操作系统来说,包括:

MATLAB自带的 Lcc C version 2.4 Watcom C/C++ versions 10.6 & 11.0 Borland C++ versions 5.0, 5.2, 5.3, 5.4, & 5.5 Microsoft Visual C++(MSVC) versions 5.0 & 6.0 对于 UNIX平台来说,包括:

GNU C compiler, gcc(HP和 SGI64工作站除外) 所有 UNIX平台系统自带的 ANSI C compiler 所有 U N IX 平台自带的 C++ com piler(Linux除外)

Linux平台上的 GNU C++ compiler, g++ 如果想知道有关 MATLAB 支持的所有编译器的最新信息,请登录网址

http://www.mathworks.com/support/tech-notes/v5/1600/1601.shtml查询。 mex –setup 命令让用户指定对应所选编译器的编译选项文件,放在目录

<UserProfile>\Application Data\MathWorks\MATLAB\R12(对 Windows 操作系统而言)下,或者$HOME/.matlab/R12 (对 UNIX平台而言)中,供以后用 mex/mcc命令编译文件时使用。若想使 Microsoft Visual C++开发环境中出现如图 3.2 所示的 MATLAB Project Wizard插件,则还需运行如下两条命令:

>> cd(prefdir) >> mccsavepath

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (不需要缩进,下同)

Page 109: Matlab Simulink

从Matlab/Simulink模型到代码实现 96

该插件的用途在后面会讲到。

>> mbuild -setup Please choose your compiler for building standalone MATLAB applications: Would you like mbuild to locate installed compilers [y]/n? y Select a compiler: [1] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc [2] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio [0] None Compiler: 2 Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: C:\Program Files\Microsoft Visual Studio Are these correct?([y]/n): y The default options file:

"C:\Documents and Settings\Yongchun\Application Data\MathWorks\MATLAB\R12\compopts.bat" is being updated from D:\MATLAB6P1\BIN\WIN32\mbuildopts\ msvc60compp.bat... Installing the MATLAB Visual Studio add-in ...

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.awx from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.awx

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.hlp from D:\MATLAB6P1\BIN\WIN32\MATLABWizard.hlp

Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\addins\MATLABAddin.dll from D:\MATLAB6P1\BIN\WIN32\MATLABAddin.dll Merged D:\MATLAB6P1\BIN\WIN32\usertype.dat

with C:\Program Files\Microsoft Visual Studio\common\msdev98\bin\usertype.dat

mbuild –setup 命令让用户指定对应所选编译器的编译选项文件,放在目录<UserProfile>\Application Data\MathWorks\MATLAB\R12(对 Windows 操作系统而言)下,或者$HOME/.matlab/R12中(对 UNIX平台而言),供以后用 mbuild/mcc命令编译 m文件时使用。

删除的内容:

删除的内容: ,

删除的内容: 我们

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 110: Matlab Simulink

第 3章 将 m程序转换成独立的应用 97

图 3.2 MATLAB Project Wizard

3.2 从 m程序自动生成独立的应用 和 C/C++源代码

【例 7】设计一个 16阶 Butterworth滤波器,要求采样频率 Fs=16kHz,从 1.5kHz到5kHz 带通,作出其频率响应图,并将该 m 程序转成独立的应用程序和对应的 C/C++源 代码。

function designbutworth %designbutworth.m %used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz %passband with a sampling rate 16kHz. Fs=16; [b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass') freqz(b,a,512,16000) >> designbutworth b = Columns 1 through 6 0.0040 0 -0.0320 0 0.1120 0

删除的内容:

删除的内容: kHz

删除的内容:

删除的内容:

删除的内容: kHz

删除的内容:

删除的内容: kHz

删除的内容: KHz

删除的内容: KHz

删除的内容: (大写 K按规定要改成小写,此处是否能

改?)

删除的内容: KHz

Page 111: Matlab Simulink

从Matlab/Simulink模型到代码实现 98

Columns 7 through 12 -0.2241 0 0.2801 0 -0.2241 0 Columns 13 through 17 0.1120 0 -0.0320 0 0.0040 a = Columns 1 through 6 1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 Columns 7 through 12 8.8294 -6.6792 4.5314 -2.7004 1.3838 -0.6100 Columns 13 through 17 0.2342 -0.0737 0.0181 -0.0032 0.0004

滤波器幅频响应和相频响应如图 3.3所示。

图 3.3 滤波器幅频响应和相频响应

>> mcc -B sgl designbutworth.m

删除的内容: 分页符

Page 112: Matlab Simulink

第 3章 将 m程序转换成独立的应用 99

命令 mcc –B sgl将函数 m文件编译生成独立的应用和对应的 C代码,生成的目录和文件包括:

bin

bilinear.c

freqz.c

buffer_mex_interface.c

freqzplot.c

buttap.c

signal_private_dividenowarn.c

butter.c

signal_private_db.c

datawrap.c

psdoptions.c

designbutworth.c

lp2lp.c

designbutworth_mainhg.c

signal_private_iirchk.c

subplot.c

lp2hp.c

lp2bs.c

lp2bp.c

designbutworth.exe

designbutworth.h

lp2bs.h

lp2bp.h

datawrap.h

lp2hp.h

butter.h

lp2lp.h

buttap.h

psdoptions.h

buffer_mex_interface.h

signal_private_db.h

bilinear.h

signal_private_dividenowarn.h

freqz.h

signal_private_iirchk.h

freqzplot.h

删除的内容:

Page 113: Matlab Simulink

从Matlab/Simulink模型到代码实现 100

subplot.h

在 bin目录下有两个 MATLAB图形文件:FigureMenuBar.fig和 FigureToolBar.fig,用于在执行 designbutworth.exe 时指定如何生成菜单和工具条。在发布应用程序时,该目录应该保存在 designbutworth.exe 所在的目录中,否则会出现警告信息,并且使得菜单和工具条无法显示。

>> !designbutworth b = Columns 1 through 7 0.0040 0 -0.0320 0 0.1120 0 -0.2241 Columns 8 through 14 0 0.2801 0 -0.2241 0 0.1120 0 Columns 15 through 17 -0.0320 0 0.0040 a = Columns 1 through 7 1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294 Columns 8 through 14 -6.6792 4.5314 -2.7004 1.3838 -0.6100 0.2342 -0.0737 Columns 15 through 17 0.0181 -0.0032 0.0004

菜单和工具条可以正确显示,如图 3.4所示。

Page 114: Matlab Simulink

第 3章 将 m程序转换成独立的应用 101

图 3.4 菜单和工具条可以正确显示

>> !del bin E:\material\book\example7\bin\*, 是否确认 (Y/N) ? y y >> !designbutworth b = Columns 1 through 7 0.0040 0 -0.0320 0 0.1120 0 -0.2241 Columns 8 through 14 0 0.2801 0 -0.2241 0 0.1120 0 Columns 15 through 17 -0.0320 0 0.0040 a = Columns 1 through 7 1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294 Columns 8 through 14

Page 115: Matlab Simulink

从Matlab/Simulink模型到代码实现 102

-6.6792 4.5314 -2.7004 1.3838 -0.6100 0.2342 -0.0737 Columns 15 through 17 0.0181 -0.0032 0.0004 Warning: Unable to find FigureToolBar.fig on path - not adding built-in toolbar. Warning: Unable to find FigureMenuBar.fig on path - not adding built-in menus. Warning: Unable to find FigureToolBar.fig on path - not adding built-in toolbar.

命令行显示警告信息,菜单和工具条无法显示,如图 3.5所示。

图 3.5 菜单和工具条无法显示

>> mcc -B sglcpp designbutworth.m

命令 mcc –B sglcpp将函数 m文件编译生成独立的应用和对应的 C++代码,生成的目录和文件包括:

bin bilinear.cpp freqz.cpp buffer_mex_interface.cpp freqzplot.cpp buttap.cpp signal_private_dividenowarn.cpp butter.cpp signal_private_db.cpp

删除的内容:

删除的内容:

Page 116: Matlab Simulink

第 3章 将 m程序转换成独立的应用 103

datawrap.cpp psdoptions.cpp designbutworth.cpp lp2lp.cpp designbutworth_mainhg.cpp signal_private_iirchk.cpp subplot.cpp lp2hp.cpp lp2bs.cpp lp2bp.cpp designbutworth.exe designbutworth.hpp lp2bs.hpp lp2bp.hpp datawrap.hpp lp2hp.hpp butter.hpp lp2lp.hpp buttap.hpp psdoptions.hpp buffer_mex_interface.hpp signal_private_db.hpp bilinear.hpp signal_private_dividenowarn.hpp freqz.hpp signal_private_iirchk.hpp freqzplot.hpp subplot.hpp >> which mcc D:\MATLAB6p1\toolbox\compiler\mcc.dll >> help mcc MCC MATLAB to C/C++ Compiler (Version 2.2). MCC [-options] fun [fun2 ...] [mexfile1 ...] [mlibfile1 ...] Translate fun.m to fun.c or fun.cpp, and optionally create any Supported binary file. Write any resulting files into the current directory, by default. If more than one M-file is specified, a C or C++ file is generated for each M-file.

删除的内容:

删除的内容:

Page 117: Matlab Simulink

从Matlab/Simulink模型到代码实现 104

If C or object files are specified, they are passed to MEX or MBUILD along with any generated C files. If MEX-files are specified, MCC will generate wrapper code so that calls can be made from compiled M-files to the specified MEX-files. Also, if a MEX-file and an M-file with the same base name are located in the same directory, specifying the MEX-file causes MCC to use it instead of the M-file. Otherwise MCC favors M-files over MEX-files. MLIB files describe the functions in a shared library created by MCC (see -Wlib below). Specifying an MLIB file tells MCC to link to the MLIB file's corresponding shared library whenever it needs to use any of the functions found in that library. The MLIB file and its corresponding shared library file must be located within the same directory. If conflicting options are presented to MCC, the rightmost conflicting option is used. In order to assist in migrating to this new release, we have prepared a quick-reference card which contains the Compiler 2.2 options. You can access this pdf file by selecting "Online Manuals" from the HELPDESK. OPTIONS: A <option> Specify annotation. The following table shows valid <option>strings and their effects: annotation:all (*) - All lines from source M-file appears as comments in generated output file. annotation:comments - Comments from source M-file appear as comments in generated output file. annotation:none - No text from source M-file appears in generated output file. line:on - #line directives appear in generated output file which map lines in source M- code to lines in output file. line:off (*) - No such #line directives are generated. debugline:on - Run-time error messages report the source file name and line number where they occurred. debugline:off (*) - Run-time error messages do not report any

删除的内容:

删除的内容:

删除的内容:

Page 118: Matlab Simulink

第 3章 将 m程序转换成独立的应用 105

information about the source where they occurred. (*) indicates default setting. B <filename> Specify bundle file. <filename> is a text file containing Compiler command line options. The Compiler behaves as if the "-B <filename>" were replaced by the contents of the bundle file. Newlines appearing in these files are allowed and are treated as whitespace.The MathWorks provides options files for the following: sgl Used for building stand-alone C Graphics Library applications sglcpp Used for building stand-alone C++ Graphics Library applications pcode Used for building MATLAB P-Code files. c C only. Translate M-file to C, but do not produce a MEX-file or stand-alone application. This is equivalent to "-T codegen" as the rightmost argument on the command line. d <directory> Output directory. All generated files will be put in <directory>. F list. List the <option>s available in the next form of the command, together with their current values and a short explanation. F <option>:<number> Typesetting format options. Assign the value <number> to the formatting option <option>. See "F list" for <option>s. f <filename> Use the specified options file when calling MEX or MBUILD. This allows you to use different ANSI compilers. This option is a direct pass-through to the MEX or MBUILD script. See the "Application Program Interface Guide" for more information. G Debug only. Simply turn debugging on, so debugging symbol information is included. g Debug. Include debugging symbol information. This option also includes the -A debugline:on switch. This will have an impact on performance of the generated code. If you wish to have debugging information, but do not want the performance degradation associated with the debug line information use: -g -A debugline:off. This option also includes the -O none switch. That switch causes all compiler optimizations to be turned off.

删除的内容:

删除的内容:

删除的内容:

Page 119: Matlab Simulink

从Matlab/Simulink模型到代码实现 106

If you wish to have some optimizations on, you may specify them after the debug switch. h Compile helper functions. All M-functions called will be compiled into the resulting MEX-file or stand-alone application. I <path> Include path. Add <path> to the list of paths to search for M-files. The MATLAB path is automatically included when running from MATLAB, but NOT when running from DOS or the Unix shell. See "help mccsavepath". L <option> Language. Specifies target language. <option> can be "C"for C,"Cpp" for C++, or "P" for MATLAB P-code. l Line. Generates code that reports file name and line numbers on run-time errors. (Equivalent to -A debugline:on) m Macro that generates a C stand-alone application. This is equivalent to the options "-t -W main -L C -h -T link:exe

libmmfile.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/ macro_option_m.

Note: the "-h" means that helper functions will be included. M "<string>" Pass <string> to the MBUILD or MEX script used to build an executable. If -M is used multiple times, the rightmost occurrence is used. o <outputfilename> Output name. Set the name of the final executable output (MEX or stand-alone application) to <outputfilename>. A suitable,possibly platform-dependent, extension is added to <outputfilename> (e.g., ".exe" for PC stand-alone applications, ".mexsol" for Solaris MEX-files). O <optimization> Optimization. There are three possibilities: <optimization class>:[on|off] - Turns the class on or off For example: -O fold_scalar_mxarrays:on list - Lists the available optimization classes. <optimization level> - Uses a bundle file called

opt_bundle_<level> to determine which optimizations are on or off.

删除的内容:

删除的内容:

Page 120: Matlab Simulink

第 3章 将 m程序转换成独立的应用 107

For example "-O all" looks for a bundle file called opt_bundle_all and uses the switches present. The current optimization levels are "all" and "none". The default is to have all optimizations on. p Macro that generates C++ stand-alone application. This is equivalent to the options "-t -W main -L Cpp -h -T link:exe libmmfile.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/

macro_option_p. Note: the "-h" means that helper functions will be included. S Macro that generates Simulink C-MEX S-Function. This is equivalent to the options "-t -W simulink -L C -T link:mex libmatlbmx.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/

macro_option_S. Note: the absence of "-h" means that helper functions will not be included. t Translate M code to target language. Translate any M-functions specified on the command line to C or C++ functions. This option is included in all macro options. Omitting it allows the generation of wrapper C/C++files without generating the C/C++ files corresponding to M-files. T <option> Specify target phase and type. The following table shows valid <option> strings and their effects: codegen - translate M-files to C/C++ files and generate a wrapper file. (This is the default -T setting.) compile:mex - same as codegen, plus compile C/C++ files to object form suitable for linking into a SIMULINK S-function MEX-file. compile:mexlibrary - same as codegen, plus compile C/C++ files to object form suitable for linking into an ordinary (non-S-function) MEX-file. compile:exe - same as codegen, plus compile C/C++ files to object form suitable for linking into a standalone executable. compile:lib - same as codegen, plus compile C/C++ files to object form suitable for linking into a shared library/DLL. link:mex - same as compile:mex, plus link object files into a SIMULINK S-function MEX-file.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 121: Matlab Simulink

从Matlab/Simulink模型到代码实现 108

link:mexlibrary - same as compile:mexlibrary, plus link object files into an ordinary (non S-function) MEX-file. link:exe - same as compile:exe, plus link object files into a standalone executable. link:lib - same as compile:lib, plus link object files into a shared library/DLL. u <number> Specify that the number of inputs to a generated Simulink S-function should be <number>. Valid only if either "- S" or "-W simulink" option has also been specified. v Verbose. Show compilation steps. w list. List the <msg> strings allowed in the next form of the command,together with the full text of the warning messages to which they correspond. w <option>[:<msg>] Warnings. The possible options are "enable", "disable",and "error". If "enable:<msg>" or "disable:<msg>" is specified, enable or disable the warning associated with <msg>. If "error:<msg>" is specified, enable the warning associated with <msg> and treat any instances of that warning as an error. If the <option> but not ":<msg>"is specified, the Compiler applies the action to all warning messages. For backward compatibility with previous Compiler revisions,"-w" (with no option) is the same as "-w enable". W <option> Wrapper functions. Specify which type of wrapper file should be generated by the Compiler. <option> can be one of "mex", "main","simulink", "lib:<string>", or "none" (default). For the lib wrapper,<string> contains the name of the shared library to build. When generating a "lib" wrapper, MCC also creates an MLIB file describing the functions in the shared library. x Macro that generates a MEX file. This is equivalent to the options "-t -W mex -L C -T link:mex libmatlbmx.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/ macro_option_x. Note: the absence of "-h" means that helper functions will not be included. y <number> Specify that the number of outputs from a generated Simulink S-function should be <number>. Valid only if either "- S" or "-W simulink" option has also been specified.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 122: Matlab Simulink

第 3章 将 m程序转换成独立的应用 109

Y <license.dat file> Override default license.dat file with specified argument. z <path> Specify the path to use for library and include files. This option uses the specified path for the Compiler libraries instead of MATLABROOT. ? Help. Display this help message. EXAMPLES: Make a C translation and a MEX-file for myfun.m: mcc -x myfun Make a C translation and a stand-alone executable for myfun.m: mcc -m myfun Make a C++ translation and a stand-alone executable for myfun.m: mcc -p myfun Make a C translation and a Simulink S-function for myfun.m (using dynamically sized inputs and outputs): mcc -S myfun Make a C translation and a Simulink S-function for myfun.m (explicitly calling for one input and two outputs): mcc -S -u 1 -y 2 myfun Make a C translation and stand-alone executable for myfun.m. Look for myfun.m in the directory /files/source, and put the resulting C files and executable in the directory /files/target: mcc -m -I /files/source -d /files/target myfun Make a C translation and a MEX-file for myfun.m. Also translate and include all M-functions called directly or indirectly by myfun.m. Incorporate the full text of the original M-files into their corresponding C files as C comments: mcc -x -h -A annotation:all myfun Make a generic C translation of myfun.m: mcc -t -L C myfun

Page 123: Matlab Simulink

从Matlab/Simulink模型到代码实现 110

Make a generic C++ translation of myfun.m: mcc -t -L Cpp myfun Make a C MEX wrapper file from myfun1.m and myfun2.m: mcc -W mex -L C libmatlbmx.mlib myfun1 myfun2 Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (using one mcc call): mcc -m myfun1 myfun2 Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (by generating each output file with a separate mcc call). Note that the MLIB file "libmmfile.mlib" only needs to be specified when generating a wrapper file, and when linking the final executable: mcc -t -L C myfun1 % yields myfun1.c mcc -t -L C myfun2 % yields myfun2.c mcc -W main -L C myfun1 myfun2 libmmfile.mlib % yields myfun1_main.c mcc -T compile:exe myfun1.c % yields myfun1.o mcc -T compile:exe myfun2.c % yields myfun2.o mcc -T compile:exe myfun1_main.c % yields myfun1_main.o mcc -T link:exe myfun1.o myfun2.o myfun1_main.o libmmfile.mlib Make a shared/dynamically linked library called "liba" from a0.m and a1.m,where neither a0 nor a1 calls functions in libmmfile: mcc -t -W lib:liba -T link:lib a0 a1 Make a shared/dynamically linked library called "liba" from a0.m and a1.m, where at least one of a0 or a1 calls at least one function in libmmfile. Define LIBMMFILE to be 1 when compiling the C code.: mcc -t -W lib:liba -T link:lib a0 a1 libmmfile.mlib -M "-DLIBMMFILE=1" Make a C translation and a stand-alone graphics library executable from myfun.m (using one mcc call): mcc -B sgl myfun1 Make a C++ translation and a stand-alone graphics library executable from myfun.m (using one mcc call): mcc -B sglcpp myfun1 Make a shared/dynamically linked library called "liba" from a0.m and a1.m that makes calls into the MATLAB C/C++ Graphics Library: mcc -B sgl -t -W libhg:liba -T link:lib a0 a1

删除的内容:

删除的内容:

Page 124: Matlab Simulink

第 3章 将 m程序转换成独立的应用 111

Note: on PCs, filenames ending with .o above would actually end with .obj. See also COMPILER/FUNCTION, MCCSAVEPATH, REALONLY, REALSQRT, REALLOG, REALPOW, COMPILER_SURVEY, COMPILER_BUG_REPORT, MEX, MBUILD.

3.3 不是所有的 m程序都能转换成 C/C++代码

应该指出的是,到MATLAB R12.1为止,MATLAB Compiler并不能将所有的 m程序转换成 C/C++代码或者独立的应用。

首先,它不能转换脚本 m 文件(当然,这并不存在很大的问题,因为脚本 m 文件很容易改写成函数 m文件),而只能转换函数 m文件,并且函数 m文件最好不要带输入参数。如果确实需要输入参数,可以让 m 函数带一个字符串参数(如果确实想输入多个参数,用法请见附录)。

【例 8】按给定的偶数阶数设计一个 Butterworth 滤波器,要求阶数大于 16,采样频率 Fs=16kHz,1.5kHz~5kHz 带通,作出其频率响应图,并将该 m 程序转成独立的应用程序和对应的 C源代码。

function dsgnbutworth_varorder(order) %dsgnbutworth_varorder.m %used to design a Butterworth filter,which has a variable %even order(>=16)and a 1.5kHz-5kHz passband with a sampling %rate 16kHz. if order<16|(mod(order,2)~=0) disp('The order should be an even integer,not less than 16!'); return; end Fs=16; [b,a]=butter(order/2,[1.5/(Fs/2) 5/(Fs/2)],'bandpass') freqz(b,a,512,16000) >> dsgnbutworth_varorder(14) The order should be an even integer,not less than 16! >> dsgnbutworth_varorder(15) The order should be an even integer,not less than 16! >> dsgnbutworth_varorder(16) b =

带格式的

带格式的

删除的内容:

删除的内容: 分页符

删除的内容: (

删除的内容: )

删除的内容: 。

删除的内容: A。

删除的内容: kHz

删除的内容:

删除的内容: 从

删除的内容: kHz

删除的内容: 到

删除的内容: kHz

删除的内容: KHz

删除的内容: KHz

删除的内容: KHz

删除的内容: ~

删除的内容: 此处是否有上标

删除的内容:

Page 125: Matlab Simulink

从Matlab/Simulink模型到代码实现 112

Columns 1 through 7 0.0040 0 -0.0320 0 0.1120 0 -0.2241 Columns 8 through 14 0 0.2801 0 -0.2241 0 0.1120 0 Columns 15 through 17 -0.0320 0 0.0040 a = Columns 1 through 7 1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294 Columns 8 through 14 -6.6792 4.5314 -2.7004 1.3838 -0.6100 0.2342 -0.0737 Columns 15 through 17 0.0181 -0.0032 0.0004

滤波器的幅频响应和相频响应如图 3.6所示。 >> mcc -B sgl dsgnbutworth_varorder.m >> !dir /w /b dsgnbutworth_varorder.exe dsgnbutworth_varorder.exe >> !dsgnbutworth_varorder 14 Warning: COLON arguments must be real scalars. ERROR: Matrix dimensions must agree. EXITING >> !dsgnbutworth_varorder 15 The order should be an even integer,not less than 16! >> !dsgnbutworth_varorder 16 Warning: COLON arguments must be real scalars. 删除的内容:

图 3.6 滤波器的频率响应

Page 126: Matlab Simulink

第 3章 将 m程序转换成独立的应用 113

ERROR: Matrix dimensions must agree. EXITING

图 3.6 滤波器的频率响应

mcc 命令在将 dsgnbutworth_varorder.m 程序转成独立的应用程序 dsgnbutworth_ varorder.exe时,会将 dsgnbutworth_varorder.m中的参数 order解释成一个字符串,所以执行 dsgnbutworth_varorder.exe以后,得到的结果就不正确了。可对 dsgnbutworth_varorder.m作如下修改,然后再用 mcc命令编译:

function dsgnbutworth_varorder(order) %dsgnbutworth_varorder.m %used to design a Butterworth filter,which has a variable %even order(>=16)and a 1.5kHz-5kHz passband with a sampling %rate 16kHz. if ischar(order) disp('The input argument is always taken as a string when converting'); disp('m function to console Application!'); order=str2num(order); end if order<16|(mod(order,2)~=0) disp('The order should be an even integer,not less than 16!'); return; end

删除的内容:

删除的内容: KHz

删除的内容: KHz

删除的内容: KHz

删除的内容:

删除的内容: (必须和上一行在同一行,否则是程序是有

语法错误的)

删除的内容: (程序必须和我给你的原文完全一致,不能

因为排版而分行,否则可能

出现语法错误!!!其它的

程序与此处同)

删除的内容:

Page 127: Matlab Simulink

从Matlab/Simulink模型到代码实现 114

Fs=16; [b,a]=butter(order/2,[1.5/(Fs/2) 5/(Fs/2)],'bandpass') freqz(b,a,512,16000) >> mcc -B sgl dsgnbutworth_varorder.m >> !dsgnbutworth_varorder 14 The input argument is always taken as a string when converting m function to console Application! The order should be an even integer,not less than 16! >> !dsgnbutworth_varorder 15 The input argument is always taken as a string when converting m function to console Application! The order should be an even integer,not less than 16! >> !dsgnbutworth_varorder 16 The input argument is always taken as a string when converting m function to console Application! b = Columns 1 through 7 0.0040 0 -0.0320 0 0.1120 0 -0.2241 Columns 8 through 14 0 0.2801 0 -0.2241 0 0.1120 0 Columns 15 through 17 -0.0320 0 0.0040 a = Columns 1 through 7 1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294 Columns 8 through 14 -6.6792 4.5314 -2.7004 1.3838 -0.6100 0.2342 -0.0737

Page 128: Matlab Simulink

第 3章 将 m程序转换成独立的应用 115

Columns 15 through 17 0.0181 -0.0032 0.0004

滤波器的频率响应如图 3.7所示。

图 3.7 修改后得到的滤波器频率响应

其次,即使是满足上述要求的 m函数,要用 MATLAB Compiler转成 C/C++源代码或者独立的应用,编写时也有一些限制。

不能使用MATLAB对象。

修改【例 7】,把设计出的滤波器转换成直接 II型结构:

function designbutworthand2df2 %designbutworthand2df2.m %used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz passband %a sampling rate 16kHz, then construct a direct-form II object. Fs=16; [b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass'); h=df2(b,a)

编译它,结果如下: >> mcc -B sgl designbutworthand2df2.m Warning: File: designbutworthand2df2 Line: 7 Column: 3 The MATLAB Compiler does not currently support MATLAB object-oriented programming. References to the method "df2" will produce a run-time error. MATLAB Complier当前不能支持面向对象的编程,调用函数 df2,会产生运行时的

删除的内容: 分页符

删除的内容: KHz

删除的内容: KHz

删除的内容:

删除的内容: KHz

删除的内容:

删除的内容:

Page 129: Matlab Simulink

从Matlab/Simulink模型到代码实现 116

错误 >> !designbutworthand2df2 ERROR: Undefined function or variable 'df2'. EXITING

不能用 input或者 eval操作 MATLAB工作空间变量,对于没有使用 MATLAB工作空间变量的 input和 eval命令,能够正确地编译和执行。例如:

function testinputandeval R = input('Input MATLAB expression: ','s'); R eval(R);

编译并不显示错误信息,但是如果输入MATLAB工作空间的变量,则运行出错。 >> mcc -B sgl testinputandeval >> a='sin(10)' a = sin(10) >> !testinputandeval Input MATLAB expression: a R = a ERROR: Reference to unknown function or variable 'a' while evaluating expression. EXITING >> !testinputandeval Input MATLAB expression: sin(10) R = sin(10)

删除的内容:

Page 130: Matlab Simulink

第 3章 将 m程序转换成独立的应用 117

ans = -0.5440

不能动态地命名变量,然后用 load或者 save命令来操作,例如: function testls %testls.m y= 'a'; load('testls.mat',y);

假设 a是存储在 MATLAB数据文件 testls.mat中的一个变量,程序就无法正确地编译和执行。

>> mcc -B sgl testls.m Warning: File: E:\book\testls.m Line: 3 Column: 19 The load statement cannot be translated unless it specifically lists the names of variables to be loaded as constant strings. >> !testls ERROR: Run-time Error: File: E:\book\testls.m Line: 3 Column: 19 The load statement did not specifically list the names of variables to be loaded as constant strings. EXITING

但是 function testls %testls.m load('testls.mat','a'); a

可以正确地编译和执行。 >> mcc -B sgl testls.m >> !testls ans = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22

Page 131: Matlab Simulink

从Matlab/Simulink模型到代码实现 118

10 12 19 21 3 11 18 25 2 9

当然有一些第三方的软件产品,扩展了 MATLAB Compiler 的能力,例如MATCOM。使几乎所有用 MATCOM m的程序,包括脚本 m文件和函数 m文件都可以转成独立的应用和 C/C++源代码。

3.4 从 VC++中调用 m函数

为了能够从 VC++中调用 m 函数,首先要正确地使用 mex –setup、cd(prefdir)、mccsavepath和 mbuild –setup命令选择 Microsoft Visual C++ (MSVC)versions 5.0 & 6.0编译器(关于如何操作前文已有所论述)。如果已经正确地选择了 Microsoft Visual C++ (MSVC)versions 6.0,请按如下步骤继续(选择 Microsoft Visual C++(MSVC) versions 5.0时的操作步骤与此类同)。

步骤 1. 在 Microsoft Visual C++ IDE 中,使用 File|New...菜单命令,选择 MATLAB Project Wizard,如图 3.8所示。在正确填写相关参数后,单击 OK按钮,进入图 3.9所示界面。

图 3.8 MATLAB Project Wizard

步骤 2. 如图 3.9所示设置各选择项,然后单击 Finish按钮,进入图 3.10所示界面。 步骤 3. 在图 3.10 所示界面中单击 OK 按钮,进入如图 3.11 所示的 m 文件选择对

话框。 步骤 4. 在图 3.11所示对话框中选择需要调用的 m函数(该函数最好不带参数,或者

仅带一个字符串参数),进入图 3.12所示的编译日志显示界面。

带格式的

带格式的

带格式的

带格式的

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: (

删除的内容: )

删除的内容: )

删除的内容: (

删除的内容: )

Page 132: Matlab Simulink

第 3章 将 m程序转换成独立的应用 119

图 3.9 MATLAB Project Wizard 项目设置

图 3.10 New Project Information

图 3.11 选择 m文件

删除的内容: 分页符

Page 133: Matlab Simulink

从Matlab/Simulink模型到代码实现 120

图 3.12 mcc-log.txt

步骤 5. 如果在步骤 4中选择了 plotfreq.m文件,其内容如图 3.13所示,那么现在可以看到在 VC++中生成的工程文件,如图 3.14所示。

图 3.13 plotfreq.m

步骤 6. 在Microsoft Visual C++ IDE中编译并且运行图 3.14所示界面中的工程文件,结果如图 3.15所示。

在编译连接 plotfreqprj.exe 的过程中,在 plotfreqprj.exe 所在的目录中会创建一个 bin目录,该目录中包含两个文件——FigureMenuBar.fig 和 FigureToolBar.fig。在发布plotfreqprj.exe 文件时,必须保证 bin 目录(包括它下面的文件 FigureMenuBar.fig 和FigureToolBar.fig)位于执行文件所在的目录,否则菜单和工具条无法显示。执行图 3.16所示的操作,得到的结果如图 3.16和图 3.17所示。与图 3.15相比,图 3.17中没有显示菜单和工具条。

带格式的

带格式的

删除的内容: 我们

删除的内容: 我们

删除的内容: (

删除的内容: )

删除的内容: 中的

Page 134: Matlab Simulink

第 3章 将 m程序转换成独立的应用 121

图 3.14 与 plotfreq.m对应的 VC++工程文件

图 3.15 plotfreqprj.exe运行结果

Page 135: Matlab Simulink

从Matlab/Simulink模型到代码实现 122

图 3.16 去掉 bin目录后执行 plotfreqprj.exe

图 3.17 去掉 bin目录后执行 plotfreqprj.exe显示的结果

3.5 从 VC++中调用MATLAB C Math Library

本节以Microsoft Visual C++ 6.0为例,讲解从 VC++中调用MATLAB C Math Library的步骤(Microsoft Visual C++ 5.0的情况与此类同)。

从Win32控制台程序调用MATLAB C Math Library

步骤 1. 使用 Microsoft Visual C++ IDE中的菜单命令 File|New…选择 Win32 Console 带格式的

删除的内容: (

删除的内容: )

Page 136: Matlab Simulink

第 3章 将 m程序转换成独立的应用 123

Application,如图 3.18所示。正确填充参数后,单击 OK按钮,进入图 3.19所示界面。

图 3.18 Win32 Console Application

图 3.19 Win32 Console Application选项设置

步骤 2. 在图 3.19所示界面中选择 A “Hello,World!” application,单击 Finish按钮,进入图 3.20所示界面。

步骤 3. 在图 3.20所示界面中单击 OK按钮,生成如图 3.21所示的工程文件。 步骤 4. 使用 Microsoft Visual C++ IDE中的菜单命令 Project|Add To Project|New…向

consoleprj工程中添加一个新文件 mysvd.cpp,如图 3.22所示。

带格式的

带格式的

带格式的

Page 137: Matlab Simulink

从Matlab/Simulink模型到代码实现 124

图 3.20 New Project Information

图 3.21 consoleprj工程文件

Page 138: Matlab Simulink

第 3章 将 m程序转换成独立的应用 125

图 3.22 添加新文件 mysvd.cpp

步骤 5. 如图 3.23所示编辑 mysvd.cpp,该文件主要是调用 MATLAB C Math Library中的函数实现类似于 MATLAB 函数 svd 的对矩阵进行奇异值分解的功能。关于如何调用MATLAB C Math Library中的函数,请参考MATLAB的 PDF帮助文档 cmath_ref2b.pdf和cmath_ug2b.pdf(在MATLAB安装盘的 Document盘中)。mysvd.cpp的内容如下:

#include "stdafx.h" #include "matlab.h" static double data[] = { 21, 3, 15, 57, 12, 83, 6, 90 }; int mysvd() { /* Initialize pointers to array arguments */ mxArray *X = NULL; mxArray *U = NULL, *S = NULL, *V = NULL; mlfEnterNewContext(0, 0); mlfAssign(&X, mlfDoubleMatrix(4, 2, data, NULL)); /* Compute the singular value decomposition and print it */ mlfAssign(&S, mlfSvd(NULL, NULL, X, NULL)); mlfPrintf("One input, one output:\n"); mlfPrintf("S = \n"); mlfPrintMatrix(S); /* Multiple output arguments */ mlfAssign(&U, mlfSvd(&S, &V, X, NULL)); mlfPrintf("One input, three outputs:\n"); mlfPrintf("U = \n"); mlfPrintMatrix(U);

带格式的

删除的内容: (

删除的内容: )

Page 139: Matlab Simulink

从Matlab/Simulink模型到代码实现 126

mlfPrintf("S = \n"); mlfPrintMatrix(S); mlfPrintf("V = \n"); mlfPrintMatrix(V); /* Multiple input and output arguments */ mlfAssign(&U, mlfSvd(&S, &V, X, mlfScalar(0.0))); mlfPrintf("Two inputs, three outputs:\n"); mlfPrintf("U = \n"); mlfPrintMatrix(U); mlfPrintf("S = \n"); mlfPrintMatrix(S); mlfPrintf("V = \n"); mlfPrintMatrix(V); mxDestroyArray(X); mxDestroyArray(U); mxDestroyArray(S); mxDestroyArray(V); mlfRestorePreviousContext(0, 0); return(EXIT_SUCCESS); }

图 3.23 mysvd.cpp

步骤 6. 如图 3.24 所示,修改工程文件的主函数。用户可以根据自己的应用程序的需要,添加自己的调用MATLAB C Math Library库函数的算法程序。

带格式的

Page 140: Matlab Simulink

第 3章 将 m程序转换成独立的应用 127

图 3.24 consoleprj.cpp

步骤 7. 使用 Microsoft Visual C++ IDE中的菜单命令 Tools|Options…添加一个头文件搜索路径%MATLABROOT%\extern\include(该路径中有调用 MATLAB C/C++ Math Library库函数需要的头文件),如图 3.25所示。

步骤 8. 使用 Microsoft Visual C++ IDE中的菜单命令 Tools|Options…添加一个库文件搜索路径%MATLABROOT%\extern\lib\win32\Microsoft\msvc60 (如果是 Microsoft Visual C++ 5.0,添加的路径应该是%MATLABROOT%\extern\lib\ win32\Microsoft\msvc50,这两个目录中有调用MATLAB C/C++ Math Library库函数需要的库文件),如图 3.26所示。

步骤 9. 如图 3.27 所示,使用 Microsoft Visual C++ IDE 中的菜单命令 Project| Settings…将目录%MATLABROOT%\extern\lib\win32\Microsoft\msvc60 下的所有库文件libmmfile.lib、 libmwarpack.lib、 libeng.lib、 libmwlapack.lib、 libmat.lib、 libmwsglm.lib、libmatlb.lib、libmx.lib、libmatlbmx.lib、sgl.lib和 libmex.lib添加到 Link页面 Object/library modules 编辑框中原有库的后面(如果是 Microsoft Visual C++ 5.0,添加的应该是目录%MATLABROOT%\extern\lib\win32 \Microsoft\msvc50下所有的库文件)。

步骤 10. 现在可以编译连接运行工程文件,结果如图 3.28所示。

带格式的

带格式的

带格式的

带格式的

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 141: Matlab Simulink

从Matlab/Simulink模型到代码实现 128

图 3.25 添加头文件搜索路径%MATLABROOT%\extern\inlcude

图 3.26 添加库文件搜索路径%MATLABROOT%\extern\lib\win32\Microsoft\msvc60

图 3.27 添加库文件

删除的内容:

删除的内容:

删除的内容: 步骤 9. 如图3.27所示,使用Microsoft Visual C++ IDE中的菜单命令 Project|Settings…将目录%MATLABROOT%\extern\lib\win32\Microsoft\msvc60 下的所有库文件 libmmfile.lib、libmwarpack.lib、libeng.lib、libmwlapack.lib、libmat.lib、libmwsglm.lib、libmatlb.lib、libmx.lib、libmatlbmx.lib、sgl.lib和 libmex.lib添加到Link页面 Object/library modules编辑框中原有库的后面(如果是Microsoft Visual C++ 5.0,添加的应该是目录%MATLABROOT%\extern\lib\win32 \Microsoft\msvc50下所有的库文件)。步骤 10. 现在可以编译连接运行工程文件,结果如图

3.28所示。分页符

Page 142: Matlab Simulink

第 3章 将 m程序转换成独立的应用 129

图 3.28 consoleprj.exe运行结果

从MFC Windows应用程序中调用MATLAB C Math Library

步骤 1. 使用Microsoft Visual C++ IDE中的菜单命令 File|New…选择MFC AppWizard (exe),如图 3.29所示。正确填充参数后,单击 OK按钮,进入图 3.30所示界面。

图 3.29 MFC AppWizard (exe)

带格式的

删除的内容: (

删除的内容: )

删除的内容: 分页符

Page 143: Matlab Simulink

从Matlab/Simulink模型到代码实现 130

步骤 2. 在图 3.30所示界面中选择 Single document,后续步骤都按默认状态选择,直至生成如图 3.31所示的工程文件。

图 3.30 选择 Single document

图 3.31 mfcprj工程文件

步骤 3. 修改 mfcprjView.h,在视类定义中添加一行语句:int mysvd(CDC *pDC);,如下所示。

带格式的

带格式的

删除的内容:

删除的内容: 步骤 3. 修改mfcprjView.h,在视类定义中添加一行 int mysvd

删除的内容: (

删除的内容: (CDC *pDC

删除的内容: )

删除的内容: );,如下所示。

删除的内容: 分页符

Page 144: Matlab Simulink

第 3章 将 m程序转换成独立的应用 131

#if !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_) #define AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMfcprjView : public CView { protected: // create from serialization only CMfcprjView(); DECLARE_DYNCREATE(CMfcprjView) // Attributes public: CMfcprjDoc* GetDocument(); // Operations public: int mysvd(CDC *pDC); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMfcprjView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CMfcprjView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions

删除的内容: #if !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INC#LUDED_)define AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__ #INCLUDED_

删除的内容: (请与我给你的原文一致,程序不能随便换

行!!!)

删除的内容:

删除的内容: #if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000

class CMfcprjView : public CView{protected: // create from serialization only

CMfcprjView();

DECLARE_DYNCREATE(CMfcprjView)

// Attributespublic:

CMfcprjDoc* GetDocument();

// Operationspublic:

int mysvd(CDC *pDC);// Overrides

// ClassWizard generated virtual function overrides

//{{AFX_VIRTUAL(CMfcprjView)

public:virtual void OnDraw(CDC*

pDC); // overridden to draw this view

virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

protected:virtual BOOL

OnPreparePrinting(CPrintInfo* pInfo);

virtual void OnBeginPrinting(CDC* pDC, ... [1]

Page 145: Matlab Simulink

从Matlab/Simulink模型到代码实现 132

protected: //{{AFX_MSG(CMfcprjView) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in mfcprjView.cpp inline CMfcprjDoc* CMfcprjView::GetDocument() { return (CMfcprjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous //line. #endif // !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_) 步骤 4. 修改生成的视类的实现代码,主要包括:

添加头文件 matlab.h; 定义静态全局数组; 编写函数 mysvd(CDC *pDC)的实现代码; 在函数 OnDraw(CDC* pDC)中调用函数 mysvd(CDC *pDC)。

// mfcprjView.cpp : implementation of the CMfcprjView class // #include "stdafx.h" #include "mfcprj.h" #include "mfcprjDoc.h" #include "mfcprjView.h" #include "matlab.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static double data[] = { 21, 3, 15, 57, 12, 83, 6, 90 };

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 146: Matlab Simulink

第 3章 将 m程序转换成独立的应用 133

//////////////////////////////////////////////////////////////////////// // CMfcprjView IMPLEMENT_DYNCREATE(CMfcprjView, CView) BEGIN_MESSAGE_MAP(CMfcprjView, CView) //{{AFX_MSG_MAP(CMfcprjView) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() //////////////////////////////////////////////////////////////////////// // CMfcprjView construction/destruction CMfcprjView::CMfcprjView() { // TODO: add construction code here } CMfcprjView::~CMfcprjView() { } BOOL CMfcprjView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } //////////////////////////////////////////////////////////////////////// // CMfcprjView drawing void CMfcprjView::OnDraw(CDC* pDC) { CMfcprjDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc);

Page 147: Matlab Simulink

从Matlab/Simulink模型到代码实现 134

// TODO: add draw code for native data here mysvd(pDC); } //////////////////////////////////////////////////////////////////////// // CMfcprjView printing BOOL CMfcprjView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMfcprjView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMfcprjView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } int CMfcprjView::mysvd(CDC *pDC) { /* Initialize pointers to array arguments */ mxArray *X = NULL; mxArray *U = NULL, *S = NULL, *V = NULL; char str[20*sizeof(double)]; double *ptr; int nHeight=20; pDC->TextOut(0,0,"Hello Everyone!"); pDC->TextOut(0,nHeight,"This is a demo of calling SVD function directly"); pDC->TextOut(0,2*nHeight,"from Win32 Console Application,which has the"); pDC->TextOut(0,3*nHeight,"siminar functionality as the MATLAB function"); pDC->TextOut(0,4*nHeight,"SVD - Singular value decomposition."); mlfEnterNewContext(0, 0); mlfAssign(&X, mlfDoubleMatrix(4, 2, data, NULL)); /* Compute the singular value decomposition and print it */ mlfAssign(&S, mlfSvd(NULL, NULL, X, NULL)); //mlfPrintf("One input, one output:\n"); pDC->TextOut(0,7*nHeight,"One input, one output:");

删除的内容: pDC->TextOut(0,nHeight,"This is a demo of calling SVD function directly");

Page 148: Matlab Simulink

第 3章 将 m程序转换成独立的应用 135

//mlfPrintf("S = \n"); mlfPrintMatrix(S); pDC->TextOut(0,8*nHeight,"S = "); ptr=mxGetPr(S); sprintf(str,"%12.4f",ptr[0]); pDC->TextOut(0,9*nHeight,str); sprintf(str,"%12.4f",ptr[1]); pDC->TextOut(0,10*nHeight,str); /* Multiple output arguments */ mlfAssign(&U, mlfSvd(&S, &V, X, NULL)); // mlfPrintf("One input, three outputs:\n"); pDC->TextOut(0,12*nHeight,"One input, three outputs:"); //mlfPrintf("U = \n"); mlfPrintMatrix(U); pDC->TextOut(0,13*nHeight,"U = "); ptr=mxGetPr(U); sprintf(str,"%12.4f\t%12.4f\t%12.4f\t%12.4f",ptr[0],ptr[4],ptr[8],ptr[12]); pDC->TextOut(0,14*nHeight,str); sprintf(str,"%12.4f\t%12.4f\t%12.4f\t%12.4f",ptr[1],ptr[5],ptr[9],ptr[13]); pDC->TextOut(0,15*nHeight,str); sprintf(str,"%12.4f\t%12.4f\t%12.4f\t%12.4f",ptr[2],ptr[6],ptr[10],ptr[14]); pDC->TextOut(0,16*nHeight,str); sprintf(str,"%12.4f\t%12.4f\t%12.4f\t%12.4f",ptr[3],ptr[7],ptr[11],ptr[15]); pDC->TextOut(0,17*nHeight,str); //mlfPrintf("S = \n"); mlfPrintMatrix(S); pDC->TextOut(0,19*nHeight,"S = "); ptr=mxGetPr(S); sprintf(str,"%12.4f\t%12.4f",ptr[0],ptr[4]); pDC->TextOut(0,20*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[1],ptr[5]); pDC->TextOut(0,21*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[2],ptr[6]); pDC->TextOut(0,22*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[3],ptr[7]); pDC->TextOut(0,23*nHeight,str); //mlfPrintf("V = \n"); mlfPrintMatrix(V); pDC->TextOut(0,25*nHeight,"V = "); ptr=mxGetPr(V); sprintf(str,"%12.4f\t%12.4f",ptr[0],ptr[2]); pDC->TextOut(0,26*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[1],ptr[3]); pDC->TextOut(0,27*nHeight,str); /* Multiple input and output arguments */ mlfAssign(&U, mlfSvd(&S, &V, X, mlfScalar(0.0)));

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 149: Matlab Simulink

从Matlab/Simulink模型到代码实现 136

//mlfPrintf("Two inputs, three outputs:\n"); pDC->TextOut(0,29*nHeight,"Two input, three outputs:"); //mlfPrintf("U = \n"); mlfPrintMatrix(U); pDC->TextOut(0,30*nHeight,"U = "); ptr=mxGetPr(U); sprintf(str,"%12.4f\t%12.4f",ptr[0],ptr[4]); pDC->TextOut(0,31*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[1],ptr[5]); pDC->TextOut(0,32*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[2],ptr[6]); pDC->TextOut(0,33*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[3],ptr[7]); pDC->TextOut(0,34*nHeight,str); //mlfPrintf("S = \n"); mlfPrintMatrix(S); pDC->TextOut(0,36*nHeight,"S = "); ptr=mxGetPr(S); sprintf(str,"%12.4f\t%12.4f",ptr[0],ptr[2]); pDC->TextOut(0,37*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[1],ptr[3]); pDC->TextOut(0,38*nHeight,str); //mlfPrintf("V = \n"); mlfPrintMatrix(V); pDC->TextOut(0,40*nHeight,"V = "); ptr=mxGetPr(V); sprintf(str,"%12.4f\t%12.4f",ptr[0],ptr[2]); pDC->TextOut(0,41*nHeight,str); sprintf(str,"%12.4f\t%12.4f",ptr[1],ptr[3]); pDC->TextOut(0,42*nHeight,str); mxDestroyArray(X); mxDestroyArray(U); mxDestroyArray(S); mxDestroyArray(V); mlfRestorePreviousContext(0, 0); return(EXIT_SUCCESS); } /////////////////////////////////////////////////////////////////////// // CMfcprjView diagnostics #ifdef_DEBUG void CMfcprjView::AssertValid() const { CView::AssertValid(); }

Page 150: Matlab Simulink

第 3章 将 m程序转换成独立的应用 137

void CMfcprjView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMfcprjDoc* CMfcprjView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMfcprjDoc))); return (CMfcprjDoc*)m_pDocument; } #endif //_DEBUG //////////////////////////////////////////////////////////////////////// // CMfcprjView message handlers

步骤 5. 按“从 Win32控制台程序调用 MATLAB C Math Library”中的步骤 7、8、9作相关设置。

步骤 6. 现在可以编译连接运行工程文件 mfcprj,结果如图 3.32所示。

图 3.32 mfcprj.exe 运行结果

带格式的

删除的内容: (上述程序代码必须与我给你的原文一致,

否则出现语法错误!!!)

删除的内容: 《

删除的内容: 》

Page 151: Matlab Simulink

从Matlab/Simulink模型到代码实现 138

3.6 从 VB中调用MATLAB功能

要想从 VB 中调用类似于 MATLAB 的科学计算、数据分析和可视化功能,需要安装MATLAB 产品中的 MatrixVB 模块。MatrixVB 不在 MATLAB 的安装盘中,需要从MathWorks公司的网站 http://www.mathworks.com上下载。以 MatrixVB4.51为例,它的安装过程如下:

步骤 1. 在 Windows 的资源浏览器中,运行 MatrixVB4.51 安装文件 matrix VB4510.exe,弹出如图 3.33所示的界面。

图 3.33 Welcome to MatrixVB Setup

步骤 2. 在图 3.33 中,单击 Next按钮,进入图 3.34所示界面。

图 3.34 Read Me File

带格式的

带格式的

Page 152: Matlab Simulink

第 3章 将 m程序转换成独立的应用 139

步骤 3. 在图 3.34所示界面中单击 Next按钮,弹出MathWorks公司软件协议窗口,如图 3.35所示。

图 3.35 MathWorks Inc. Software License Agreement

步骤 4. 要继续安装,在图 3.35所示界面中必须接受协议条款,然后进入图 3.36所示的安装目录选择对话框。注意目录名中不能包含空格,一般用默认目录即可。然后,单击

Next按钮,开始安装,如图 3.37所示。

图 3.36 选择安装目录

步骤 5. 安装快要结束时,会提示用户输入表示有权使用 MatrixVB 的 license,如图3.38所示。请输入 license(如果没有 license,用户需要与代理商联系),然后单击 OK按钮,安装过程结束。

带格式的

带格式的

带格式的

删除的内容: 你的

删除的内容: (

删除的内容: 请与你的

删除的内容: )

Page 153: Matlab Simulink

从Matlab/Simulink模型到代码实现 140

图 3.37 Installing

图 3.38 MatrixVB License

安装完 MatrixVB后,在 MatrixVB程序组中会有如图 3.39所示的一些项目。图 3.40所示是从 VB中调用 MATLAB invhilb和 plot函数功能的一个 Microsoft Visual Basic工程文件的例子,图 3.41 是该工程文件的运行结果。关于如何在 VB 中调用类似于 MATLAB的科学计算、数据分析和可视化功能,请参考相关的文档,例如,如图 3.39 所示的MatrixVB Guide和 Reference Guide等,由于篇幅所限,本书不再予以论述。

图 3.39 MatrixVB程序项

删除的内容: L

删除的内容: r

Page 154: Matlab Simulink

第 3章 将 m程序转换成独立的应用 141

图 3.40 VB中调用MATLAB的 invhilb和 plot函数功能

图 3.41 VB中调用MATLAB的 invhilb和 plot函数功能的运行结果

>> plot(invhilb(5))

运行结果如图 3.42所示。

删除的内容: L

Page 155: Matlab Simulink

从Matlab/Simulink模型到代码实现 142

图 3.42 输入 plot(invhilb(5))的运行结果

>> which invhilb D:\MATLAB6p1\toolbox\matlab\elmat\invhilb.m >> help invhilb INVHILB Inverse Hilbert matrix. INVHILB(N) is the inverse of the N by N matrix with elements 1/(i+j-1), which is a famous example of a badly conditioned matrix. The result is exact for N less than about 15. See also HILB.

Page 156: Matlab Simulink

页 131: [1] 删除的内容 fcr 2002-9-17 9:16:00

#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMfcprjView : public CView { protected: // create from serialization only CMfcprjView(); DECLARE_DYNCREATE(CMfcprjView) // Attributes public: CMfcprjDoc* GetDocument(); // Operations public: int mysvd(CDC *pDC); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMfcprjView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CMfcprjView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMfcprjView) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP()

Page 157: Matlab Simulink

}; #ifndef _DEBUG // debug version in mfcprjView.cpp inline CMfcprjDoc* CMfcprjView::GetDocument() { return (CMfcprjDoc*)m_pDocument; } #endif //////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous //line. #endif // !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_ 06D3FB7B69CC__ INCLUDED_) (上述程序代码务必与我给你的原文一致!!)

Page 158: Matlab Simulink

第 4章 系统级设计工具 Simulink

Simulink 是 MATLAB 产品中的图形化建模工具,它主要用于系统级的设计和仿真,同时也可用于算法开发。用 Simulink 搭建的模型,通过 Real-Time Workshop 可以自动生成面向不同目标的 C代码。

4.1 图形化建模

Simulink 是一个图形化的建模工具。从某种意义上讲,凡是能够用数学方式描述的系统,都可用 Simulink 建模。当然,针对自己特定的系统,用户应该权衡 Simulink 的易用性和方便性,以选择是否用 Simulink 建模。例如通信系统网络层的仿真,用 Simulink 加上 Stateflow 是可以实现的,但不会太方便,所以笔者主张类似的仿真现在还不宜用Simulink。用 Simulink可以很容易就搭建的系统主要包括:

通信系统物理层和数据链路层 动力学系统 控制系统 数字信号处理系统 电力系统 生物系统 金融系统 为了建立各种各样的系统的模型,Simulink提供了一些基本库(由 Simulink基本模块

提供)和针对特定领域的扩展库。用户可以使用这些库中的模块搭建自己的模型。用户为

了实现特定领域的系统建模,购买 MATLAB产品时通常需要选择 Simulink基本模块和自己所属领域的扩展模块。例如要做通信系统的建模和仿真,就需要如下几个模块:

Simulink DSP Blockset Communications Blockset 当然,还需要MATLAB基本模块和一些工具箱。

删除的内容: (

删除的内容: )

删除的内容: 比

Page 159: Matlab Simulink

从Matlab/Simulink模型到代码实现 144

4.2 基本模块库

Simulink提供的基本模块库如图 4.1所示。

图 4.1 Simulink基本模块库

包括: 用于连续系统的基本模块(Simulink/Continuous),如图 4.2所示。

图 4.2 用于连续系统的基本模块

用于离散系统的基本模块(Simulink/Discrete),如图 4.3所示。

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 160: Matlab Simulink

第 4章 系统级设计工具 Simulink 145

图 4.3 用于离散系统的基本模块

函数调用、S-函数和查表运算模块(Simulink/Functions & Tables),如图 4.4 所示。

图 4.4 函数调用 S-函数和查表运算模块

数学运算基本模块(Simulink/Math),如图 4.5所示。 非线性模块(Simulink/Nonlinear),如图 4.6所示。 信号与系统基本模块(Simulink/Signals & Systems),如图 4.7所示。

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 161: Matlab Simulink

从Matlab/Simulink模型到代码实现 146

图 4.5 数学运算基本模块

图 4.6 非线性模块

Page 162: Matlab Simulink

第 4章 系统级设计工具 Simulink 147

图 4.7 信号与系统基本模块

信宿模块(Simulink/Sinks),如图 4.8所示。

图 4.8 信宿模块

删除的内容: (

删除的内容: )

删除的内容: ,

Page 163: Matlab Simulink

从Matlab/Simulink模型到代码实现 148

信源模块(Simulink/Sources),如图 4.9所示。

图 4.9 信源模块

子系统基本模块(Simulink/Subsystems),如图 4.10所示。

图 4.10 子系统基本模块

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 164: Matlab Simulink

第 4章 系统级设计工具 Simulink 149

4.3 Blocksets

Blocksets,即模块库,是 MathWorks 公司提供的面向特定领域的专业模块库,它是Simulink 基本功能的扩展,极大地方便了用户搭建特定应用领域的模型。例如,如果用户要搭建数字信号处理方面的系统模型,则 DSP Blockset 向用户提供了一些极有价值的模块,涵盖了滤波、变换、功率谱估计、统计等数字信号处理的各个方面,如图 4.11 所示。

图 4.11 DSP Blockset

MATLAB R12.1产品提供的所有 Simulink的扩展模块库,如图 4.12所示。MATLAB的第三方开发厂商也可能提供一些很好的专业模块库,例如 RadioScape 公司的 RadioLab 3G产品就提供了用于 3GPP UMTS Layer 1 FDD Mode仿真的模块库。

Page 165: Matlab Simulink

从Matlab/Simulink模型到代码实现 150

图 4.12 扩展模块库

4.4 Simulink仿真机理

对 Simulink系统模型的仿真主要包含两个阶段: 初始化阶段 初始化阶段主要完成以下工作:

每个模块的所有参数都传递给 MATLAB 进行求值,得到的数值作为实际的参数使用。

展开模型的层次结构,每个子系统被它们所包含的模块替代,带有触发和使能模块的子系统被视为原子单元进行处理。

检查信号的宽度和模块的连接情况,提取状态和输入/输出依赖关系方面的信息,确定模块的更新顺序。

带格式的: 项目符号和编号

删除的内容:

删除的内容:

Page 166: Matlab Simulink

第 4章 系统级设计工具 Simulink 151

确定状态的初值和采样时间。 运行阶段 初始化之后,仿真进入运行阶段。仿真是由求解器控制的,它计算模块的输出,更新

离散状态,计算连续状态。在采用变步长求解器时,求解器还会确定时间步长。计算连续

状态包含下面两个步骤: 首先,求解器为待更新的系统提供当前状态、时间和输入值,反过来,求解器需要状态导数的值;

然后,求解器对状态的导数进行积分,计算新的状态的值。 状态计算完成后,再进行一次模块的输出更新。这时,一些模块可能会发出过零的警

告,促使求解器探测出发生过零的准确时间。 Simulink的仿真过程是在 Simulink求解器和系统相互作用之下完成的,系统和求解器

在仿真过程中的对话作用如图 4.13所示。

求解器传递模块输出对状态导数积分确定采样时间

系统计算模块输出状态的导数状态的更新生成过零事件

输出、导数、事件通知

SIMULINK

时间、输入、状态

图 4.13 系统和求解器之间的对话

在图 4.13 中,求解器的作用是传递模块的输出,对状态导数进行积分,并确定采样时间。系统的作用是计算模块的输出,对状态进行更新,计算状态的导数,生成过零 事件。从求解器传递给系统的信息包括时间、输入和当前状态;反过来,系统为求解器提

供模块的输出、状态的更新和状态的导数。整个仿真过程如图 4.14所示。

带格式的

带格式的

带格式的: 项目符号和编号

带格式的

删除的内容: 展开模型的层次结构,每个子系统被它们所

包含的模块替代,带有触发

和使能模块的子系统被视为

原子单元进行处理。

<#>检查信号的宽度和模块的连接情况,提取状态和输

入/输出依赖关系方面的信息,确定模块的更新顺序。

<#>确定状态的初值和采样时间。 运行阶段初始化之后,仿真

进入运行阶段。仿真是由求

解器控制的,它计算模块的

输出,更新离散状态,计算

连续状态。在采用变步长求

解器时,求解器还会确定时

间步长。计算连续状态包含

下面两个步骤:

删除的内容: 然后,求解器对状态的导数进行积分,计算

新的状态的值。

状态计算完成后,再进行一

次模块的输出更新。这时,

一些模块可能会发出过零的

警告,促使求解器探测出发

生过零的准确时间。

Page 167: Matlab Simulink

从Matlab/Simulink模型到代码实现 152

设置初始条件

计算下一个采样所在时刻(仅对变步长仿真)

计算输出

更新离散状态(如果系统存在离散状态)

计算输出

计算导数

结束

图 4.14 Simulink仿真过程

4.5 重 要 概 念

系统模型搭建完成之后,可以对其进行各种各样的仿真,以测试系统的性能。仿真过

程涉及到一些重要的概念。

过零检测

过零检测通过在系统和求解器之间建立对话的方式工作(如图 4.13 所示)。对话包含的一个内容是事件通知,即系统告知求解器在前一时间步发生了一个事件。事件由过零

表示,过零在下列两个条件下产生: 信号在上一个时间步改变了符号(含变为 0 和离开 0)。 模块在上一个时间步改变了模式(例如积分器进入了饱和区段) 。 过零是一个重要的事件,表征系统中的不连续性,例如响应中的跳变。如果仿真中不

对过零进行检测,可能会导致不准确的仿真结果。 当采用变步长求解器时,Simulink 能够检测到过零(使用固定步长的求解器,Simulink 不检测过零)。当一个模块通知系统前一时间步发生了过零,变步长求解器就会缩小步长,即便绝对误差和相对误差是可接受

带格式的: 项目符号和编号

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 168: Matlab Simulink

第 4章 系统级设计工具 Simulink 153

的。缩小步长的目的是判定事件发生的准确时间。当然,这样会降低仿真的速度,但这样

做对有些模块来讲是至关重要和必要的,因为这些模块的输出可能表示了一个物理值,它

的零值有着重要的意义。事实上,只有少量的模块能够发出过零事件通知。每个模块发出

专属于自己的事件通知,而且可能与不止一个类型的事件发生关联。 能够产生过零通知的 Simulink模块如图 4.15所示。

图 4.15 能够产生过零通知的 Simulink模块

各个模块的过零的类型是有差异的。例如,Abs 模块在输入改变符号时产生一个事件,而 Saturation模块能够生成两个不同的过零,一个用于下饱和,一个用于上饱和。

Signals&Systems 库中的 HitCrossing 模块输入穿过零点时产生一个过零,可以用来为不带过零能力的模块提供过零检测的能力。一些过零只是用来通知求解器模式已经发生了

改变,另外一些则与信号相关,用于触发其他模块。触发包含三种类型: 上升沿 – 信号上升到或穿过零或者信号离开零变正; 下降沿 – 信号下降到或穿过零或者信号离开零变负; 双边沿 –上升或下降两者之一发生。 【例 9】模型如图 4.16 所示,采用 Fcn 模块和 Abs 模块计算输入的绝对值。注意,

Fcn 块不支持过零,结果一些拐角点被漏掉了;而由于 Abs块能够产生过零,每当它的输入改变符号时,都能够精确地得到零点结果,如图 4.17所示。

如果想关闭对系统模型中能够产生过零事件的模块的过零检测功能,例如为了加快仿

真速度,那么可以如图 4.18 所示设置仿真参数对话框 Advanced 选项卡中的选项Opimimations/Zero crossing detection 为 Off,但这样可能会导致不正确的仿真结果。对图4.16所示界面中的模型作上述设定后,仿真结果如图 4.19所示。

带格式的: 项目符号和编号

删除的内容: ,当它的

删除的内容: 上升沿 – 信号上升到或穿过零或者信号离开

零变正;

下降沿 – 信号下降到或穿过零或者信号离开零变负;

<#>双边沿 –上升或下降两者之一发生。

Page 169: Matlab Simulink

从Matlab/Simulink模型到代码实现 154

图 4.16 zerocrossing_detect.mdl

图 4.17 zerocrossing_detect.mdl 变步长仿真结果

图 4.18 关闭过零检测

Page 170: Matlab Simulink

第 4章 系统级设计工具 Simulink 155

图 4.19 关闭过零检测后 zerocrossing_detect.mdl 变步长仿真结果

代数环

直接馈通(Direct feedthrough)定义为系统的输出直接依赖于输入,换句话说,如果模块的输出方程中包含输入,则它具备直接馈通特性。Gain 模块有直接馈通特性,而 Unit Delay 模块则不具备。在 Simulink模型中,将带有直接馈通特性的各模块串成一个回路会导致一个代数环。在一个代数环中,由于模块之间是相互依赖的,所有的模块都要求

在同一个时刻计算输出,这与通常的仿真顺序概念相抵触。具有代数环的模型,仿真得到

的结果可能不正确。所以在用 Simulink搭建系统模型之前,应尽量通过手工的方法对方程求解,以去掉代数环。

如图 4.20 所示的模型是一个含有代数环的模型例子。为了计算求和模块的输出,Simulink 需要知道它的输入,但是输入恰恰是输出自己!这个代数环可以很方便地手工 解出:

1-x-x=x,x=0.3333

图 4.20 algebra_loop.mdl

Simulink自带一个内置的代数环求解器,可以解决类似于图 4.20所示界面中的代数环问题,也可以使用 Simulink/Math 库中的 Algebraic Constraint 模块对方程求解。Algebraic

带格式的

带格式的

带格式的

带格式的

删除的内容:

删除的内容:

删除的内容:

Page 171: Matlab Simulink

从Matlab/Simulink模型到代码实现 156

Constraint 模块调整它的输出,使它的输入为零。可以为这个模块指定初始的估计值。 如果想使用一个简单的方式提供初始估计值的话,也可以使用 Simulink/Signals & Systems/IC 模块。IC 模块给出了一个信号的初始值(仿真开始时刻),而在其他时刻使用当时的输入值。Simulink 使用 Newton 法求解代数环。尽管这个方法很有效,但是对有些代数环来说,这个方法可能不收敛。所以尽量不要在模型中包含代数环,以免仿真结果不正确。图

4.21和图 4.22所示是用 Simulink搭建的求解方程 022 =−− xx 的同一个模型,只是模型中

Algebraic Constraint模块的初始估计值不同。

图 4.21 求解 022 =−− xx 的模型,得到两个解

图 4.22 求解 022 =−− xx 的模型,仅得到一个解

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

删除的内容:

Page 172: Matlab Simulink

第 4章 系统级设计工具 Simulink 157

对比图 4.21 和图 4.22,可以看到,初始估计值不同,得到的结果可能不同,用户不是总能得到方程 022 =−− xx 的两个解,除非给出恰当的 Algebraic Constraint 模块的初始估计值。

如果想在仿真时查看某个模型中是否含有代数环,可按图 4.23 所示那样设置仿真参数对话框中的诊断选项,设置 Configuration options/Algebraic loop 为 Warning,这样仿真时在 MATLAB 命令窗口会出现对代数环的警告信息。例如,如果用户按图 4.23 设置图4.21 中模型 algebraic_constraint.mdl 的仿真参数对话框中的诊断选项,仿真algebraic_constraint模型时,MATLAB命令窗口出现的警告信息如下所示:

Warning: Block diagram 'algebraic_constraint' contains 2 algebraic loop(s). Found algebraic loop containing block(s): 'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Initial Guess' 'algebraic_constraint/Sum' 'algebraic_constraint/Sum1' 'algebraic_constraint/Product' 'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Sum' (algebraic variable) Found algebraic loop containing block(s):

'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Initial ]Guess' 'algebraic_constraint/Sum2' 'algebraic_constraint/Sum3' 'algebraic_constraint/Product1' 'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Sum' (algebraic variable)

图 4.23 代数环检查

删除的内容: 如

删除的内容: ,

删除的内容: 我们

删除的内容: 警告信息是否也要按格式走?

删除的内容: Warning: Block diagram 'algebraic_constraint' contains 2 algebraic

删除的内容:

删除的内容: loop(s).Found algebraic loop containing block(s): 'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Initial

删除的内容:

删除的内容: Guess' 'algebraic_constraint/Sum' 'algebraic_constraint/Sum1' 'algebraic_constraint/Product' 'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Sum'

删除的内容:

删除的内容: (algebraic variable)Found algebraic loop containing block(s): 'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Initial ]

删除的内容:

删除的内容: Guess' 'algebraic_constraint/Sum2' 'algebraic_constraint/Sum3' 'algebraic_constraint/Product1' 'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Sum'

删除的内容:

删除的内容: (algebraic variable)

Page 173: Matlab Simulink

从Matlab/Simulink模型到代码实现 158

4.6 封装自己的 C算法和 m语言算法

在 Simulink模型中可以集成自己的 C算法和 m语言算法。要让 Simulink模型能够使用自己的 C算法或者 m语言算法,先要对其进行封装。这要求用户必须用 C语言或者 m语言编写 S-函数。编写 S-函数有一套固定的规则,这是由 Simulink 的仿真机制决定的。是用 m语言还是 C语言编写,取决于用户的需要。

C 语言编写的 S-函数不仅能够用于 Simulink 仿真,也可用于通过 Real-Time Workshop 转成面向不同目标的代码,而 m 语言编写的 S-函数只能用于 Simulink仿真。

用 C语言编写 S-函数比用 m语言复杂,但一般来讲运行速度要快一些,如果速度是用户关注的焦点,则宜用 C语言编写 S-函数。

用户应尽量采用 Simulink 和各种模块库中的模块来搭建系统模型,除非上述模块不能满足要求,或者用户确实关注仿真速度,才宜编写 S-函数,以免带来不必要的错误。

本书我们不讲解怎样编写 S-函数(关于如何编写 S-函数,用户可参考 MATLAB Document安装盘上的 PDF文档 sfunctions.pdf),而是重点介绍封装自己的 C算法和 m语言算法的整个过程。

【例 10】在 Simulink模型中使用自己的 xy *10= C算法。

步骤 1. 编写 S-函数,程序代码如下: /* * File : times10_c.c * An example C-file S-function for multiplying an input by 10, * y = 10*u */ #define S_FUNCTION_NAME times10_c #define S_FUNCTION_LEVEL 2 #include "simstruc.h" /*================* * Build checking * *================*/

删除的内容: 则

删除的内容: (

删除的内容: )

Page 174: Matlab Simulink

第 4章 系统级设计工具 Simulink 159

/* Function: mdlInitializeSizes ======================================= * Setup sizes of the various vectors. */ static void mdlInitializeSizes(SimStruct *S) { ssSetNumSFcnParams(S, 0); if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) { return; /* Parameter mismatch will be reported by Simulink */ } if (!ssSetNumInputPorts(S, 1)) return; ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED); ssSetInputPortDirectFeedThrough(S, 0, 1); if (!ssSetNumOutputPorts(S,1)) return; ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED); ssSetNumSampleTimes(S, 1); /* Take care when specifying exception free code */ ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE | SS_OPTION_USE_TLC_WITH_ACCELERATOR); } /* Function: mdlInitializeSampleTimes ================================== * Specifiy that we inherit our sample time from the driving block. */ static void mdlInitializeSampleTimes(SimStruct *S) { ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); } /* Function: mdlOutputs ================================================ * y = 10*u */ static void mdlOutputs(SimStruct *S, int_T tid) { int_T i;

Page 175: Matlab Simulink

从Matlab/Simulink模型到代码实现 160

InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0); real_T *y = ssGetOutputPortRealSignal(S,0); int_T width = ssGetOutputPortWidth(S,0); for (i=0; i<width; i++) { /* * This example does not implement complex signal handling. */ *y++ = 10.0 *(*uPtrs[i]); } } /* Function: mdlTerminate ============================================== * Abstract: * No termination needed, but we are required to have this routine. */ static void mdlTerminate(SimStruct *S) { } #ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */ #include "simulink.c" /* MEX-file interface mechanism */ #else #include "cg_sfun.h" /* Code generation registration function */ #endif

步骤 2. 在 MATLAB命令窗口,用 mex命令编译 times10_c.c,生成一个动态链接库(在 Windows平台上为 times10_c.dll);在 UNIX平台上动态库的扩展名与平台有关。如果还没有选择适当的 C编译器,先用 mex –setup命令选择。

>> mex times10_c.c >> dir times10_c.dll TIMES10_C.DLL

带格式的

删除的内容: (

删除的内容: )

删除的内容: 请

Page 176: Matlab Simulink

第 4章 系统级设计工具 Simulink 161

步骤 3. 拖放如图 4.24所示的 Simulink/Functions & Tables中的 S-Function模块,创建需要使用 xy *10= 算法的系统模型,例如想将 )sin(tx = 放大 10 倍,创建的模型如图 4.25

所示。

图 4.24 S-Function模块

图 4.25 sintx10.mdl

步骤 4. 将图 4.25 所示模型中的 Sine Wave 模块的参数设置为如图 4.26 所示,S-Function 模块的参数设置为如图 4.27 所示(必须保证 times10_c 动态库在 MATLAB 的搜索路径或者当前目录中)。

步骤 5. 保存之后,系统模型如图 4.28 所示,使用默认仿真参数得到的仿真结果如图4.29所示,这样就用自己的 C算法把波形放大了 10倍。

带格式的

带格式的

带格式的

删除的内容:

删除的内容: (

删除的内容: )

Page 177: Matlab Simulink

从Matlab/Simulink模型到代码实现 162

图 4.26 Sine Wave模块参数设置

图 4.27 S-Function模块参数设置

图 4.28 修改完成后的 sintx10.mdl

Page 178: Matlab Simulink

第 4章 系统级设计工具 Simulink 163

图 4.29 sintx10.mdl仿真结果

【例 11】在 Simulink模型中使用自己的 xy *10= m语言算法。

步骤 1. 编写 m S-函数,程序代码如下: function [sys,x0,str,ts] = times10_m(t,x,u,flag) %TIMES10_m S-function whose output is ten times its input. % This M-file illustrates how to construct an M-file S-function that % computes an output value based upon its input. The output of this % S-function is ten times the input value: % % y = 10 * u; % % Dispatch the flag. The switch function controls the calls to % S-function routines at each simulation stage of the S-function. % switch flag, %%%%%%%%%%%%%%%%%% % Initialization % %%%%%%%%%%%%%%%%%% % Initialize the states, sample times, and state ordering strings. case 0 [sys,x0,str,ts]=mdlInitializeSizes; %%%%%%%%%%% % Outputs % %%%%%%%%%%% % Return the outputs of the S-function block. case 3 sys=mdlOutputs(t,x,u);

带格式的

Page 179: Matlab Simulink

从Matlab/Simulink模型到代码实现 164

%%%%%%%%%%%%%%%%%%% % Unhandled flags % %%%%%%%%%%%%%%%%%%% % There are no termination tasks (flag=9) to be handled. % Also, there are no continuous or discrete states, % so flags 1,2, and 4 are not used, so return an emptyu % matrix case { 1, 2, 4, 9 } sys=[]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Unexpected flags (error handling)% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Return an error message for unhandled flag values. otherwise error(['Unhandled flag = ',num2str(flag)]); end % end timestwo % %======================================================================= % mdlInitializeSizes % Return the sizes, initial conditions, and sample times for the S-function. %======================================================================= % function [sys,x0,str,ts] = mdlInitializeSizes() sizes = simsizes; sizes.NumContStates = 0; sizes.NumDiscStates = 0; sizes.NumOutputs = -1; % dynamically sized sizes.NumInputs = -1; % dynamically sized sizes.DirFeedthrough = 1; % has direct feedthrough sizes.NumSampleTimes = 1; sys = simsizes(sizes); str = []; x0 = []; ts = [-1 0]; % inherited sample time

删除的内容:

删除的内容: (必须和上一行在同一行,请和原文一

致!!)

Page 180: Matlab Simulink

第 4章 系统级设计工具 Simulink 165

% end mdlInitializeSizes % %======================================================================= % mdlOutputs % Return the output vector for the S-function %======================================================================= % function sys = mdlOutputs(t,x,u) sys = u * 10; % end mdlOutputs

步骤 2. m语言编写的 S-函数使用时不需要编译。剩下的步骤和【例 10】相同,只是要把模型 sintx10.mdl中的 S-Function模块的参数设置为如图 4.30所示(times10_m.m需在MATLAB的搜索路径或者当前目录中)。最后的仿真结果和【例 10】是一样的。

图 4.30 S-Function模块参数设置

4.7 定制自己的 Blockset

如果用户自己开发了一些模块,在建模时需要经常使用,这时,可以选择将这些模块

封装在自己的 Blockset中,再将其加在 Simulink Library Browser里面,就可以像使用标准模块库那样使用定制模块库中的模块了。

【例 12】将【例 10】和【例 11】中的模块封装成 Blockset。步骤如下: 步骤 1. 将文件 times10_c动态库文件(Windows 平台上为 times10_c.dll)、times10_c.c

带格式的

带格式的

删除的内容: (再重复一遍,所有的程序文本必须和我给

你的原文一致,否则将会出

现语法错误!!!这是你做

修改时首先应该遵守的原

则,因为如果程序有语法错

误,别人会认为我MATLAB没有学好;而如果某些文字

表达不好,他们最多说我语

文不过关。。。。。。事实

上如果你做格式修改时,忠

实于原稿,可能不会有什么

逻辑错误(当然会有一些我

未发现的错误),我也不需

要把你改错的东西,再改正

过来。)

删除的内容: 22

删除的内容: (

删除的内容: )

删除的内容: 22

删除的内容:

删除的内容: [例 10]

删除的内容: [例 11]

删除的内容: (

删除的内容: )

Page 181: Matlab Simulink

从Matlab/Simulink模型到代码实现 166

(这个文件不是必要的,但如不涉及知识产权保护,一般还是将它包括在内,以供用户参

考)和 times10_m.m复制到某个目录(例如 e:/material/book/myblksetdemo)中。 步骤 2. 将当前目录设置为 e:\material\book\myblksetdemo,使用菜单命令 Simulink

Library Browser|File|New|Library创建新模型。 步骤 3. 拖放两个 Simulink\Functions & Tables\S-Function模块,创建如图 4.31所示的

两个模块,其参数设置分别如图 4.32和 4.33所示。

图 4.31 m S-Function模块和 C S-Function模块

图 4.32 m S-函数

图 4.33 C S-函数

步骤 4. 如图 4.34所示,使用快捷菜单中的 Create subsystem命令将图 4.31中的两个

带格式的

带格式的

带格式的

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 182: Matlab Simulink

第 4章 系统级设计工具 Simulink 167

模块合成一个子系统,结果如图 4.35所示。

图 4.34 创建子系统

图 4.35 创建的子系统

步骤 5. 如图 4.36 所示,删除图 4.35 所示子系统中的输入输出端口,结果如图 4.37 所示。

图 4.36 删除子系统输入输出端口

步骤 6. 在图 4.37 中使用快捷菜单中的 Mask subsystem 命令封装子系统,如图 4.38 所示。

步骤 7. 如图 4.39 所示设置 Mask Editor 对话框,其他参数为默认值,结果如图 4.40 所示。

带格式的

带格式的

带格式的

Page 183: Matlab Simulink

从Matlab/Simulink模型到代码实现 168

图 4.37 删除输入输出端口后的子系统

图 4.38 封装子系统

图 4.39 Mask Editor对话框参数设置

删除的内容: 分页符

Page 184: Matlab Simulink

第 4章 系统级设计工具 Simulink 169

图 4.40 封装之后的子系统

步骤 8. 将图 4.40所示界面中的子系统名 Subsystem修改为 my own X 10 blocks,然后将模型保存为 times10.mdl,如图 4.41所示。

图 4.41 times10.mdl

步骤 9. 在图 4.40所示界面中添加 Simulink\Math\Gain模块,增益参数修改为 10,然后保存,如图 4.42所示。

图 4.42 添加 Gain模块之后的 times10.mdl

步骤 10. 关闭模型 times10.mdl,在目录 e:\material\book\myblksetdemo 中编写一个 m文件 slblocks.m。其内容如下:

1. function blkStruct = slblocks 2. %SLBLOCKS Defines the Simulink library block representation 3. %for My Simulink Blockset demo. 4.

带格式的

带格式的

带格式的

Page 185: Matlab Simulink

从Matlab/Simulink模型到代码实现 170

5. 6. blkStruct.Name = ['times10' sprintf('\n') 'Blockset']; 7. blkStruct.OpenFcn = 'times10'; 8. blkStruct.MaskInitialization = ''; 9. blkStruct.MaskDisplay = ['disp(''times10 Blockset'')'];

10. 11. % Define the library list for the Simulink Library browser. 12. % Return the name of the library model and the name for it 13. % 14. Browser(1).Library = 'times10'; 15. Browser(1).Name = 'Times10 Blockset'; 16. 17. blkStruct.Browser = Browser; 18. 19. % End of slblocks.m

程序说明如下:

第 7行,定义打开模块库的命令,一般为模块库文件名(不带 mdl扩展名)。 第 14行,定义模块库文件名(不带 mdl扩展名)。 第 15行,定义显示在 Simulink Library Browser中的模块库名称。

Simulink Library Browser 在启动的过程中会搜索 MATLAB 的搜索路径下的各个slblocks.m文件,将其中定义的模块库调入 Simulink Library Browser中。

步骤 11. 将 e:\material\book\myblksetdemo 添加至 MATLAB 搜索路径,如图 4.43 所示。

图 4.43 设置MATLAB搜索路径

带格式的

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 186: Matlab Simulink

第 4章 系统级设计工具 Simulink 171

步骤 12. 关闭 Simulink Library Browser,再重新打开,应该可以看到定制的模块库Times10 Blockset已经加在 Simulink Library Browser中了,如图 4.44和图 4.45所示。现在就可以像使用标准模块库中的模块一样使用 Times10 Blockset中的模块了。

图 4.44 定制的 Times10 Blockset

图 4.45 定制的 Times10 Blockset\my own X 10 blocks

带格式的

Page 187: Matlab Simulink

从Matlab/Simulink模型到代码实现 172

4.8 系统级设计和仿真

整体上而言,Simulink 是一个系统级的设计和仿真工具,它可以为各种各样的系统建立模型。使用 Simulink 很容易创建系统的模型,设置仿真参数,然后对模型进行仿真。Simulink 和 Matlab 是高度集成的,用户可以借助 Matlab 强大的数据分析和可视化功能来分析系统仿真结果。下面略举几例,目的是让大家对 Simulink的系统建模和仿真能力有一个感性认识。关于如何使用 Simulink 进行系统建模的详细内容,请参考 MATLAB Document 安 装 盘 上 的 PDF 文 档 sl_using.pdf 。 从 MathWorks 公 司 的 网 址http://www.mathworks.com 上可以下载到各种系统的典型 Simulink 模型,供用户设计系统时作参考。

【例 13】图 4.46所示是 F-14战机飞控系统模型,它的仿真结果如图 4.47所示。

图 4.46 %MATLABROOT%\toolbox\simulink\simdemos\aerospace\f14.mdl

【例 14】图 4.48所示是使用蓝牙技术的语音传输模型。 【例 15】图 4.49所示是 IS-95A的反向业务信道开环和闭环功率控制模型,它的仿真

结果如图 4.50所示。

带格式的

删除的内容: 是否也有侵权问题?

Page 188: Matlab Simulink

第 4章 系统级设计工具 Simulink 173

图 4.47 f14.mdl仿真结果

图 4.48 bluetooth_voice.mdl

Page 189: Matlab Simulink

从Matlab/Simulink模型到代码实现 174

图 4.49 tpc95.mdl

图 4.50 tpc95.mdl仿真结果

Page 190: Matlab Simulink

第 4章 系统级设计工具 Simulink 175

【例 16】图 4.51 所示模型是 GSM 和 EDGE调制方式的一个比较,它的仿真结果如图 4.52、图 4.53、图 4.54和图 4.55所示。

图 4.51 gsm_edge.mdl

图 4.52 GSM调制星座图

删除的内容: 分页符

Page 191: Matlab Simulink

从Matlab/Simulink模型到代码实现 176

图 4.53 GSM/EDGE调制的频谱

图 4.54 滤波后的 EDGE调制星座图

删除的内容: 分页符

Page 192: Matlab Simulink

第 4章 系统级设计工具 Simulink 177

图 4.55 未滤波的 EDGE调制星座图

【例 17】图 4.56所示是 IS-95A移动台呼叫处理模型,其中用到了用来描述有限状态机的 Stateflow模型。

Page 193: Matlab Simulink

从Matlab/Simulink模型到代码实现 178

图 4.56 IS-95A移动台呼叫处理模型

Page 194: Matlab Simulink

第 4章 系统级设计工具 Simulink 179

【例 18】图 4.57所示是软件无线电的一个欠采样处理模型。

图 4.57 softdec.mdl

删除的内容:

Page 195: Matlab Simulink

第 5章 Real-Time Workshop

算法的开发、系统级设计和仿真只是产品开发的两个环节,产品开发还有最为关键的

一环,那就是实现。前面已经介绍过,m语言开发的算法通过 MATLAB Compiler可以转成独立的应用和 C/C++源代码。有必要强调一下,MATLAB Compiler 生成的 C/C++源代码不是面向目标的,而是针对 PC和 UNIX 平台的,它连接了很多动态链接库,无法应用到诸如 DSP、FPGA 和支持 VxWorks 的处理器等产品实现中经常使用的目标。在MATLAB开发环境中,如果想自动生成面向诸如 DSP、FPGA和支持 VxWorks的处理器等目标的代码,只能是先使用 Simulink 搭建算法或者系统的模型,然后通过 Real-Time Workshop(RTW)或者第三方工具(例如 Xilinx System Generator、Altera DSP Builder等)自动生成面向目标的代码。本书的这一章及后续第 6、7、8章主要讲这方面的内容。

5.1 减轻程序员负担

Real-Time Workshop是MathWorks公司提供的代码自动生成工具,它可以使 Simulink模型自动生成面向不同目标的代码。目前它主要能生成 ANSI C 和 Ada 语言源代码,但它也提供了一个开放的接口,供第三方或者用户自己定制其他语言代码的自动生成。

图 5.1 传统的产品开发流程

传统的产品开发流程如图 5.1 所示,它通常包含许多小组,各小组负责不同的但又相互关联的工作。他们之间缺乏有效的交流手段,通常是通过各种文档、资料、数据等进行

沟通。由于不同的小组专注的问题层面不同,很难准确理解和贯彻彼此的意图,这增大了

产品开发的风险,延长了产品的上市时间。RTW可以帮助开发产品,如图 5.2所示。通过

删除的内容:

删除的内容: )

删除的内容: (

删除的内容: )

Page 196: Matlab Simulink

第 5章 Real-Time Workshop 181

Simulink 模型,RTW 能够自动生成面向不同目标系统的执行代码。通过这种方式,可以

方便地建立系统的模型,作为一个动态可执行规范,供各个小组快速地对系统进行检验,

提出改进措施。更为重要的是,自动代码生成的功能实现了从系统设计到实现的完美过

渡,大大减轻了软件工程师的编码工作量。

图 5.2 RTW提供的产品开发流程

5.2 自动代码生成过程

Real-Time Workshop的代码生成过程如图 5.3所示。Real-Time Workshop是若干执行工具和文件的集合。RTW 大多数操作都是在 Matlab 中执行的,也就是说,Matlab 是RTW 运行的环境。当使用 RTW 生成程序代码时, Simulink 框图可以视为程序的规范。建立一个程序代码的过程中生成以下的文件:

model.rtw:这是一个由 model.mdl生成的中间文件(model指用 Simulink搭建的系统模型的文件名),它是由 Matlab 的内建函数 rtwgen 创建的。model.rtw 文件包含对应于模型 model.mdl 中的每一个块(包含 S-函数块)的记录。这些记录通过花括号和 TLC关键字“Block”分隔。model.rtw与 model.mdl文件非常相似。

model.c:这个文件是通过目标语言编译器(例如图 5.3中的 tornado.tlc)创建的。model.c 文件是 Simulink 框图的 C 代码实现。目标语言编译器读取 model.rtw 文件,对于每一个 Block{}组件,目标语言编译器都会寻求一个对应的 TLC 文件(例如图 5.3中的 gain.tlc)。该 TLC文件告诉目标语言编译器如何用目标语言实现这个组件。包含在 TLC文件中的描述被写到 model.c当中。这些 TLC文件主要放在%MATLABROOT%\rtw\c(ada)\tlc\目录和各个模块库的 tlc_c(tlc_ada)目录下,它们是对应于 Simulink库中各模块的文件。用户编写的 TLC文件(例如图5.3 中的 sfun.tlc)可以用来描述用 C 语言编写的 S-函数模块(例如图 5.3 中的sfun.c)。如果 S-函数是用 C语言编写的(又叫 C-MEX S-函数),那么对这些函

删除的内容:

图 5.3 RTW 自动代码生成过程

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 197: Matlab Simulink

从Matlab/Simulink模型到代码实现 182

数的调用是在 model.c中进行的。

图 5.3 RTW 自动代码生成过程

model.mk:这是一个针对具体模型的 makefile文件。它是由 Matlab函数 rtw_c.p或rtw_ada.p 根据模板 makefile 文件(例如图 5.3 中的 tornado.tmf)创建的。模板makefile 文件的扩展名是 .tmf,名字对应于特定的目标。例如,对应于VxWorks/Tornado目标的模板 makefile文件是 tornado.tmf。rtw_c.p或 rtw_ada函数读取模板 makefile 文件并分析里面的标识。这些标识可以在 makefile 文件中的注释部分找到,带有|>TOKEN<|的标志。每个标识都作为 makefile 变量,用具体项目中的值来代替。

model.exe:这是已编译的目标程序(这里显示的.exe 扩展名,是 Microsoft 平台特有的)。它是通过安装在本机的编译器和连接器产生的。注意,并不是所有提供

的目标最终都生成 exe执行文件。

5.3 RTW支持的目标

如果安装了 Real-Time Workshop 模块,在 Simulink 模型的仿真参数对话框中,会出现 Real-Time Workshop 设置页面,如图 5.4 所示。单击 Browse 按钮,可以选择特定的 目标。

每个目标都对应两个特定的文件: 系统目标文件(*.tlc),是一个目标语言编译器(Target Language Compiler)。 模板 makefile文件(*.tmf)。 例如,目标 Tornado(VxWorks)Real-Time Target 对应的系统目标文件和模板

makefile 文件分别为 tornado.tlc、tornado.tmf。这两个文件在代码生成过程中的作用在 5.2节中已有描述。

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: …删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

Page 198: Matlab Simulink

第 5章 Real-Time Workshop 183

图 5.4 Real-Time Workshop参数设置

在 Windows 平台上,MATLAB R12.1 Real-Time Workshop 支持的目标如图 5.5 所示。

图 5.5 Real-Time Workshop支持的目标

ASAM-ASAP2 Data Definition Target

ASAP2 是自动化和测量系统标准化组织(ASAM)提议的一种数据定义标准,是用于数据测量、标定和系统诊断的标准描述格式。RTW提供了两种能够产生 ASAP2文件的 目标:

ASAM-ASAP2 Data Definition Target只产生一个 ASAP2文件,而不会生成可执行

删除的内容:

删除的内容: (

删除的内容: )

Page 199: Matlab Simulink

从Matlab/Simulink模型到代码实现 184

文件; RTW Embedded Coder可以在代码生成的过程中产生一个 ASAP2文件。 选 择 ASAM-ASAP2 Data Definition Target , 使 用 默 认 参 数 , 由 模 型

%MATLABROOT%\toolbox\stateflow\sfdemos\sf_car.mdl生成的 ASAP2文件如下所示。 ************************************************************************ * * ASAP2 file: sf_car.a2l * * Real-Time Workshop code generation for Simulink model "sf_car.mdl". * * Model Version : 1.132 * Real-Time Workshop file version : 4.1 $Date: 2001/05/16 13:59:43 $ * Real-Time Workshop file generated on : Mon Dec 17 20:59:10 2001 * TLC version : 4.1 (May 19 2001) * C source code generated on : Mon Dec 17 20:59:15 2001 * * Relevant TLC Options: * InlineParameters = 1 * RollThreshold = 5 * CodeFormat = RealTime * * Simulink model settings: * Solver : FixedStep * StartTime : 0.0 s * StopTime : 30.0 s * FixedStep : 0.04 s * * (add additional file header information here) * ***************************************************************************/ ASAP2_VERSION 1 30 /begin PROJECT unspecified "" /begin HEADER "" /* (add HEADER definition here) */ /end HEADER /begin MODULE unspecified "" /begin A2ML

删除的内容: on

Page 200: Matlab Simulink

第 5章 Real-Time Workshop 185

/* (add A2ML definition here) */ /end A2ML /begin MOD_PAR "" /* (add mod_par definition here) */ /end MOD_PAR /begin MOD_COMMON "" /* (add mod_common definition here) */ /end MOD_COMMON /begin RECORD_LAYOUT Scalar_UBYTE FNC_VALUES 1 UBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_BYTE FNC_VALUES 1 SBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_UWORD FNC_VALUES 1 UWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_WORD FNC_VALUES 1 SWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_ULONG FNC_VALUES 1 ULONG COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_LONG FNC_VALUES 1 SLONG COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_FLOAT32_IEEE FNC_VALUES 1 FLOAT32_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Scalar_FLOAT64_IEEE FNC_VALUES 1 FLOAT64_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT

Page 201: Matlab Simulink

从Matlab/Simulink模型到代码实现 186

/begin RECORD_LAYOUT Lookup1D_UBYTE NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 UBYTE INDEX_INCR DIRECT FNC_VALUES 4 UBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_BYTE NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 SBYTE INDEX_INCR DIRECT FNC_VALUES 4 SBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_UWORD NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 UWORD INDEX_INCR DIRECT FNC_VALUES 4 UWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_WORD NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 SWORD INDEX_INCR DIRECT FNC_VALUES 4 SWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_ULONG NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 ULONG INDEX_INCR DIRECT FNC_VALUES 4 ULONG COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_LONG NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 SLONG INDEX_INCR DIRECT FNC_VALUES 4 SLONG COLUMN_DIR DIRECT /end RECORD_LAYOUT

删除的内容: X

删除的内容: VALUES

删除的内容: RESERVED

删除的内容: VALUES

Page 202: Matlab Simulink

第 5章 Real-Time Workshop 187

/begin RECORD_LAYOUT Lookup1D_FLOAT32_IEEE NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 FLOAT32_IEEE INDEX_INCR DIRECT FNC_VALUES 4 FLOAT32_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup1D_FLOAT64_IEEE NO_AXIS_PTS_X 1 UBYTE RESERVED 2 UBYTE AXIS_PTS_X 3 FLOAT64_IEEE INDEX_INCR DIRECT FNC_VALUES 4 FLOAT64_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_UBYTE NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 UBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_BYTE NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 SBYTE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_UWORD NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 UWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_WORD NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 SWORD COLUMN_DIR DIRECT /end RECORD_LAYOUT

删除的内容: RESERVED

Page 203: Matlab Simulink

从Matlab/Simulink模型到代码实现 188

/begin RECORD_LAYOUT Lookup2D_ULONG NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 ULONG COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_LONG NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 SLONG COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_FLOAT32_IEEE NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 FLOAT32_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT /begin RECORD_LAYOUT Lookup2D_FLOAT64_IEEE NO_AXIS_PTS_X 1 UBYTE NO_AXIS_PTS_Y 2 UBYTE RESERVED 3 UBYTE FNC_VALUES 4 FLOAT64_IEEE COLUMN_DIR DIRECT /end RECORD_LAYOUT /end MODULE /end PROJECT /* (add any file trailer comments here) */ /* EOF sf_car.a2l */

DOS(4GW)Real-Time Target

DOS(4GW)Real-Time Target 提供了一种在 DOS 环境中实时运行 Simulink 模型的方式,但是同时 xPC Target和 Real-Time Windows Target提供了比它更好的性能,推荐用户使用 xPC Target 和 Real-Time Windows Target 两种目标之一做面向 PC 平台的实时开发。DOS(4GW)Real-Time Target 需要 WATCOM C 编译器。DOS(4GW) Real-Time Target 可生成一个在 DOS 操作系统环境中实时运行的可执行文件,这种可执行文件在Microsoft Windows DOS命令窗口不能正确运行。如果想在Microsoft Windows环境中实时

删除的内容: RESERVED

删除的内容: RESERVED

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: 你

Page 204: Matlab Simulink

第 5章 Real-Time Workshop 189

地运行代码,请选择 Real-Time Windows Target。

RTW Embedded Coder

RTW Embedded Coder是 MathWorks提供的基于 RTW的一个单独的模块产品,它提供了生成嵌入式代码的一个框架。这种代码对速度、内存和代码量都作了优化。RTW Embedded Coder 生成的代码适于嵌入式系统的代码实现,它生成的是嵌入式 C 代码。RTW Embedded Coder有如下特点:

可生成定点代码; 可生成浮点代码; 对单速率或者多速率系统,都支持异步中断方式; 自动生成 S-函数封装模块,使得用户可在 Simulink中验证 RTW Embedded Coder生成的代码(软件在回路仿真);

自动生成 HTML格式的代码生成报告。 注意,RTW Embedded Coder只支持内嵌的(inlined)S-函数。 RTW Embedded Coder 生成的代码的效率非常高,早期版本的测试结果如图 5.6 所

示,MATLAB R12.1中 RTW Embedded Coder的版本是 2.0,效率应当更高。

图 5.6 RTW Embedded Coder生成的代码的效率测试结果

Visual C/C++ Project Makefile only for the RTW Embedded Coder

集成 RTW Embedded Coder生成的代码,生成一个 Visual C/C++工程文件。

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

Page 205: Matlab Simulink

从Matlab/Simulink模型到代码实现 190

Generic Real-Time Target

Generic Real-Time Target生成的是非实时的仿真代码,它静态地分配模型运行需要的内存空间,通常用于快速仿真。它可以作为创建那些不使用实时操作系统任务原语的实时

目标快速原型的起点。

Visual C/C++ Project Makefile only for the “grt” target

集成 Generic Real-Time Target生成的代码,生成一个 Visual C/C++工程文件。

Generic Real-Time Target with dynamic memory allocation

类似于 Generic Real-Time target,只是动态分配内存空间。

Visual C/C++ Project Makefile only for the “grt_malloc” target

集成 Generic Real-Time Target with dynamic memory allocation生成的代码,生成一个Visual C/C++工程文件。

(Beta)LE/O (Lynx-Embedded OSEK) Real-Time Target

LE/O(Lynx-Embedded OSEK)Real-Time Target生成可在 Lynx-Embedded OSEK上实时运行的代码。OSEK是汽车控制器开发的一个行业标准。

Rapid Simulation Target

Rapid Simulation Target可以生成快速的独立运行的非实时仿真程序,主要用于批处理或者Monte Carlo仿真。针对 Rapid Simulation Target 生成的可执行文件,用户很容易写出运行批处理仿真的 m语言脚本。

Ada83 Target for GNAT

Ada Simulation Target for GNAT

Ada Multitasking Real-Time Target for GNAT

Ada是美国军方使用的编程语言的一个标准,在中国使用得较少。

Real-Time Windows Target

Real-Time Windows Target 是 MathWorks 公司提供的实时系统快速原型和测试的 PC

删除的内容: ,

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: ,

Page 206: Matlab Simulink

第 5章 Real-Time Workshop 191

解决方案 。它在Microsoft Windows环境中实时地运行模型,同时在 Simulink环境中观测仿真的结果。Real-Time Windows Target的典型应用包括:

实时控制 实时的硬件在回路仿真 教学为学生树立建模、仿真和测试实时系统及进行迭代设计的整个流程和概念

S-function Target

S-function target,可让用户创建 S-函数模块,该模块可用于其他 Simulink模型中。S-function Target 生成的代码格式遵循 Simulink C MEX S-函数 API。 S-function Target 可 用于:

将一个 Simulink模型转换成一个模块,该模块可用于其他模型中; 将一个子系统转换成一个模块; 加速仿真; 代码重用。

S-function Target 生成的是非内嵌的(noninlined)S-函数,它不能被 RTW Embedded Coder调用,因为 RTW Embedded Coder只支持内嵌的(inlined)S-函数。

Target for C6701 EVM

Target for C6701 EVM将 Simulink模型生成面向 C6701 EVM的一个 TI CCS工程文件,并且可直接编译、下载和运行。

Tornado(VxWorks)Real-Time Target

Tornado(VxWorks)Real-Time Target将 Simulink模型生成可在 VxWorks/Tornado环境中实时运行的任务。

xPC Target

xPC Target 是 MathWorks 公司针对基于 PC 硬件的实时操作系统产品提供的快速原型、测试和发布的主机-目标机解决方案。在 xPC Target 环境中,主机用于创建 Simulink模型、非实时仿真、产生和下载实时 xPC 代码,目标机用于实时地运行代码。主机和目标机之间可以以外部模式的方式工作,即在目标机上运行代码,在主机的 Simulink环境中观测运行结果。

MathWorks 公司的第三方厂商也提供一些基于 Real-Time Workshop 的目标,请登录网址 http://www.mathworks.com/products/connections查询。

删除的内容: ─

删除的内容: target

删除的内容: :

删除的内容: target

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

Page 207: Matlab Simulink

从Matlab/Simulink模型到代码实现 192

5.4 RTW的价值

RTW 的价值在于能够从系统设计的 Simulink 模型直接生成面向目标的代码,减少了用户编写代码的工作量,对于某些目标用户甚至不需要编写一行代码,例如针对目标

C6701 EVM,就可以完成从编译、连接、下载直至运行的整个过程。 RTW 具有完全可定制的生成过程,可从任意固定步长的模型中生成代码,它的用途

主要体现在以下几个方面: 快速仿真; 快速原型; 实时实现; 提供了建立实时程序的框架; 提供了开放的接口以支持第三方硬件和工具。 本书的后续章节将介绍一些产品实现中常用的 Real-Time Workshop支持的目标。

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容: 提供了开放的接口以支持第三方硬件和工具

本书的后续章节将介绍一些

产品实现中常用的 Real-Time Workshop支持的目标。

Page 208: Matlab Simulink

第 6章 面向 TI DSP 的自动代码生成

6.1 Developer’s Kit for TI DSP 概述

Developer’s Kit for TI DSP是MathWorks公司和 Texas Instruments(TI)公司合作开发的一个基于 Simulink 和 Real-Time Workshop 的开发工具箱。有了这个开发工具箱,用户可以在 Simulink 环境中搭建数字信号处理的算法,然后通过 Real-Time Workshop 生成面向 TMS320C6701 Evaluation Module(C6701 EVM)或者 Texas Instruments Code Composer Studio Integrated Development Environment(CCS IDE)的 ANSI C 代码。Developer’s Kit for TI DSP可以利用 TI 的编译工具将生成的代码编译成面向 C6701 EVM的机器码,并可将该机器码直接下载到 C6701 EVM 上执行。为了支持面向 C6701 EVM 的代码生成,

Developer’s Kit for TI DSP提供了一个基于 Real-Time Workshop的目标 Target for C6701 EVM。使用这个目标,用户可以从 Simulink模型生成 C6701 EVM的可执行文件或者生成一个针对 C6701 EVM的 CCS IDE工程文件。用户可以在 CCS IDE环境中修改该工程文件,然后再编译下载。

Texas Instruments可向用户提供 C6701 EVM,帮助用户开发针对 TMS320C6701的数字信号处理程序。一方面,C6701 EVM 上为 TMS320C6701 DSP 提供了输入端口、输出端口、时钟电路、内存单元和电源;另一方面,MathWorks公司和 TI公司为 Windows用户提供了集成的开发环境 ,方便用户开发、编译、下载和调试在 C6701 EVM上运行的算法程序。

除了能够产生面向 C6701 EVM的代码,Developer’s Kit for TI DSP还提供了使用 CCS IDE和 TI Real-Time Data Exchange (RTDX)的两个接口。

6.2 三 种 接 口

Developer’s Kit for TI DSP向用户提供的三种接口,如图 6.1所示。

Target for CCS IDE/C6701 EVM

Target for CCS IDE/C6701 EVM可让用户从数字信号处理的 Simulink模型自动生成面

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

Page 209: Matlab Simulink

从Matlab/Simulink模型到代码实现 194

向 C6701 EVM的 CCS IDE工程文件,并可进一步自动编译下载到 C6701 EVM上执行。设计人员可以快速地将数字信号处理的算法模型下载到实时硬件平台上执行,用以评估算

法的性能,或者转换成一个 CCS IDE工程文件,实现从 Simulink环境到 CCS IDE环境的无缝连接。通过 Target for CCS IDE/C6701 EVM,用户可以方便地利用MathWorks公司提供的 DSP、通信和数学算法库,将主要的精力放在设计而不是在 DSP 编程上,进行反复的迭代设计,直到算法满足系统性能要求。Target for CCS IDE/C6701 EVM对用户的价值在于:

有助于实现 DSP算法原型; 系统级的算法验证; 从 Simulink模型到 CCS IDE工程的无缝转换; 降低编写 DSP代码的难度和工作量。

图 6.1 三种接口

Link for CCS IDE

Link for CCS IDE接口实现了 CCS IDE和Matlab之间的连接,允许用户在MATLAB命令窗口下载运行 CCS IDE 中的程序,与目标内存之间(非实时地)交换数据,检测处理器的状态,停止或者启动程序在 DSP中的运行。Link for CCS IDE 对用户的价值在于:

用户可以利用 MATLAB 强大的数据分析和可视化功能,节省设计和调试程序的 时间;

可以编写用于调试数字信号处理程序的 m 语言批处理脚本,实现调试和分析的自动化;

支持 TI 的 C5000/6000 系列 DSP。

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容:

删除的内容: 有助于实现DSP算法原型;

删除的内容: 系统级的算法验证;

从 Simulink模型到 CCS IDE工程的无缝转换;

降低编写 DSP代码的难度和工作量。

删除的内容: (

删除的内容: )

Page 210: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 195

Link for RTDX

Link for RTDX接口提供了MATLAB和支持 RTDX的 TI DSP上运行的程序之间实时交换数据的一种方式。通过 Developer’s Kit for TI DSP 提供的 MATLAB ActiveX 对象CCSDSP,可以建立 MATLAB和 DSP之间的通信通道,在 MATLAB命令窗口和 DSP处理程序之间实时地发送和接收数据,而不必中断目标程序的运行。Link for RTDX 对用户的价值在于:

可以实现对实时数据的自动的高级分析和可视化; 实现对复杂 DSP程序的有效验证; 支持 TI 的 C5000/6000 系列 DSP。

6.3 Developer’s Kit for TI DSP的安装

Developer’s Kit for TI DSP直到MATLAB R12.1才开始正式发行。在MATLAB R12.1中,它的版本号是 1.1,这可用 ver命令查到:

>> ver tiddk Developer's Kit for TI(tm) DSP Version 1.1 (R12.1) 08-Jun-2001

安装 Developer’s Kit for TI DSP需要: MATLAB基本模块; Simulink基本模块; DSP Blockset; Real-Time Workshop; Signal Processing Toolbox; Texas Instruments Code Composer Studio Integrated Development Environment 1.2或更高版本。

另外, 为了 Target for C6701 EVM 接口能够下载运行 DSP 程序,用户需要至少一个

TMS320C6701 EVM。如果只是生成面向 C6701 EVM 的工程文件,可以不要

TMS320C6701 EVM。 为了使用 Link for CCS IDE或者 Link for RTDX接口,需要至少一个 CCS IDE支持的 TI DSP开发系统。Link for CCS IDE可以使用 CCS IDE 提供的软件仿真器,但 Link for RTDX需要支持 RTDX接口的 C5000/6000硬件平台。

即使是使用 Link for CCS IDE和 Link for RTDX(这两种接口是Matlab和 TI DSP之

带格式的: 项目符号和编号

删除的内容: 可以实现对实时数据的自动的高级分析和可

视化;

实现对复杂 DSP程序的有效验证;

支持 TI 的 C5000/6000 系列DSP。

删除的内容: ;

Page 211: Matlab Simulink

从Matlab/Simulink模型到代码实现 196

间的接口),用户也需要: MATLAB基本模块; Simulink基本模块。

安装完 Developer’s Kit for TI DSP后,在%MATLABROOT%\toolbox目录下会包含一个如图 6.2所示的目录结构,它是 Developer’s Kit for TI DSP安装后生成的目录结构。

图 6.2 Developer’s Kit for TI DSP目录

6.4 从Matlab访问 TI DSP

实现Matlab到 TI DSP的访问,有两种接口:Link for CCS IDE和 Link for RTDX。下面分别举例说明如何使用这两种接口。

Link for CCS IDE

【例 19】Link for CCS IDE示例。linkforccsidedemo.m是使用 Link for CCS IDE接口访问 TI DSP 内存的一个例子(这个例子其实就是%MATLABROOT%\toolbox\tiddk\ tidemos\ccstutorial.m),在MATLAB命令窗口运行这个例子之前,先要用 Code Composer Setup正确地设置 TI DSP系统开发环境。本例运行时的配置如图 6.3所示。

带格式的

删除的内容: ide

删除的内容: (

删除的内容:

删除的内容: )

删除的内容: ,

删除的内容: 其

删除的内容: 文中的文件名是否要与程序中一致

Page 212: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 197

图 6.3 Code Composer Setup

以下为 linkforccsidedemo.m文件代码:

1 % linkforccsidedemo.m 2 % LINKFORCCSIDEDEMO is an example script intended to get the user started with 3 % the 'Link for Code Composer Studio IDE'. A simple target DSP 4 % application is loaded and run on the target DSP. Memory reads/writes 5 % are demonstrated. Methods that are demonstrated include 6 % Global Commands: 7 % ccsboardinfo, boardprocsel, ccsdsp, clear 8 % CCSDSP object methods: 9 % visible,disp,info,isrunning,address,halt,run,restart,read, write 10 % regread,regwrite,visible. 11 % 12 13 echo off 14 15 % ==================================================================

删除的内容: s

删除的内容: (linkforccsdemo.m的文本请和原文保持一致)

删除的内容:

删除的内容: ‘

删除的内容: ’

删除的内容:

删除的内容:

Page 213: Matlab Simulink

从Matlab/Simulink模型到代码实现 198

16 % Intro 17 disp(sprintf(['=================================================\n'… 18 ' The ''Link for Code Composer(tm) Studio IDE'' provides a direct\n'… 19 ' connection between MATLAB and a DSP CPU in Code Composer.\n'… 20 ' This provides a mechanism for controlling and manipulating\n'… 21 ' a DSP application using the full computational power of MATLAB.\n'… 22 ' This can be used to assist DSP debugging and development.\n'… 23 ' Another possible use is for creation of MATLAB scripts for\n'… 24 ' verification and testing of algorithms that exist in their \n'… 25 ' final implementation on an actual DSP target.\n\n'… 26 ' Before discussing the methods available with the link object,\n'… 27 ' it''s necessary to select a DSP CPU to target. When the\n'… 28 ' link is created, it is specific to a particular CPU,\n'… 29 ' (i.e. a DSP chip) so selection is required before proceeding\n'… 30 ' In general, the selection processor is only necessary \n'… 31 ' for multiprocessor configurations of Code Composer.\n'… 32 '===========================================================\n\n'])); 33 disp('--- Press any key to continue ---'); 34 pause; 35 36 % ================================================================= 37 38 % command line board/processor selection command: ccsboardinfo 39 disp(sprintf(['=================================================\n'… 40 ' The ''Link for Code Composer(tm) Studio'' provides two tools for\n'… 41 ' selecting a DSP board and processor in multiprocessor\n'… 42 ' configurations. First, a command line version called: ''ccsboardinfo'' \n'… 43 ' which prints a list of the available boards and processors.\n'… 44 ' For scripting, this command can return a structure, which\n'… 45 ' can be applied to programmatically select a particular DSP chip.\n'… 46 '==========================================================\n\n'])); 47 disp('--- Press any key to continue: ccsboardinfo ---'); 48 pause; 49 echo on 50 ccsboardinfo 51 echo off; 52 53 % ================================================================== 54 55 % GUI board/processor selection tool: boardprocsel 56 disp(sprintf(['================================================\n'…

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…‘

删除的内容: ‘…’

... [16]

... [17]

... [4]

... [18]

... [12]

... [19]

... [1]

... [6]

... [2]

... [3]

... [7]

... [21]

... [8]

... [22]

... [9]

... [23]

... [10]

... [24]

... [11]

... [5]

... [25]

... [20]

... [13]

... [26]

... [14]

... [27]

... [15]

... [28]

Page 214: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 199

57 ' Another selection option is a GUI tool called ''boardprocsel''.\n'… 58 ' Please Note – the CPU that is selected in the GUI will be used\n'… 59 ' for the rest of this tutorial. For single processor installations,\n'… 60 ' of Code Composer Studio, simply press ''OK'' to continue.\n’… 61 '=========================================================\n\n'])); 62 63 disp('--- Press any key to continue, then select a DSP from the GUI: boardprocsel ---'); 64 65 pause; 66 echo on 67 [boardNum,procNum] = boardprocsel 68 echo off 69 70 if isempty(boardNum) | isempty(procNum), 71 disp(sprintf(['The board/processor GUI was canceled without selecting a valid device\n'… 72 ' Please restart the tutorial and select a valid board and processor\n'])); 73 error('No board or processor selected to create Link' ); 74 else 75 fprintf(1,[ '\n The goal of this selection process is a board number\n' 76 ' and processor number that uniquely identify a particular\n'… 77 ' target DSP. These values are then applied during the link creation.\n\n' 78 ' You selected board number = %d, and processor number = %d\n\n'],boardNum,procNum); 79 end 80 %================================================================== 81 % Object Constructor: ccsdsp 82 disp(sprintf(['================================================\n'… 83 ' Next, the actual connection between the MATLAB command line and Code \n'… 84 ' Composer will be established. This link is represented by a MATLAB\n'… 85 ' object, which for this session will be saved in variable ''cc''. The\n'… 86 ' link object is created with the ''ccsdsp'' command, which accepts the\n'… 87 ' board number and processor number as input parameters. Other\n'… 88 ' properties can also be defined during the object creation; refer to\n'… 89 ' the ''ccsdsp'' documentation for more information on these properties.\n'… 90 ' The generated ''cc'' object will be used to direct actions to the \n'… 91 ' designated DSP chip. Therefore, it will appear in all commands that\n'… 92 ' follow the object creation. Naturally, in multiprocessor \n'… 93 ' implementations it is possible to have more than one link object.\n'… 94 ' NOTE – Before proceeding, your DSP hardware should be reset and \n'… 95 ' configured as needed for operation by Code Code Composer.\n'… 96 '==========================================================\n\n'])); 97

删除的内容: ‘

删除的内容: …

删除的内容: ‘‘…’’…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ‘

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’…

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’…

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

... [38]

... [34]

... [33]

... [51]

... [32]

... [35]

... [52]

... [36]

... [53]

... [47]

... [48]

... [54]

... [40]

... [37]

... [49]

... [41]

... [29]

... [56]

... [50]

... [42]

[57]

... [55]

... [43]

... [30]

... [44]

... [46]

... [31]

... [39]

... [45]

Page 215: Matlab Simulink

从Matlab/Simulink模型到代码实现 200

98 disp('--- Press any key to continue: ccsdsp ---'); 99 100 pause; 101 echo on 102 cc=ccsdsp('boardnum',boardNum, 'procnum',procNum) 103 echo off 104 %================================================================== 105 % Visibility of Code Composer 106 disp(sprintf([‘=================================================\n'… 107 ' You may have noticed Code Composer appear briefly when ''ccsdsp''\n'… 108 ' was called. If Code Composer was not running before the link\n'… 109 ' is established, it is started and then placed in the background.\n'… 110 ' In most cases, the user will need to interact with Code Composer,\n'… 111 ' so the first method that will be introduced (called ''visible'')\n'… 112 ' controls the state of Code Composer on the desktop. This accepts\n’… 113 ' a Boolean input that makes Code Composer visible (1) or \n’… 114 ' invisible (0) on the desktop. For the rest of this tutorial, \n’… 115 ' we will need to interact with Code Composer, so we''ll use \n'… 116 ' ''visible'' to bring it up to the desktop.\n'… 117 '===========================================================\n\n'])); 118 119 disp('--- Press any key to continue: visible ---'); 120 121 pause; 122 echo on 123 cc.visible(1) % Force Code Composer to be visible on the desktop 124 echo off 125 %================================================================== 126 % Link Status: info, isrunning, disp 127 disp(sprintf(['================================================\n'… 128 ' With the link in place, it is now possible from MATLAB to\n'… 129 ' query Code Composer for status on the specified DSP CPU\n'… 130 ' Three methods are available to receive status information: \n'… 131 ' ''info'' – returns a structure of testable Target conditions.\n'… 132 ' ''disp'' – prints a list of information about the target CPU.\n'… 133 ' ''isrunning'' – returns the state (running or halted) of the CPU.\n'… 134 ' The next segment will demonstrate these methods.\n'… 135 '===========================================================\n\n'])); 136 disp('--- Press any key to continue: info,disp,isrunning ---'); 137 pause; 138 echo on

删除的内容: ‘…‘

删除的内容: ‘…’…’…’

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ‘‘…’’…’

删除的内容: ‘

删除的内容:

删除的内容: ‘

删除的内容: ‘

删除的内容:

删除的内容: ‘…’’…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…‘

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘… …‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘

... [59]

... [63]

... [70]

... [61]

... [60]

... [62]

... [72]

... [67]

... [73]

... [68]

... [74]

... [69]

... [75]

... [64]

... [76]

... [71]

... [77]

... [65]

... [78]

... [66]

... [79]

Page 216: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 201

139 disp(cc) 140 linkinfo = info(cc) 141 cpurunstatus = isrunning(cc) 142 echo off 143 144 %=================================================================== 145 146 % Determine family (5x or 6x) 147 sfamily = linkinfo.subfamily; 148 if sfamily >= hex2dec('50') & sfamily < hex2dec('60'), 149 c5xfamily = (1==1); 150 elseif sfamily >= hex2dec('60') & sfamily < hex2dec('70'), 151 c5xfamily = (1==0); 152 else 153 error(' The selected family of DSP Processors is NOT supported by this product'); 154 end 155 disp(sprintf(['From the ''subfamily'' and ''revfamily'' members of the structure\n'… 156 ' returned by the ''info'' method, it was determined that you selected\n'… 157 ' a TMS%03dC%2s%02d DSP processor.\n'… 158 'Please note – In some cases, the values reported by Code Composer\n'… 159 ' do not match the physical device numbering scheme.\n\n'],… 160 linkinfo.family,dec2hex(linkinfo.subfamily),linkinfo.revfamily)); 161 162 %================================================================== 163 164 % The Code Composer Files: load/open 165 166 disp(sprintf([‘================================================\n’… 167 168 ' Now that a connection has been established, the target CPU needs\n'… 169 ' something to do! Therefore, the next step is to create executable \n'… 170 ' code for the target CPU with Code Composer. For this tutorial, a\n'… 171 ' Code Composer project file was written and included with MATLAB. \n'… 172 ' The following set of commands will locate the tutorial project\n'… 173 ' file and load it into Code Composer. This will use the ''open''\n'… 174 ' method, which can direct Code Composer to load a project files \n'… 175 ' or workspace file. (Note – Code Composer has its own workspace\n'… 176 ' files, which are quite different from MATLAB workspace files).\n'… 177 ' Before proceeding, load a valid GEL file to configure the EMIF\n',… 178 ' registers of your DSP and perform any required initialization.\n',… 179 ' The default GEL files are located in the TI directory space:\n',…

删除的内容: ‘…’…‘…’

删除的内容: ‘…’…‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ‘‘…’’…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

... [81]

... [85]

... [92]

... [87]

... [82]

... [95]

... [86]

... [84]

... [88]

... [89]

... [98]

... [94]

... [83]

... [93]

... [99]

... [80]

... [96]

... [91]

... [100]

... [90]

... [97]

... [101]

Page 217: Matlab Simulink

从Matlab/Simulink模型到代码实现 202

180 ' (TI)\\cc\\gel. Use menu option File->Load_GEL in Code Composer. \n',… 181 ' With executable code running on the DSP, we can get down to the\n'… 182 ' ultimate goal: exchanging data blocks with the target!\n'… 183 '==========================================================\n\n'])); 184 disp('--- Load a GEL File(if necessary), then press any key to continue: open ---'); 185 pause; 186 if c5xfamily, 187 echo on 188 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_54xx.mak') 189 projpath = fileparts(projfile) 190 open(cc,projfile) % Open project file 191 cd(cc,projpath) % Change working directory of Code Composer(only) 192 echo off 193 elseif cc.info.revfamily > 10, 194 echo on 195 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x11.mak') 196 projpath = fileparts(projfile) 197 open(cc,projfile) % Open project file 198 cd(cc,projpath) % Change working directory of Code Composer(only) 199 echo off 200 else 201 echo on 202 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x0x.mak') 203 projpath = fileparts(projfile) 204 open(cc,projfile) % Open project file 205 cd(cc,projpath) % Change working directory of Code Composer(only) 206 echo off 207 end 208 %================================================================== 209 % The Code Composer Files: address 210 211 disp(sprintf(['=================================================\n'… 212 213 213 ' You should notice the tutorial''s project file in Code Composer.\n'… 214 ' At this point, build the tutorial project from Code Composer.\n'… 215 ' (Go to the Project->Build menu option in Code Composer)\n'… 216 ' The ''Link for Code Composer'' includes methods for reading\n'… 217 ' the target''s symbol table to give direct access to data in \n'… 218 ' the DSP memory. Note – The symbol table is only available after \n'… 219 ' the program file is loaded into the DSP (and after build!).\n'… 220 ' The next step will load the generated program file ''a.out''\n'…

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ‘

删除的内容: ’…’…’…’…’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容:

删除的内容: ’…’…’…’…’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容:

删除的内容: ’…’…’…’…’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容:

删除的内容: ‘…’

删除的内容: ‘…’’

删除的内容:

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容: ‘‘…’’

删除的内容: ’

删除的内容: ‘

删除的内容: ’’

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…’

... [110]

... [115]

... [119]

... [103]

... [120]

... [118]

... [106]

... [107]

... [122]

... [116]

... [123]

... [121]

... [104]

... [124]

... [105]

... [111]

... [117]

... [112]

... [102]

... [113]

... [125]

... [114]

... [108]

... [126]

... [109]

... [127]

Page 218: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 203

221 ' using the ''load'' method. Notice the results of checking\n'… 222 ' the symbol table for the variable ''ddat'' before and after\n'… 223 ' the load.\n'… 224 '==========================================================\n\n’])); 225 disp('--- Build the program file, then press any key to continue: load,address,dec2hex ---'); 226 pause; 227 try 228 echo on 229 warnState = warning('on'); % Enable warnings to demonstrate the next command 230 address(cc, 'ddat') % Note – This may (correctly) issue a warning before the executable file is loaded. 231 warning(warnState); % Reinstate warning state 232 load(cc, 'a.out',30) % Load the target execution file 233 ddatA = address(cc, 'ddat') % Now it should find the address of global value: ddat 234 dec2hex(ddatA) % in hexadecimal (address and page) 235 echo off 236 catch 237 echo off 238 warnState = warning(warnState); 239 disp(lasterr); 240 240 disp(sprintf(['!!!!! The load of ''a.out'' failed. Please attempt to rebuild it\n'… 241 'and then manually load it from Code Composer before proceeding. \n'… 242 'Then press return to attempt the load operation again\n'])); 243 pause; 244 echo on 245 load(cc, 'a.out',40) % Load the target execution file 246 ddatA = address(cc, 'ddat') % Read the address of global: ddat 247 dec2hex(ddatA) % in hexadecimal (address and page) 248 echo off 249 end 250 251 %=================================================================== 252 253 % Halt, run, read 254 disp(sprintf(['================================================\n'… 255 ' With the target code loaded, it is now possible to examine\n'… 256 ' and modify data values in the DSP target from MATLAB.\n'… 257 ' If you look at the source file listing in the Code Composer \n'… 258 ' application window, there should be a file labeled:\n'… 259 ' ''ccstut.c'', which was shipped with this tutorial and included\n'… 260 ' in the project. It has two global data arrays: ''ddat'' and \n'… 261 ' ''idat''. They are declared and initialized in lines 10 and 11.\n'…

带格式的

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容: ‘

删除的内容:

删除的内容: ‘

删除的内容: ‘…’

删除的内容:

删除的内容: ’…’

删除的内容:

删除的内容: ’…’

删除的内容: ’…’

删除的内容:

删除的内容: ‘… ‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ’…’

删除的内容: ’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

... [132]

... [139]

... [131]

... [142]

... [140]

... [143]

... [141]

... [144]

... [133]

... [145]

... [134]

... [129]

... [135]

... [147]

... [136]

... [148]

... [146]

... [137]

... [149]

... [128]

... [150]

... [138]

... [151]

... [130]

Page 219: Matlab Simulink

从Matlab/Simulink模型到代码实现 204

262 ' These DSP memory arrays can be accessed directly from\n'… 263 ' MATLAB command line using the ''read'' and ''write'' methods.\n'… 264 ' To control target execution use the ''run'', ''halt'' and\n'… 265 ' ''restart'' methods. To demonstrate these commands, go to\n'… 266 ' Code Composer and manually add a breakpoint to line 26 of\n'… 267 ' ''cctut.c''. Then proceed with the tutorial.\n'… 268 '===========================================================\n\n'])); 269 disp('--- Insert Breakpoint then press any key to continue: halt,restart,read ---'); 270 pause; 271 try 272 if c5xfamily, 273 echo on 274 halt(cc) % halt the CPU (if necessary) 275 restart(cc) % reset the PC to start of program 276 run(cc, 'runtohalt',20); % wait for program execution to stop at breakpoint! (timeout = 20 seconds) 277 278 ddatV = read(cc,address(cc, 'ddat'), 'single',4) % Should equal initialized value from C-Code 279 280 idatV = read(cc,address(cc, 'idat'), 'int16',4) 281 282 write(cc,address(cc, 'ddat'),single([pi 12.3 exp(-1) sin(pi/4)])) % Modify memory values 283 284 write(cc,address(cc, 'idat'),int16([1:4])) 285 286 run(cc, 'runtohalt',20); % Resume execution from breakpoint, then modify 287 288 ddatV = read(cc,address(cc, 'ddat'), 'single',4) 289 290 idatV = read(cc,address(cc, 'idat'), 'int16',4) 291 292 restart(cc); 293 echo off 294 else 295 echo on 296 halt(cc) % halt the CPU (if necessary) 297 restart(cc) % reset the PC to start of program 298 run(cc, 'runtohalt',20); % wait for program execution to stop at breakpoint! (timeout = 20 seconds) 299 300 ddatV = read(cc,address(cc, 'ddat'), 'double',4) % Should equal initialized value from C-Code 301

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’…‘‘…’’’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ‘

删除的内容: ’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容: ’…’

删除的内容:

删除的内容: ’…’

删除的内容: ’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容: ’…’…’…’

删除的内容: ’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容:

... [156]

... [154]

... [159]

... [163]

... [160]

... [155]

... [157]

... [161]

... [165]

... [162]

... [166]

... [153]

... [167]

... [152]

... [164]

... [168]

... [158]

Page 220: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 205

302 idatV = read(cc,address(cc, 'idat'), 'int32',4) 303 304 write(cc,address(cc, 'ddat'),double([pi 12.3 exp(-1) sin(pi/4)])) % Modify memory values 305 306 write(cc,address(cc, 'idat'),int32([1:4])) 307 308 run(cc, 'runtohalt',20); % Resume execution from breakpoint, then modify 309 310 ddatV = read(cc,address(cc, 'ddat'), 'double',4) 311 312 idatV = read(cc,address(cc, 'idat'), 'int32',4) 313 314 restart(cc); 315 316 echo off 317 end 318 catch 319 echo off 320 disp(lasterr); 321 disp(sprintf(['!!!! The program execution failed – Generally this is because the\n'…. 322 'breakpoint was not included in the source file. This caused the\n'… 323 'CPU to continue execution without halting. Try re-running the\n'… 324 'tutorial and be sure to insert the breakpoint when it is requested.\n'… 325 'In some cases, resetting the board before running the tutorial may be\n'… 326 'necessary. It is often helpful to verify the Target code in Code\n'… 327 'Composer before executing the tutorial.\n'])); 328 error('CCS Tutorial failure'); 329 end 330 331 %=================================================================== 332 333 % regread/regwrite 334 if c5xfamily, 335 disp(sprintf([‘================================================\n'… 336 ' For Assembly language programmers, there are also methods\n'… 337 ' to directly access CPU registers. For the c5xxx family, most\n'…. 338 ' registers are memory-mapped and consequently are available using \n'… 339 ' standard memory read/write methods. However, the ''PC'' register\n'… 340 ' is not memory-mapped and therefore requires a special pair of \n'… 341 ' methods: ''regread'' and ''regwrite''.\n'… 342 '==========================================================\n\n']));

删除的内容: ’…’…’…’

删除的内容: ’…’

删除的内容:

删除的内容: ’…’

删除的内容: ’…’

删除的内容:

删除的内容: ’…’…’…’

删除的内容: ’…’…’…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’

删除的内容:

删除的内容: ’

删除的内容: ‘

删除的内容:

删除的内容: ’

删除的内容: ‘…‘‘…’’…‘‘…’’

删除的内容: ‘…’

... [176]

... [183]

... [170]

... [172]

... [185]

... [179]

... [184]

... [171]

... [173]

... [182]

... [181]

... [186]

... [188]

... [174]

... [189]

... [175]

... [178]

... [180]

... [190]

... [169]

... [177]

... [191]

... [187]

... [192]

Page 221: Matlab Simulink

从Matlab/Simulink模型到代码实现 206

343 disp('--- Press any key to continue: regread/regwrite ---'); 344 pause; 345 echo on 346 cc.regread('PC', 'binary') 347 cc.regwrite('PC',hex2dec('100'), 'binary') 348 echo off 349 else 350 disp(sprintf(['=================================================\n'… 351 ' For Assembly language programmers, there are also methods\n'… 352 ' to access CPU registers: ''regread'' and ''regwrite''.\n'… 353 '===========================================================\n\n'])); 354 disp('--- Press any key to continue: regread/regwrite ---' ); 355 pause; 356 echo on 357 tReg = cc.regread('A0', '2scomp') % 2's complement version of A0 358 cc.regread('B2', 'binary') % Unsigned version of B2 359 cc.regwrite('A2',tReg, '2scomp') 360 echo off 361 end 362 363 %================================================================== 364 365 % Deleting the link: clear 366 disp(sprintf(['================================================\n'… 367 ' Finally, to delete the link to Code Composer, use\n'… 368 ' ''clear cc''. Note, if a link object exists, manually \n'… 369 ' exiting Code Composer will not kill the application. It\n'… 370 ' simply moves to the background. Once all link objects\n'… 371 ' have been deleted (or by quiting MATLAB), then\n'… 372 ' the Code Composer Application will be terminated.\n'… 373 ' However, a ''visible'' Code Composer is assumed\n'… 374 ' to be active and will never be halted by clearing\n'… 375 ' any Maltab links.\n'… 376 '==========================================================\n\n’])); 377 disp('--- Press any key to continue: clear ---' ); 378 pause; 379 echo on 380 clear cc 381 echo off

程序说明如下:

带格式的: 项目符号和编号

带格式的: 项目符号和编号

删除的内容: ‘…‘

删除的内容: ‘…’…’…’

删除的内容: ‘…’…‘…’…’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…‘‘…’’’

删除的内容: ‘…’

删除的内容: ‘…‘

删除的内容: ‘…’…’…’…’

删除的内容: ‘…’…’…’

删除的内容: ‘…’…’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘…‘‘…’’…’

删除的内容: ‘…’

删除的内容: ‘…’

删除的内容: ‘

删除的内容: ‘…‘

删除的内容: echo off

删除的内容:

... [196]

... [195]

... [198]

... [201]

... [197]

... [193]

... [200]

... [194]

... [199]

... [206]

... [202]

... [207]

... [210]

... [208]

... [213]

... [209]

... [203]

... [214]

... [204]

... [211]

... [205]

... [212]

Page 222: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 207

第 13行,关闭命令本身在MATLAB命令窗口的显示。 第 49行,开启命令本身在MATLAB命令窗口的显示。 第 50行,向 Code Composer Setup索取系统开发板和处理器的列表。

>> ccsboardinfo Board Board Proc Processor Processor Num Name Num Name Type --- ------ --- ---------------------------- -------------- 1 C64xx Simulator (Texas Instrum ... 0 CPU TMS320C6400 0 C6xxx EVM (Texas Instruments) 0 CPU_1 TMS320C6200

第 67 行,打开开发板和处理器选择对话框,选择目标板和目标板上的处理器,如图 6.4所示,返回板号和处理器号。

>> [boardNum,procNum] = boardprocsel boardNum = 1 procNum = 0

图 6.4 选择目标板和目标板上的处理器

第 70~79行,判断返回的目标板号和目标处理器号是否有效。 第 102行,创建 MATLAB CCSDSP对象 cc,用于 MATLAB和所选目标板、目标处理器之间的连接,同时以后台方式运行 Code Composer Studio。Link for CCS IDE接口就是通过操作 CCSDSP对象来实现的。

删除的内容: :

删除的内容: :

删除的内容:

图 6.4 选择目标板和目标板上的处理器

删除的内容:

删除的内容: ─

删除的内容: 和

Page 223: Matlab Simulink

从Matlab/Simulink模型到代码实现 208

>> cc=ccsdsp('boardnum',boardNum,'procnum',procNum) CCSDSP Object: API version : 1.0 Processor type : TMS320C64127 Processor name : CPU Running? : No Board number : 1 Processor number : 0 Default timeout : 10.00 secs

Developer’s Kit for TI DSP 提供了许多函数,用于操作 Link for CCS IDE,如表 6.1 所示。

第 123行,调用 cc的 visible方法,让读者可以见到 Code Composer Studio的开发环境。

>> cc.visible(1)

运行结果如图 6.5所示。

图 6.5 cc.visible(1)让开发环境可见

第 139行,显示目标处理器信息: >> disp(cc) CCSDSP Object:

删除的内容:

删除的内容: (对不起,原稿中该图放错了位置!!!)

删除的内容:

Page 224: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 209

API version : 1.0 Processor type : TMS320C64127 Processor name : CPU Running? : No Board number : 1 Processor number : 0 Default timeout : 10.00 secs

第 140行,返回包含目标处理器信息的一个结构。 >> linkinfo = info(cc) linkinfo = procname: 'CPU' isbigendian: 0 family: 320 subfamily: 100 revfamily: 127

timeout: 10

表 6.1 用于操作 Link for CCS IDE的函数

函 数 重 载 描 述

animate 在目标处理器上运行程序直到遇到断点为止

ccsboardinfo 返回 CCS IDE识别到的目标板或者仿真器的信息

ccsdsp 创建一个到 CCS IDE的连接

cd 改变 CCS IDE使用的工作目录

clear 是 终结 CCS IDE连接

dir 列出 CCS IDE当前工作目录中的文件

disp 是 显示 CCS IDE连接的属性

display 是 显示 CCS IDE连接的属性

get 是 返回 CCS IDE连接的属性值

halt 终止执行正在目标处理器上运行的进程

info 是 返回关于目标处理器的信息

isreadable 是 判断MATLAB能否读取指定的内存块

isrunning 检测目标处理器是否正在执行一个进程

isvisible 检测 CCS IDE是否正在 PC上可见

iswritable 是 检测MATLAB能否写指定的内存块

load 下载一个程序文件(*.out,*.obj)到目标处理器

open 是 装载一个文件到 CCS IDE

删除的内容:

删除的内容:

分页符

图 6.5 cc.visible(1)让开发环境可见

删除的内容: linkinfo = info(cc)运行结果

Page 225: Matlab Simulink

从Matlab/Simulink模型到代码实现 210

read 从目标处理器的指定内存提取数据 删除的内容:

Page 226: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 211

续表

函 数 重 载 描 述

regread 读取目标处理器指定寄存器中的数据值

regwrite 向目标处理器指定的寄存器中写入一个值

reset 复位目标处理器

restart 为目标处理器上的当前程序重置程序计数器到起始点

run 执行目标处理器上的程序

set 是 为 CCS IDE连接设置属性

symbol 从 CCS IDE返回最近的程序符号表

visible 设置 CCS IDE窗口的可见性

write 向目标处理器的指定内存写入数据

第 141行,返回目标处理器的运行状态,0表示没有运行,1表示处于运行状态。

cpurunstatus = isrunning(cc) cpurunstatus = 0

第 146~154行,判断目标处理器是否属于 TI C5000/6000系列 DSP。 第 155~160行,由 info返回的结构构造出目标处理器的名称。

>> disp(sprintf(['From the ''subfamily'' and ''revfamily'' members of the structure\n'...

' returned by the ''info'' method, it was determined that you selected\n'... ' a TMS%03dC%2s%02d DSP processor.\n'... 'Please note - In some cases, the values reported by Code Composer\n'... ' do not match the physical device numbering scheme.\n\n'],... linkinfo.family,dec2hex(linkinfo.subfamily),linkinfo.revfamily)); From the 'subfamily' and 'revfamily' members of the structure returned by the 'info' method, it was determined that you selected a TMS320C64127 DSP processor. Please note - In some cases, the values reported by Code Composer do not match the physical device numbering scheme.

第 186~207 行,根据目标处理器所属的系列,选择在 CCS IDE 中打开的工程文件,并将 MATLAB当前目录指向该工程文件所在的目录。本例中打开的工程文件如图 6.6所示。

第 227~249行,向目标处理器下载可执行文件 a.out,返回全局变量 ddat对应的内存地址,并将其转换成十六进制格式。

删除的内容: —

删除的内容: ─

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容: (上述命令格式请和原稿一致!!!)

删除的内容: ─

删除的内容: ,

删除的内容: ─

Page 227: Matlab Simulink

从Matlab/Simulink模型到代码实现 212

>> warnState = warning('on'); address(cc,'ddat') Warning: Address: Failed to locate symbol 'ddat' in symbol table ans = [] >>ddatA = address(cc,'ddat') ddatA = 1.0e+009 * 2.1475 0 >>dec2hex(ddatA) ans = 80000010 00000000

图 6.6 ccstut_6x11.mak

第 269~270行,提示插入一个断点,这时在图 6.6中的第 3条 printf语句处插入一个断点,然后按任意键继续。

第 271~329 行,运行程序至断点(图 6.6 中的第 3 条语句),然后读取全局变量ddat中的 4个双精度数至 MATLAB变量 ddatV中,读取全局变量 idat中的 4个整数至 MATLAB 变量 idatV 中;接着向全局变量 ddat 写入 4 个新的双精度数double([pi 12.3 exp(-1) sin(pi/4)],向全局变量 idat写入 4个新的整数 int32([1:4]);

删除的内容: ─

删除的内容: 请

删除的内容: ─

删除的内容: (

删除的内容: )

Page 228: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 213

再从断点处继续执行程序,然后再读取修改后的全局变量 ddat 中的 4 个双精度数至 MATLAB 变量 ddatV 中,读取修改后的全局变量 idat 中的 4 个整数至MATLAB变量 idatV中;最后复位 DSP计数器到执行程序的起点。

>> halt(cc) restart(cc) run(cc,'runtohalt',20); ddatV = read(cc,address(cc,'ddat'),'double',4) idatV = read(cc,address(cc,'idat'),'int32',4) write(cc,address(cc,'ddat'),double([pi 12.3 exp(-1) sin(pi/4)])) write(cc,address(cc,'idat'),int32([1:4])) run(cc,'runtohalt',20); ddatV = read(cc,address(cc,'ddat'),'double',4) idatV = read(cc,address(cc,'idat'),'int32',4) restart(cc); ddatV = 16.3000 -2.1300 5.1000 11.8000 idatV = 1 508 647 7000 ddatV = 3.1416 12.3000 0.3679 0.7071 idatV = 1 2 3 4

第 333~361行,读写指定寄存器的内容。 tReg = cc.regread('A0','2scomp') ,以补码格式读取寄存器 A0的内容;

删除的内容: 的执行

删除的内容: ─

Page 229: Matlab Simulink

从Matlab/Simulink模型到代码实现 214

>> tReg = cc.regread('A0','2scomp') tReg = 3

cc.regread('B2','binary') ,以无符号格式读取寄存器 B2的内容; >>cc.regread('B2','binary') ans = 1

cc.regwrite('A2',tReg,'2scomp'),向寄存器 A2写入数据 tReg的补码格式。 cc.regread('PC','binary'),以无符号格式读取程序计数器的内容; cc.regwrite('PC',hex2dec('100'),'binary'),向程序计数器写入 256 的无符号 格式。

第 380行,删除 CCSDSP对象,断开 Link for CCS IDE。 程序中有许多使用 disp和 pause语句的地方,那是用于在 MATLAB命令窗口产生提示信息。

Link for RTDX

【例 20】Link for RTDX示例。linkforrtdxdemo.m是使用 Link for RTDX接口实现和TI DSP 实时交换数据的一个例子(这个例子其实就是%MATLABROOT%\toolbox\tiddk\ tidemos\rtdxtutorial.m)。在 MATLAB命令窗口运行这个例子之前,需要有支持 RTDX接口的 C5000/6000硬件平台并且正确设置 Code Composer Setup。本例运行时假设已经正确地安装了 C6701 EVM并且设置了 Code Composer Setup。

以下为 linkforrtdxdemo.m程序代码: 1 %linkforrtdxdemo.m 2 % LINKFORRTDXDEMO is an example script intended to get the user started with the 3 % Link for RTDX. A simple target DSP application is loaded and run on the 4 % target DSP, and data messages are transfered via RTDX between the host 5 % application (MATLAB) and the target DSP. The tutorial writes integers 1:10 6 % to the target DSP. The target DSP takes the array of integers and 7 % increments it by 1 and writes the resultant array to the host. This action 8 % is performed 20 successive times, with each iteration incrementing the the 9 % previous array result by one. The 20 messages are read by the script using 10 % READMSG and READMAT, employing various output formats. 11 %

带格式的: 项目符号和编号

删除的内容: ,

删除的内容: (

删除的内容:

删除的内容: )

删除的内容: ,

删除的内容: (

删除的内容: (linkforrtdxdemo.m的文本请和原稿一致

删除的内容: !!!

删除的内容: !!!

删除的内容: )

删除的内容: )

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 230: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 215

12 13 % Board and processor selection 14 disp(sprintf(['You will need to select a board and processor using the '... 15 'BOARD SELECTION TOOL.\nHit any key to bring up the selection tool...'])); 16 pause; 17 18 [boardNum,procNum] = boardprocsel; 19 echo on 20 cc=ccsdsp('boardnum',boardNum,'procnum',procNum) 21 echo off 22 23 % Make sure selected processor is RTDX-compatible 24 % ================================================================= 25 count = 0; 26 notReady = 1; 27 while notReady & count < 2, 28 if cc.isrtdxcapable, 29 if (cc.info.subfamily >= hex2dec('50')) & ... 30 (cc.info.subfamily <= hex2dec('5f')), 31 c5x = logical(1); 32 target_subdir = 'c5x'; 33 outFile = 'rtdxtutorial_5x.out'; 34 notReady = 0; 35 % GEL reset 36 disp('Hit any key to continue...'); 37 pause 38 uiwait(msgbox({'For the C54xx, you may need to manually load c5000.gel ';... 39 'and then run C5402_DSK_Init under GEL --> C54x.'}, ... 40 'Warning: Reset GEL','modal')); 41 elseif (cc.info.subfamily >= hex2dec('60')) & ... 42 (cc.info.subfamily <= hex2dec('6f')), 43 c5x = logical(0); 44 if cc.info.revfamily > 10, 45 target_subdir = 'c6x'; 46 outFile = 'rtdxtutorial_6x1x.out'; 47 else 48 target_subdir = 'c6x'; 49 outFile = 'rtdxtutorial_6x0x.out'; 50 end 51 notReady = 0; 52 else % Selected processor is not a C5xxx nor C6xxx 53 uiwait(msgbox({'RTDX is not supported for the selected board, '; 带格式的: 项目符号和编号

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 231: Matlab Simulink

从Matlab/Simulink模型到代码实现 216

54 'please select another board'},... 55 'Selection Error','modal')); 56 count = count+1; 57 if count<2, 58 clear cc; 59 [boardNum,procNum] = boardprocsel; 60 pause(0.1); 61 echo on; 62 cc=ccsdsp('boardnum',boardNum,'procnum',procNum); 63 echo off; 64 end 65 end 66 else % Selected processor is a Simulator 67 uiwait(msgbox({'RTDX is not supported for the Simulator, '; 68 'please select another board'},... 69 'Selection Error','modal')); 70 count = count+1; 71 if count<2, 72 clear cc; 73 [boardNum,procNum] = boardprocsel; 74 pause(0.1); 75 echo on; 76 cc=ccsdsp('boardnum',boardNum,'procnum',procNum); 77 echo off; 78 end 79 end 80 end 81 if ~exist('outFile'), 82 clear cc; 83 error('RTDX is not supported for the selected board. Exiting tutorial ...'); 84 end 85 %=================================================================== 86 87 % ===================== START OF DEMONSTRATION===================== 88 echo on; 89 90 % Specify target directory where target files reside 91 % target_subdir is dependent on processor type 92 target_dir = fullfile(matlabroot,'toolbox','tiddk','tidemos', 'rtdxtutorial',target_subdir); 93 94 % Go to target directory

删除的内容:

删除的内容: uiwait(msgbox({'RTDX is not supported for the selected board, ';

删除的内容:

删除的内容: =

删除的内容:

Page 232: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 217

95 cc.cd(target_dir); 96 97 % Display contents of target directory 98 cc.dir; 99 100 % make Code Composer IDE visible 101 cc.visible(1); 102 103 % LOAD .out file to target 104 cc.load(outFile); 105 106 %=================================================================== 107 echo off 108 disp('Hit any key to continue...'); 109 pause 110 echo on 111 112 % CONFIGURE channel buffers, 4 buffers of 1024 bytes each 113 cc.rtdx.configure(1024,4); 114 115 % OPEN write channel 116 cc.rtdx.open('ichan','w');

117

118 % OPEN read channel

119 cc.rtdx.open('ochan','r');

120

121 % ENABLE RTDX, and verify, for C54x

122 cc.rtdx.enable;

123 cc.rtdx.isenabled

124

125 %===================================================================

126 echo off

127 disp('Hit any key to continue...');

128 pause

129 echo on

130

131 % SET global timeout value, and verify

132 timeout = cc.rtdx.get('timeout')

133 cc.rtdx.set('timeout', 15) % set timeout to 15 seconds

134 timeout = cc.rtdx.get('timeout')

135

Page 233: Matlab Simulink

从Matlab/Simulink模型到代码实现 218

136 % test DISPLAY and DISP

137 cc.rtdx

138

139 % RESTART target

140 cc.restart;

141

142 % RUN target

143 cc.run;

144

145 %==================================================================

146 echo off

147 pause(3)

148 disp('Hit any key to continue...');

149 pause

150 echo on

151

152 % ENABLE write channel

153 cc.rtdx.enable('ichan');

154 cc.rtdx.isenabled('ichan')

155

156 % write to target DSP

157 if cc.rtdx.iswritable('ichan'),

158 disp('writing to target...') 159 indata=1:10 160 cc.rtdx.writemsg('ichan', int16(indata)) 161 end 162 163 %================================================================== 164 echo off 165 disp('Hit any key to continue...'); 166 pause 167 echo on 168 169 % Check enable status of read channel 170 cc.rtdx.isenabled('ochan') 171 172 % Query for number of available messages -- should be 0 173 num_of_msgs = cc.rtdx.msgcount('ochan') 174 175 % ENABLE read channel, and verify 176 cc.rtdx.enable('ochan');

写入一个消息,该消息 中包含 10个整数 1:10

删除的内容: 十

Page 234: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 219

177 cc.rtdx.isenabled('ochan') 178 179 % give time for target DSP to process data, 180 % and write results to channel buffer 181 pause(4); 182 183 %=================================================================== 184 echo off 185 disp('Hit any key to continue...'); 186 pause 187 echo on 188 189 % Query for number of available messages -- should be 20 190 num_of_msgs = cc.rtdx.msgcount('ochan') 191 192 % Read one message: 193 outdata = cc.rtdx.readmsg('ochan', 'int16') 194 195 % Read three messages into a cell array of three 1x10 vectors: 196 outdata = cc.rtdx.readmsg('ochan', 'int16', 3) 197 % Look at second matrix--de-reference cell array: 198 outdata{1,2} 199 200 %=================================================================== 201 echo off 202 disp('Hit any key to continue...'); 203 pause 204 echo on 205 206 % Read two messages into two 2x5 matrices: 207 outdata = cc.rtdx.readmsg('ochan', 'int16', [2 5], 2) 208 209 % Look at both matrices by de-referencing cell array: 210 outdata{1,:} 211 212 % Read one message into one 10x1 column vector: 213 outdata = cc.rtdx.readmsg('ochan', 'int16', [10 1]) 214 215 %=================================================================== 216 echo off 217 disp('Hit any key to continue...'); 218 pause

Page 235: Matlab Simulink

从Matlab/Simulink模型到代码实现 220

219 echo on 220 221 % READMAT 222 % Read into a 5x2 matrix: 223 outdata = cc.rtdx.readmat('ochan','int16', [5 2]) 224 225 % Query for remaining number of available messages in read channel queue... 226 num_of_msgs = cc.rtdx.msgcount('ochan') 227 228 % Read into a 4x5 matrix (= two messages): 229 outdata = cc.rtdx.readmat('ochan','int16', [4 5]) 230 231 % Check the remaining number of available messages in read channel queue. 232 % Note: Count has been decremented by two. 233 num_of_msgs = cc.rtdx.msgcount('ochan') 234 235 %=================================================================== 236 echo off 237 disp('Hit any key to continue...'); 238 pause 239 echo on 240 241 % Read into a 10x5 matrix (= five messages): 242 outdata = cc.rtdx.readmat('ochan','int16', [10 5]) 243 244 % Check the remaining number of available messages in read channel queue. 245 % Note: Count has been decremented by five. 246 num_of_msgs = cc.rtdx.msgcount('ochan') 247 248 %================================================================== 249 echo off 250 disp('Hit any key to continue...'); 251 pause 252 echo on 253 254 % FLUSH one message: 255 cc.rtdx.flush('ochan',1) 256 257 % Check the remaining number of available messages in read channel queue. 258 % Note: Count has been decremented by one. 259 num_of_msgs = cc.rtdx.msgcount('ochan') 260

删除的内容: % Query for remaining number of available messages in read channel queue...

删除的内容:

删除的内容:

删除的内容:

Page 236: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 221

261 % FLUSH all remaining messages: 262 cc.rtdx.flush('ochan','all') 263 264 % Check the remaining number of available messages in read channel queue. 265 % Note: COUNT has been reset to zero. 266 num_of_msgs = cc.rtdx.msgcount('ochan') 267 268 %=================================================================== 269 echo off 270 disp('Hit any key to continue...'); 271 pause 272 echo on 273 274 % DISABLE all open channels 275 cc.rtdx.disable('ALL'); 276 277 if cc.isrunning, % if the target DSP is running 278 cc.halt; % halt the processor 279 end 280 281 % DISABLE RTDX 282 cc.rtdx.disable; 283 284 % CLOSE channels 285 cc.rtdx.close('ichan'); 286 cc.rtdx.close('ochan'); 287 % or use: cc.rtdx.close('all'); 288 289 if cc.isvisible, 290 cc.visible(0); 291 end 292 293 clear cc; % Call destructors 294 echo off; 295 296 % ======================= END OF DEMONSTRATION===================== 297 298 % [EOF] linkforrtdxdemo.m

程序说明如下:

第 18 行,通过开发板和处理器选择对话框、选择目标板和目标处理器,返回板号和处理器号。本例假设选择了 C6701 EVM。

删除的内容:

Page 237: Matlab Simulink

从Matlab/Simulink模型到代码实现 222

第 20行,创建 MATLAB CCSDSP对象 cc,用于 MATLAB和所选目标板及目标处理器之间的连接,同时以后台方式运行 Code Composer Studio。Link for RTDX接口就是通过操作 cc.rtdx对象来实现的。Developer’s Kit for TI DSP提供了许多函数用来操作 Link for RTDX(cc.rtdx),如表 6.2所示。

第 23~80 行,判断所选的处理器是否兼容 RTDX。如果不兼容,清除创建的CCSDSP 对象,重新选择开发板和处理器,重新创建 CCSDSP 对象,再进行判断(仅重复 1 次);如果兼容,判断所选处理器属于 C5X 还是 C6X1X 或者C6X0X,选择对应的下载文件;如果既不是 C5X 也不是 C6X,则清除创建的CCSDSP 对象,重新选择开发板和处理器,重新创建 CCSDSP 对象,再进行判断(仅重复 1次)。

第 81~84行,如果所选的下载文件不存在,提示错误信息,退出演示程序。 第 90~104 行,将当前目录指向目标文件所在目录,调用 cc 的 visible 方法,让读者可以看到 Code Composer Studio 开发环境,同时向处理器下载目标文件(本例下 载 的 目 标 文 件 为 %MATLABROOT%\toolbox\tiddk\tidemos\rtdxtutorial\c6x\ rtdxtutorial_6x0x.out)。

第 112~123 行,配置 RTDX 通道缓存,打开读写通道(这里的读写通道是相对于Matlab而言的。在 Link for RTDX连接中,Matlab的写通道,其实是 TI DSP的读通道;Matlab 的写通道,其实是 TI DSP 的读通道)并且使能 RTDX 连接(对于C54X)。

第 131~134行,设定 Link for RTDX连接超时时间。 第 137行,显示有关 RTDX连接的信息。 第 139~143行,目标机复位,运行目标程序。 第 152~154行,使能写通道。 第 156~162行,通过 RTDX连接向目标 DSP写入 10个 16位整形数[1 2 3 4 5 6 7 8

9 10]。 第 169~170 行,检查读通道的使能状态,返回值应为 0,因为读通道还处于禁止 状态。

第 172~173行,返回读通道中的有效消息数,此时的有效消息数应该为 0。 第 175~177行,使能读通道。

表 6.2 用于操作 Link for RTDX的函数

函 数 重 载 描 述

address 返回一个符号对应的地址和内存页

clear 是 删除现存的 RTDX和 CCS IDE连接,用析构函数终结连接对象

close 关闭已打开的 RTDX通道

configure 定义 RTDX通道缓存的大小和数目

带格式的

删除的内容: ─

删除的内容: (仅重复 1次

删除的内容: );

删除的内容: (

删除的内容: 仅重复 1次)

删除的内容: ─

删除的内容: ─

删除的内容: (

删除的内容: 本例下载的目标文件为%MATLABROOT%\toolbox\tiddk\tidemos\rtdxtutorial\c6x\ rtdxtutorial_

删除的内容:

删除的内容: 6x0x.out)

删除的内容: ─

删除的内容: (

删除的内容: 这里的读写通道是相对于Matlab而言的。在Link for RTDX连接中,Matlab的写通道,其实是 TI DSP的读通道;Matlab的写通道,其实是 TI DSP的读通道)

删除的内容: (

删除的内容: 对于 C54X)

删除的内容: 此句没错!!

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

Page 238: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 223

续表

函 数 重 载 描 述

disable 禁用 RTDX 接口,一个指定的 RTDX 通道或者所有的 RTDX

通道

disp 是 显示 RTDX连接的属性

display 是 显示 RTDX连接的属性

enable 使能 RTDX 接口,一个指定的 RTDX 通道或者所有的 RTDX通道

flush 清洗指定的一个或者多个 RTDX通道中的数据或者消息

get 是 返回 RTDX连接的属性值

info 是 返回指定的 RTDX连接的信息

isenabled 判断 RTDX接口,一个或者多个 RTDX通道是否处于使能状态

isreadable 是 判断MATLAB能否读取指定的 RTDX通道

iswritable 是 判断MATLAB能否写入指定的 RTDX通道

msgcout 返回读使能的 RTDX通道中现存的消息数

open 打开一个连接到目标处理器的 RTDX通道

readmat 从指定的 RTDX通道读取一个数据矩阵

readmsg 从指定的 RTDX通道读取消息

set 是 设置 RTDX连接的属性

writemsg 向目标处理器写入一个消息

第 179~181行,让目标 DSP有充足的时间处理数据,并将结果写入 RTDX连接通道缓存。如果选择的是 C6701 EVM,目标 DSP上的运行的程序如下所示。

/* RTDX tutorial target application: read from host and echo back */ #include <rtdx.h> /* RTDX_Data_Read*/ #include <stdio.h> /* printf */ #include <target.h> /*TARGET_INITIALIZE*/ #define MAX 10 short recvd[MAX]; RTDX_CreateInputChannel(ichan); /* Channel to receive data from */ RTDX_CreateOutputChannel(ochan); /* Channel to use to write data */ void main( void ) { int i,j; TARGET_INITIALIZE(); /* target specific RTDX init */ while ( !RTDX_isInputEnabled(&ichan) ) {/* wait for channel enable from MATLAB */} RTDX_read( &ichan, recvd, sizeof(recvd) );

读取一个消息,该消息 中包含 10个整数 1:10

删除的内容: ─

删除的内容: (程序文本请和原文一致!!)

Page 239: Matlab Simulink

从Matlab/Simulink模型到代码实现 224

puts("\n\n Read Completed "); for (j=1; j<=20; j++) { for (i=0; i<MAX; i++) { recvd[i] +=1; } while ( !RTDX_isOutputEnabled(&ochan) ) { /* wait for channel enable from MATLAB */ } RTDX_write( &ochan, recvd, sizeof(recvd) ); while ( RTDX_writing != NULL ) { /* wait for data xfer INTERRUPT DRIVEN for C6000 */ } } while ( RTDX_isInputEnabled(&ichan) || RTDX_isOutputEnabled(&ochan)) { /* wait for channel disable from MATLAB */ } puts("\n\n Test Completed "); while (1) {} }

第 189~190行,返回读通道中的有效消息数,此时的有效消息数应该是 20。 第 192~193行,读取一个消息,通道中的消息是读一个少一个。

>>outdata = cc.rtdx.readmsg('ochan', 'int16') outdata = 2 3 4 5 6 7 8 9 10 11

第 195~198行,读取 3个消息。 >>outdata = cc.rtdx.readmsg('ochan', 'int16', 3) outdata = [1×10 int16] [1×10 int16] [1×10 int16] >>outdata{1,2} ans = 4 5 6 7 8 9 10 11 12 13

第 206~210行,读取两个消息。 >>outdata = cc.rtdx.readmsg('ochan', 'int16', [2 5],2) outdata = [2×5 int16] [2×5 int16]

执行完 181 行后,目标机上的程序应该在此循环

写入一个消息,每个 消息都是一个数组

共写入 20个消息

删除的内容: 。

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: 三

删除的内容: ─

Page 240: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 225

第 212~213行,读取一个消息。 >>outdata = cc.rtdx.readmsg('ochan', 'int16', [10 1]) outdata = 8 9 10 11 12 13 14 15 16 17

第 222~223行,读取一个 5×2的矩阵(相当于读取一个消息)。 >>outdata = cc.rtdx.readmat('ochan', 'int16', [5 2]) outdata = 9 14 10 15 11 16 12 17 13 18

第 225~226行,返回读通道中的有效消息数,此数应该为 12。 第 228~229行,读取一个 4×5的矩阵(相当于读取两个消息)。

>>outdata = cc.rtdx.readmat('ochan', 'int16',[4 5] ) outdata = 10 14 18 13 17 11 15 19 14 18 12 16 11 15 19 13 17 12 16 20

第 231~233行,返回读通道中的有效消息数,此数应该为 10。 第 241~242行,读取一个 10×5的矩阵(相当于读取五个消息)。

删除的内容: ─

删除的内容: ─

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: ─

删除的内容: ─

删除的内容: (

删除的内容: )

删除的内容: ─

删除的内容: ─

删除的内容: (

删除的内容: )

Page 241: Matlab Simulink

从Matlab/Simulink模型到代码实现 226

>>outdata = cc.rtdx.readmat('ochan', 'int16',[4 5] ) outdata = 12 13 14 15 16 13 14 15 16 17 14 15 16 17 18 15 16 17 18 19 16 17 18 19 20 17 18 19 20 21 18 19 20 21 22 19 20 21 22 23 20 21 22 23 24 21 22 23 24 25

第 244~246行,返回读通道中的有效消息数,此数应该为 5。 第 254~255行,废除读通道的一个消息。 第 257~259行,返回读通道中的有效消息数,此数应该为 4。 第 261~262行,废除所有的消息。 第 264~266行,返回读通道中的有效消息数,此数应该为 0。 第 274~275行,禁止所有打开的 RTDX通道。 第 277~279行,如果目标处理器正在运行,则挂起它。 第 281~282行,禁止 RTDX连接。 第 284~287行,关闭 RTDX连接读写通道。 第 289~291行,将 CCS IDE置于后台运行 第 293行,清除 CCSDSP对象,关闭在后台运行的 CCS IDE。如果 CCS IDE在前台运行,那么当清除 CCSDSP对象时,不会将其关闭。

6.5 从 Simulink模型生成面向 C6701 EVM 的工程文件

安装了 Developer’s Kit for TI DSP模块之后,在 Simulink Library Browser中会出现一个支持 C6701 EVM的模块库,如图 6.7所示。在搭建需要生成面向 C6701 EVM的工程文件的 Simulink模型时,可以选用该模块库中的模块。

删除的内容:

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

Page 242: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 227

图 6.7 C6701 EVM模块库

C6701 EVM ADC模块

这个模块用于采样和量化,给 C6701 EVM 板提供外部信源,如信号发生器、频率发生器和音频设备。将 C6701 EVM ADC 模块放在 Simulink 模型中可以让用户使用 C6701 EVM上的多媒体语音编码和解码模块(codec),用以将从 Line In或者 Mic In端口输入的模拟信号转换为数字信号,供 C6701 EVM上的 DSP TMS320C6701 处理。

C6701 EVM DAC模块

将 C6701 EVM DAC模块放在 Simulink模型中后,C6701 EVM 上的 codec模块会将接收到的处理后的数字信号转换成模拟信号向 LINE OUT端口输出。

C6701 EVM LED模块

Simulink模型中的 C6701 EVM LED模块可用于触发 C6701 EVM的外部状态指示灯(USER Status LED0)或者内部状态指示灯(User Status LED1)。

Reset C6701 EVM模块

双击 Simulink 模型中的 Reset C6701 EVM 模块,可将正在运行从该模型自动生成的可执行文件的 C6701 EVM复位。只要用户双击这个模块,它就运行一个 MS-DOS函数来复位 C6701 EVM上的处理器。程序停止运行,DSP TMS320C6701返回初始状态。

【例 21】用 C6701 EVM 来实现低通滤波,软硬件平台如图 6.8 所示,要用 C6701 EVM 实 现 的 模 型 如 图 6.9 所 示 : 两 个 正 弦 信 号 ( )ty 500π2sin2.01 ×= 和

( )ty 1000π2sin2.02 ×= 叠加后,通过一个低通滤波器,目的是要滤除 1000Hz 的高频信

删除的内容: 比

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 243: Matlab Simulink

从Matlab/Simulink模型到代码实现 228

号 , 假 定 采 样 频 率 为 16kHz 。 图 6.9 中 , 模 块 y1=0.2sin(2*pi*500*t) 、y2=0.2sin(2*pi*1000*t)和 Digital Filter Design的参数设置分别如图 6.10、图 6.11和图 6.12所示。

图 6.8 用 C6701 EVM来实现低通滤波的软硬件试验平台

图 6.9 低通滤波模型 lfilterwithsimulink.mdl

图 6.10 y1=0.2sin(2*pi*500*t)参数设置

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

删除的内容: 0.2sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: 500

删除的内容: *

删除的内容: *

删除的内容: t)

删除的内容: 0.2sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 1000

删除的内容: *

删除的内容: t)

删除的内容: 删除的内容: 这个有什么关

删除的内容:

删除的内容: 0.2sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 500

删除的内容: *

删除的内容: t)

... [217]

... [218]

... [219]

... [215]

... [216]

Page 244: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 229

图 6.11 y2=0.2sin(2*pi*500*t)参数设置

图 6.12 Digital Filter Design参数设置

带格式的

带格式的

删除的内容: 分页符

删除的内容: *pi

删除的内容: 0.2sin(2π

删除的内容: ×

删除的内容: *

删除的内容: 1000

删除的内容: *

删除的内容: t)

Page 245: Matlab Simulink

从Matlab/Simulink模型到代码实现 230

如图 6.13所示设置图 6.9中的模型 lfilterwithsimulink.mdl的仿真参数(其他参数使用默认值)。仿真结果如图 6.14所示:1000Hz的高频正弦信号被有效滤除了。

图 6.13 仿真参数设置

图 6.14 lfilterwithsimulink.mdl仿真结果

现在要用 C6701 EVM来实现图 6.9中的模型 lfilterwithsimulink.mdl,软硬件平台如图6.8所示。为了能用 C6701 EVM来实现该模型,有必要对模型 lfilterwithsimulink.mdl作修改。修改后的模型(lfilterwithc6701.mdl)如图 6.15 所示(当然还有其他的修改方案):图 6.15 中的 Digital Filter Design 模块参数和图 6.9 中的一模一样,两个正弦模块被一个C6701 EVM ADC 模块取代,参数设置如图 6.16 所示,图 6.9 中的 Scope 模块被 C6701 EVM DAC模块取代,参数设置如图 6.17所示,另外可以再添加一个 C6701 EVM RESET模块(该模块只是用于 C6701 EVM复位,不添加也可以,可以用其他方法让 C6701 EVM复位)。

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: ;

删除的内容: ;

删除的内容: (

删除的内容: )

Page 246: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 231

图 6.15 lfilterwithc6701.mdl

图 6.16 C6701 EVM ADC参数设置

图 6.17 C6701 EVM DAC参数设置

Page 247: Matlab Simulink

从Matlab/Simulink模型到代码实现 232

按如下步骤设置模型 lfilterwithc6701.mdl的仿真参数对话框。 步骤 1. 如图 6.18所示,设置求解器(Solver)选项卡,通过 Real-Time Workshop生

成目标代码时,无论是什么目标,求解器一定要是固定步长。

图 6.18 选择固定步长

步骤 2. 如图 6.19 所示,在 Real-Time Workshop 选项卡选择目标 Target for C6701 EVM。此时在选项卡 Real-Time Workshop 中有许多设置类别(Category),如图 6.20 所示,用户可以根据自己的实际情况做相关设置。

步骤 3. 如图 6.21所示,使用 Real-Time Workshop选项卡类别 TLC debugging的默认设置。

图 6.19 选择 Target for C6701 EVM

带格式的

带格式的

带格式的

删除的内容: :

删除的内容: )

删除的内容: (

删除的内容:

删除的内容: ,

删除的内容: (

删除的内容: )

删除的内容: 6.29

Page 248: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 233

图 6.20 Target for C6701 EVM 相关设置

图 6.21 TLC debugging设置

步骤 4. 如图 6.22所示,使用 Real-Time Workshop选项卡类别 General code generation options的默认设置。

图 6.22 General code generation options设置

带格式的

Page 249: Matlab Simulink

从Matlab/Simulink模型到代码实现 234

步骤 5. 如图 6.23所示,使用 Real-Time Workshop选项卡类别 General code generation options(cont.)的默认设置。

图 6.23 General code generation options(cont.)设置

步骤 6. 如图 6.24所示,使用 Real-Time Workshop选项卡类别MATLAB to CCS Link的默认设置。

步骤 7. 根据 C6701 EVM实际配置情况,选择 TI C6701 compiler选项。例如,选择字节顺序为 Little_Endian还是 Big_Endian,要和 C6701 EVM的配置一致,如图 6.25所示。

步骤 8. 如图 6.26所示,使用 Real-Time Workshop选项卡类别 TI C6701 linker的默认设置。

图 6.24 MATLAB to CCS Link设置

带格式的

带格式的

带格式的

带格式的

删除的内容:

删除的内容: (

删除的内容: (

删除的内容: cont. )

删除的内容: )

删除的内容: )

删除的内容: 6.23

删除的内容: ,

删除的内容: ,

删除的内容: 这

Page 250: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 235

图 6.25 TI C6701 compiler设置

图 6.26 TI C6701 linker 设置

步骤 9. 如图 6.27所示,使用 Real-Time Workshop选项卡类别 TI C6701 EVM runtime的默认设置(用户可能要根据 C6701 EVM 的实际配置情况更改设置),此时用鼠标单击Make Project按钮,就可将 Simulink模型自动生成 CCS IDE的工程文件,并自动调入 CCS IDE 中。图 6.28 所示就是由模型 lfiterwithc6701.mdl 生成的工程文件,该工程文件可在CCS IDE中编译下载运行。

如果想在生成工程文件后,自动地编译下载到 C6701 EVM上执行,请在图 6.27中将Options\Build action 选项选为 Build_and_execute。这时 Make Project 按钮会变成 Build & Run按钮,单击该按钮即可实现自动的编译下载并执行。这是在本例中采取的方式。

设置好 lfilterwithc6701.mdl 仿真参数对话框中的参数后,单击仿真参数对话框 Real-Time Workshop选项卡 Target configuation类别的 Build & Run按钮,开始 CCS IDE工程文件的生成并自动地编译下载运行。这时,在 CCS IDE 的输出窗口会出现 ISR 溢出的错误

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: ,

删除的内容: 我们

删除的内容: ,

Page 251: Matlab Simulink

从Matlab/Simulink模型到代码实现 236

提示。这是为什么呢?这是因为模型 lfilterwithc6701.mdl 中,Digital Filter Design 模块设计的滤波器阶数太高(如图 6.12 所示,135 阶),C6701 EVM 实现不了。这也说明了软件仿真通过的模型未必就一定能实现,因为要考虑硬件的支持能力。在此必须修改滤波器

的设计,降低它的阶数,将图 6.15中 Digital Filter Design模块对应的滤波器,设计为如图6.29所示(只需把设计方法从等波纹的 FIR设计改为切贝雪夫 I型设计)后,保存模型。然后,按下快捷键 Ctrl+B,重新生成工程文件并编译下载,程序开始在 C6701 EVM上正常运行(CCS IDE的输出窗口会显示程序开始运行)。

图 6.27 TI C6701 EVM runtime

图 6.28 由 lfilterwithc6701.mdl自动生成的 CCS IDE工程文件

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: 我们

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 接着,进行如下步骤。

Page 252: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 237

图 6.29 切贝雪夫 I型设计

步骤 10. 启动两个向声卡的 Line Out端口输出波形的波形发生器。如图 6.30所示设置参数。

>> daqfcngen

图 6.30 y=sin(2*pi*500*t)

波形发生器函数 daqfcngen 由数据采集工具箱提供,它位于%MATLABROOT%\ toolbox\daq\daqdemos\daqfcngen.m 中。daqfcngen 可以通过声卡的 Line Out 端口向外输出一个波形。如图 6.31所示设置波形发生器的参数,然后单击 Start按钮(单击之后 Start按钮变为 Stop按钮),目的是生成信号 y1=0.2sin(2*pi*500*t)。

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

删除的内容: *

删除的内容: *

删除的内容: sin(2

删除的内容: π

删除的内容: ×

删除的内容: pi

删除的内容: 500

删除的内容: *

删除的内容: t)

删除的内容: 6.29

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: 2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 500

删除的内容: *

删除的内容: t)

Page 253: Matlab Simulink

从Matlab/Simulink模型到代码实现 238

图 6.31 y1=0.2sin(2*pi*500*t)

再次使用命令 daqfcngen,启动另一个向声卡的 Line Out 端口输出波形的波形发生器,并且如图 6.32 所示设置参数,然后单击 Start按钮(单击之后 Start按钮变为 Stop按钮),目的是生成信号 y2=0.2sin(2*pi*1000*t)。

>>daqfcngen

图 6.32 y2=0.2sin(2*pi*1000*t)

由图 6.8所示的硬件连接方式可知,实际上我们已经向 C6701 EVM的 Line In端口输入了信号 y=y1+y2=0.2[sin(2*pi*500*t) + sin(2*pi*1000*t)],当然幅度会有变化,这取决于声卡的声量调节按钮。y就是待处理的信号,它经过了在 C6701 EVM上运行的图 6.15所示模型的处理(先经过 AD 变换,再低通滤波,然后再 DA 输出),滤波后的信号会向C6701 EVM 的 Line Out 端口输出。由图 6.8 所示的硬件连接方式,滤波后的信号会通过Line In端口向声卡输入。

步骤 11. 启动一个显示声卡的 Line In端口输入波形的示波器。

>> daqscope

示波器函数 daqscope由数据采集工具箱提供,它位于%MATLABROOT%\toolbox\daq\ daqdemos\daqscope.m中。daqscope可以显示声卡的 Line In端口的输入波形。单击图 6.33所示界面中的启动按钮,并且调节声卡的声量调节按钮,我们可以看到类似于图 6.34 的一个正弦波形,其频率是 500Hz(f=7.3×44100/644.714=499.34),证明 1000Hz 的正弦信号已被滤除。

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

删除的内容: 0.2sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 500

删除的内容: *

删除的内容: t)

删除的内容: 6.30

删除的内容: 那样

删除的内容: (⋯)

删除的内容: 0.2sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 1000

删除的内容: *

删除的内容: t)

删除的内容: 0.2sin(2×

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 1000×

删除的内容: *

删除的内容: t)

删除的内容: sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

删除的内容: 500

删除的内容: *

删除的内容: t)

删除的内容: sin(2

删除的内容: *

删除的内容: π

删除的内容: pi

删除的内容: ×

删除的内容: *

... [221]

... [222]

... [220]

... [224]

... [223]

... [225]

... [226]

Page 254: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 239

图 6.33 示波器

图 6.34 500Hz正弦信号

如果此时直接将声卡的 Line Out 和 Line In 连接,可以看到类似于图 6.35 所示的信号,它是 500Hz和 1000Hz两个正弦的叠加。

图 6.35 500Hz和 1000Hz两个正弦的叠加

删除的内容: 我们

Page 255: Matlab Simulink

从Matlab/Simulink模型到代码实现 240

>> which daqfcngen D:\MATLAB6p1\toolbox\daq\daqdemos\daqfcngen.m >> help daqfcngen DAQFCNGEN Example function generator for the Data Acquisition Toolbox. DAQFCNGEN creates a function generator window which can be used with the Data Acquisition Toolbox's analog output objects. The function generator window is divided into three sections. The top section contains a popup menu which displays the analog output objects that currently exist in the data acquisition engine. The selected analog output object's channels are listed in the listbox. The bottom section consists of a popup menu that has a list of the supported waveforms. These waveforms include sin, sinc, square, triangle, sawtooth, random, and chirp. Waveform-specific information such as frequency or amplitude can be entered for each waveform. If values are not entered, the default values displayed are used. The right section consists of three buttons which start/stop the selected analog output object, reset the function generator window to its original state and close the function generator window. The selected waveform can be sent to multiple channels of the same analog output object. Channels of the same object cannot be connected

to different waveforms. Information on DAQFCNGEN and the Data Acquisition Toolbox are available through the Help menu. The daqfcngen window can be closed either by selecting the File menu

and then selecting the Close Function Generator menu or by selecting the "x" close button. When the daqfcngen window is closed, the analog output object will be stopped, if it is running, and deleted. See also DAQSCOPE >> which daqscope D:\MATLAB6p1\toolbox\daq\daqdemos\daqscope.m >> help daqscope

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 256: Matlab Simulink

第 6章 面向 TI DSP的自动代码生成 241

DAQSCOPE Example oscilloscope for the Data Acquisition Toolbox. DAQSCOPE creates an oscilloscope window for displaying the incoming signals which can be used with the Data Acquisition Toolbox's analog input objects. DAQSCOPE can run any registered adaptor that has an analog input subsystem. The name of these adaptors and the adaptors' device identification number are displayed in the popup menu. This allows, for example, multiple nidaq cards to be distinguished from each other by their device identification number. The listbox beneath the popup menu contains a list of the channels that can be added to the selected adaptor. If all the channels were added to the analog input object, Channel1 would correspond to the first hardware channel that could be specified, Channel2 would correspond to the second hardware channel that could be specified and so on. A maximum of sixteen channels can

be selected and displayed. If more than sixteen channels are selected, a warning will occur and no channels will be displayed. An analog input object is created from the selected adaptor, adaptor device identification number and the selected channels. When the button with the triangle image is selected, the created analog input object is

started with the start command and the selected channels' signal will be displayed in the daqscope axes. While the analog input object is running, it is not possible to change the selected adaptor or the selected channels. However, by selecting the pause button (the same button as the start button - toggled), the channels and adaptor selected can be modified.

The time range or x-axis range can be modified while the object is running by moving the X-Axis range slider. The volts per division (or the y-axis range) can be modified while the object is running by entering a value in the Volts Per Division edit text box. The volts per division can be calculated internally by selecting the Autoset radiobutton to produce a usable display of the incoming signal. A legend can be added to the axes window to distinguish between the channel signals plotted by selecting the View menu and then selecting the Legend menu. Information on DAQSCOPE and the Data Acquisition Toolbox are available

through the Help menu.

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 257: Matlab Simulink

从Matlab/Simulink模型到代码实现 242

The daqscope window can be closed either by selecting the File menu and then selecting the Close Oscilloscope menu or by selecting the "x" close button. When the daqscope window is closed, the analog input object will be stopped, if it is running, and deleted. See also DAQFCNGEN.

Page 258: Matlab Simulink

第 7章 面向 Xilinx FPGA 的自动代码生成

为了加速在通信和多媒体领域的创新和研发,MathWorks公司和 Xilinx公司合作开发了基于 Simulink 的 FPGA 实现工具 System Generator for Simulink。通过这一工具,结合Simulink 和 Matlab,MathWorks 公司向用户提供了一个无缝的自上而下的 FGPA 解决方案。用户可以:

用 Simulink开发 DSP算法; 用 System Generator for Simulink自动将 Simulink模型转成面向 Xilinx FPGA的

VHDL代码; 使用 Xilinx公司提供的 IP核。

7.1 对传统 FPGA设计方式的挑战

传统的 FPGA设计方式如图 7.1所示。DSP的设计小组如果想用 FPGA来实现自己的设计,只能是先用 Simulink或其他工具搭建和仿真系统及算法,等仿真正确之后,将系统结构的设计方案提交给 FPGA 的设计工程师。FPGA 的设计工程师再手工地将系统模型用VHDL语言来描述,同时创建测试平台,用来验证自己的 FPGA实现方式和 Simulink系统级的仿真结果是否相符。在得到系统最优的 FPGA实现之前可能会有很多的反复。只有当FPGA 实现方式和 Simulink 系统级的仿真结果相符之后,FPGA 代码才可用来做综合和 实现。

图 7.1 传统的 FPGA设计方式

带格式的: 项目符号和编号

带格式的

删除的内容: 研发

删除的内容: w

删除的内容: <#><#>

删除的内容: <#>

删除的内容: <#>。

删除的内容: <#><#><#>用 System Generator for Simulink自动将 Simulink模型转成面向 Xilinx FPGA的VHDL代码;

删除的内容: <#>。

删除的内容: <#>

删除的内容: 删除的内容:

删除的内容: 可否能把图中“设计叠代”改为“设计迭

代”

Page 259: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 243

现在,有了 System Generator for Simulink 工具,DSP 的设计小组就可以用它从Simulink模型直接自动地生成经过优化的可综合的 FPGA实现代码。这样的设计流程大大地缩短了产品的开发时间,排除了以前可能而且经常出现的与 Simulink系统级的设计不相符的 FPGA实现。FPGA的这种实现方式如图 7.2所示。

图 7.2 System Generator for Simulink提供的 FPGA设计方式

7.2 Xilinx Blockset

System Generator for Simulink是由 Xilinx公司提供的产品,在 MATLAB的安装盘中没有,如果用户需要可以与 Xilinx公司的代理商联系。本书讲解的是 System Generator for Simulink V1.0(它只能在 MATLAB R12下使用,不过现在 Xilinx公司已经开发了能够用于MATLAB R12.1下的新版本)。关于如何安装请参考相关文档。这里要强调几点:

(1)安装和使用 System Generator for Simulink并不需要 Real-Time Workshop,但需要 Simulink。

(2)System Generator for Simulink一般用来开发需用 FPGA来实现的 DSP算法,目前它并不适于用来开发逻辑控制的 FPGA 实现和一个大系统的 FPGA 实现。换言之,System Generator for Simulink适宜用作算法 FPGA实现的开发工具。

为了搭建能够转化为 VHDL代码的 Simulink模型,System Generator for Simulink工具提供了一个基于 Simulink的模块库 Xilinx Blockset,如图 7.3所示。只有用这个模块库中的模块搭建的组件,才能通过 System Generator自动转成 VHDL代码。

删除的内容:

删除的内容: System Generator for Simulink

删除的内容: 它的

删除的内容: 想

删除的内容: 的

删除的内容:

删除的内容: 是

Page 260: Matlab Simulink

从Matlab/Simulink模型到代码实现 244

图 7.3 Xilinx Blockset

Xilinx Blockset提供的模块包括: Basic Elements(基本模块),如图 7.4所示。

图 7.4 Basic Elements(基本模块) DSP(滤波和 FFT模块),如图 7.5所示。

带格式的

删除的内容: (

删除的内容: )

删除的内容: 删除的内容: (

删除的内容: )

删除的内容:

删除的内容: 此图在原稿的Word文档中就是半黑状

删除的内容: (

删除的内容: )

Page 261: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 245

图 7.5 DSP(滤波和 FFT模块)

Math(数学模块),如图 7.6所示,

图 7.6 Math(数学模块)

Memory(内存模块),如图 7.7所示。 Matlab IO(接口模块),如图 7.8所示。

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 262: Matlab Simulink

从Matlab/Simulink模型到代码实现 246

图 7.7 Memory(内存模块)

图 7.8 Matlab IO(接口模块)

用于 FPGA设计的 Simulink模型基本框架如图 7.9所示。

删除的内容:

删除的内容: 删除的内容: (⋯)

删除的内容: 此图在原稿的Word文档中就是半黑状

删除的内容: (⋯)

... [1]

... [2]

Page 263: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 247

图 7.9 用于 FPGA设计的 Simulink模型

其中, 通常的 Simulink模块是指除 Xilinx Blockset模块之外的其他 Simulink 模块。 位于 Xilinx Blockset\Matlab IO中的 Gateway In和 Gateway Out模块提供了 FPGA设计(定点)和通常 Simulink模块(浮点)之间的接口功能:

将其他 Simulink 模块的双精度浮点数据转换成 Xilinx FPGA 需要的定点数据,或者相反;

如果在 System Generator参数设置对话框中选择了 Create Testbench(产生测试向量),生成 VHDL代码时可以将 Simulink仿真输入转换成 VHDL测试激励向量,将 Simulink 仿真输出转换成对应的 VHDL 测试输出向量。这些向量可用于所产生的 VHDL代码的行为仿真。

7.3 VHDL代码生成

现举一例说明用于 FPGA 设计的 Simulink 模型的创建和 VHDL 代码的自动生成 过程。

【例 22】图 7.10所示是两种实现 FIR滤波的 FPGA设计的比较,一种实现方法是直接利用 Xilinx Blockset提供的 FIR模块,另一种实现方法是用 Xilinx Blockset提供的基本模块来搭建 FIR的滤波实现。仿真的结果表明两种实现方法可以达到相同的效果。

图 7.10中模块 Din的参数设置如图 7.11所示;模块 FIR的参数设置如图 7.12所示;模块 Dout 的参数设置如图 7.13 所示;模块 Dout MAC 的参数设置如图 7.14 所示;模块MAC Based FIR是一个子系统,它的组成如图 7.15所示。

带格式的: 项目符号和编号

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 图 7.10 firandmac.mdl(这个图不宜太小,太小读者看不

清楚!!)

删除的内容: Xilinx Blockset提供的 FIR模块,

删除的内容:

删除的内容: 另一种实现方法是用 Xilinx Blockset提供的基本模块来搭建 FIR的滤波实现,仿真的结果表明两种

实现方法可以达到相同的效

果。

删除的内容:

删除的内容: ,

删除的内容: ,

删除的内容: ,

删除的内容: ,

Page 264: Matlab Simulink

从Matlab/Simulink模型到代码实现 248

图 7.10 firandmac.mdl

图 7.11 Din模块(Gateway In模块)参数设置 删除的内容: (

删除的内容: )

Page 265: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 249

图 7.12 FIR模块参数设置

图 7.13 Dout模块(Gateway Out模块)参数设置

图 7.14 Dout MAC模块(Gateway Out模块)参数设置

删除的内容: 分页符

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 266: Matlab Simulink

从Matlab/Simulink模型到代码实现 250

图 7.15 MAC Based FIR子系统

图 7.15中的 Controller模块和 MAC模块都是一个子系统,它们的组成分别如图 7.16和图 7.17所示。

图 7.16 Controller子系统

图 7.17 MAC子系统

删除的内容: 分页符

Page 267: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 251

对图 7.10 中所示模型 firandmac.mdl 进行 Simulink 仿真,结果如图 7.18 所示,其中[ ]0753coef = ,仿真参数的设置如图 7.19所示。

图 7.18 firandmac.mdl仿真结果

图 7.19 firandmac.mdl仿真参数设置

要将模型 firandmac.mdl中的 FPGA设计自动生成 VHDL代码,必须在 FPGA设计的同一层次上添加一个 System Generator 模块,如图 7.10 所示,该模块位于 Xilinx Blockset/Basic Elements 中,用来生成面向 Xilinx FPGA 的 VHDL 代码。用鼠标双击图7.10中的 System Generator模块,会弹出类似于图 7.20所示的对话框。

删除的内容: ,

Page 268: Matlab Simulink

从Matlab/Simulink模型到代码实现 252

图 7.20 System Generator参数设置

图 7.20中各个设置项目的可选项如下:

Xilinx Product Family

System Generator for Simulink V1.0工具支持的 Xilinx FPGA系列包括: Virtex Spartan-II

Target Directory

生成代码所在的目标目录,任何有效的目录名称都可,如果目录不存在,生成代码的

过程中会提示用户创建该目录。

Create Testbench

选择该项表示在生成 VHDL代码的过程中,同时生成对应的测试向量。

Override with Doubles

通常的 Simulink 模块使用的是双精度浮点信号,当这些信号通过 Xilinx Blockset\Matlab IO\Gateway In 模块进入 Simulink 模型的 FPGA 设计部分时,它们被转换成定点信号,进行定点的 FPGA处理,然后通过 Xilinx Blockset\Matlab IO\Gateway Out模块从 FPGA设计部分输出,信号又转换成通常的 Simulink模块使用的双精度浮点信号。默认方式下,带有 FPGA设计的 Simulink模型的仿真正是按照上述方式进行的。而 Override with Doubles设置项,允许用户以双精度浮点的方式仿真整个 Simulink模型。

删除的内容: /

删除的内容: /

删除的内容: /

删除的内容: /

Page 269: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 253

这个选项在选择定点宽度,或者用定点方式仿真 FPGA 设计没有得到期望的结果时非常有用。如果用户使用定点仿真的结果不正确,用户可以选择以双精度浮点的方式仿

真整个系统或特定的某些模块,这将有助于用户发现 FPGA 设计的哪一部分存在量化 错误。

用户很容易区分 FPGA设计中的哪些模块被设置为 override with doubles,因为当它被设置时,受影响的 Xilinx模块会显示为灰色,而不是显示为正常的蓝色或者黄色。

According to Block Masks 进行 Simulink仿真时,FPGA设计部分根据模块的屏蔽情况,使用双精度浮点信号取

代定点信号。 Everywhere in Subsystem 进行 Simulink 仿真时,FPGA 设计部分在子系统中使用双精度浮点信号取代定点

信号。 Nowhere in Subsystem 进行 Simulink 仿真时,FPGA 设计部分在子系统中不使用双精度浮点信号取代定点

信号。

Generate Cores

选择在生成 VHDL代码的过程中,是否生成 Xilinx LogiCOREs。 According to Block Masks 根据模块的屏蔽情况生成 Xilinx LogiCOREs。

Everywhere Available 在任何可能的地方,都生成 Xilinx LogiCOREs。

Nowhere 不生成 Xilinx LogiCOREs。 所谓模块的屏蔽(Block Masks)指的是,当在模型的 FPGA 设计部分不同的层次上

都有 System Generator 模块时(这种情况是允许的),例如对于本例,图 7.15 所示的MAC Based FIR子系统和图 7.17所示的 MAC子系统都可以有自己的 System Generator模块,当这些 System Generator模块的 Override with Doubles及 Generate Cores设置和图 7.10中的 System Generator 模块不同时,如果层次较高的 System Generator 模块的设置为According to Block Masks,层次较低的 System Generator模块的设置将起作用。

设置好 System Generator的参数之后,单击 Generate按钮开始生成 VHDL代码。如果目标目录不存在,会提示创建该目录。生成代码要花一段时间(生成代码的过程中会将模

型再仿真一遍),屏幕上会显示进度条。代码生成之后,会弹出如图 7.21 所示的信 息框。

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 点

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: 完成

Page 270: Matlab Simulink

从Matlab/Simulink模型到代码实现 254

图 7.21 代码生成完成

如果像图 7.20所示那样设置参数,对应于模型 firandmac.mdl中的 FPGA设计部分,在目录 c:\temp\firandmac中生成的 VHDL相关文件如下:

makeproj vhdlFiles xlcounter_core1.asy xlspram_core1.asy xlfir_core1.asy xlmult_core1.asy xlsprom_core1.asy vcomscr.bat firandmac_FIR.coe firandmac_Dout.dat firandmac_Din.dat firandmac_Dout_MAC.dat vsim.do vcom.do xlfir_core1.edn xlmult_core1.edn xlcounter_core1.edn xlspram_core1.edn xlsprom_core1.edn coregen.log sysgen.log firandmac_MAC_Based_FIR_Circular_Data_Buffer.mif xlfir_core1.mif firandmac_MAC_Based_FIR_Coef_LUT.mif firandmac_FIR.mif coregen.prj firandmac_MAC_Based_FIR_MAC.vhd firandmac_MAC_Based_FIR_Controller.vhd firandmac_testbench.vhd firandmac.vhd xlcounter.vhd firandmac_MAC_Based_FIR.vhd

删除的内容: 象

Page 271: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 255

xlfir.vhd xlfir_core1.vhd const_pkg.vhd clock_driver.vhd xlmult.vhd xlcounter_core1.vhd xlspram_core1.vhd xlmult_core1.vhd xlsprom_core1.vhd xlrelational.vhd xlspram.vhd xlsprom.vhd xlfir_core1.vho xlspram_core1.vho xlcounter_core1.vho xlmult_core1.vho xlsprom_core1.vho xlfir_core1.xco sysgen.xco xlmult_core1.xco xlcounter_core1.xco xlsprom_core1.xco xlspram_core1.xco

文件 vhdlFiles的内容类似于下文,它是综合时需要的文件的列表。 const_pkg.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/conv_pkg.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_reg.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_reg_w_init.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_valid_pipe.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_mult.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlshutter.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xldelay.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlfromfile.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlregister.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlclockdriver.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xldsamp.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlconstant.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xltofile.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlusamp.vhd C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xladdsub.vhd

删除的内容: 图 7.17

Page 272: Matlab Simulink

从Matlab/Simulink模型到代码实现 256

C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlclk.vhd clock_driver.vhd xlspram_core1.vhd xlcounter_core1.vhd xlmult_core1.vhd xlfir_core1.vhd xlsprom_core1.vhd xlcounter.vhd xlspram.vhd xlfir.vhd xlsprom.vhd xlrelational.vhd xlmult.vhd firandmac_MAC_Based_FIR_MAC.vhd firandmac_MAC_Based_FIR_Controller.vhd firandmac_MAC_Based_FIR.vhd firandmac.vhd firandmac_testbench.vhd

如果只是想将MAC Based FIR子系统生成 VHDL代码,请在该子系统中,即图 7.15所示界面中添加一个 System Generator模块,再通过该 System Generator模块生成代码即可。

7.4 浮点仿真与定点仿真

对于 Simulink仿真,通常的 Simulink模型都是浮点仿真(Fixed-Point Blockset搭建的模块除外)。带有 FPGA 设计的 Simulink 模型,默认方式下,FPGA 设计部分是定点仿真,通常 Simulink模块部分是浮点仿真(Fixed-Point Blockset搭建的模块除外)。通过设置 System Generator的 Override with Doubles设置项,用户可以选择让 FPGA设计的整个部分或者其中的某一部分在作 Simulink仿真时使用浮点仿真,用以帮助用户定位某些模块中的量化错误。

7.5 未 来 之 路

MathWorks公司和 Xilinx公司一直致力于提高工程师的工作效率,为此两家公司都做了大量的工作。相对于 C 语言等高级语言编程,MathWorks 公司的 Simulink 系列工具缩

删除的内容: 7.10

删除的内容: ,

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: 做

删除的内容: 都

Page 273: Matlab Simulink

第 7章 面向 Xilinx FPGA的自动代码生成 257

短了系统设计的时间,Xilinx 公司的 System Generator for Simulink 缩短了从系统设计到FPGA实现的时间,并且可以使用 Xilinx公司经过优化的 IP核。如图 7.22所示。

图 7.22 Simulink+System Generator的优势

System Generator和 Simulink集成的结果是给用户提供了一个完整的 DSP解决方案: Simulink from The MathWorks +

Xilinx System Generator for Simulink + Xilinx Platform FPGA

同时也提供了一体化的设计流程(如图 7.2 所示),它极大地降低了发生错误的风险(错误可以在系统设计的早期被发现),生成了经过优化的 FPGA实现代码,缩短了基于FPGA的 DSP应用产品从开发到上市的时间。在未来的时间里,为了给用户提供对更高性能 DSP FPGA实现的支持,MathWorks公司和 Xilinx公司将会加强类似的合作。实际上,现在 Altera公司也提供了一个类似于 System Generator for Simulink的,基于 Simulink的FPGA代码自动生成工具包 DSPBuilder。

带格式的

删除的内容: 和

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 、

Page 274: Matlab Simulink

第 8章 面向 VxWorks 的代码生成

8.1 VxWorks/Tornado

对于程序开发和许多交互式应用来说,UNIX和 Windows可以算是优秀的操作系统。然而,它们都不适于实时应用。Tornado 是美国 WindRiver 公司为用户提供的嵌入式开发平台,VxWorks是 Tornado的运行期组件,也是嵌入式行业应用最广泛的实时操作系统。VxWorks 拥有超过 1800 个功能强大的 API(应用程序接口),具有很强的可裁剪性,适应于从最简单到最复杂的产品设计。VxWorks RTOS 的内核能力由 Wind 微核提供,同时具有先进的网络支持、强大的文件系统和 I/O 管理以及 C++等其他标准运行期支持。VxWorks的内核能力能与 WindRiver公司和基于 Tornado的第三方开发厂商提供的 300多个附加组件共同使用。MathWorks 公司也提供了从 Simulink 模型到 VxWorks 应用代码的自动转换接口 Tornado (VxWorks) Real-Time Target。Tornado 除了包含 VxWorks 组件外,还包括一整套内核和可选的交叉开发工具及实用程序,以及与主机的各种通信连接方

式。若想知道有关 VxWorks/Tornado 的详情,请登录 WindRiver 公司的网站http://www.windriver.com 查询。

8.2 Simulink VxWorks支持库

Tornado (VxWorks) Real-Time Target 接口包含在 MATLAB 产品的 Real-Time Workshop模块中。安装了 Real-Time Workshop模块后,在 Simulink Library Browser中会出现 Real-Time Workshop\VxWorks Support模块库,如图 8.1所示,这些模块可帮助用户搭建面向目标 Tornado (VxWorks) Real-Time Target的 Simulink模型。

VxWorks支持库的第一个子库 Asynchronous Support库,如图 8.2所示,它支持: 中断控制 速率转换 异步缓存读取 任务间同步 异步缓存写入

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: (

删除的内容: )

Page 275: Matlab Simulink

第 8章 面向 VxWorks的代码生成 259

图 8.1 VxWorks支持库

图 8.2 Asynchronous Support库

VxWorks支持库的第二个子库 IO Devices库,如图 8.3所示,包含对如下驱动程序的支持:

Matrix MS-AD12 Matrix MS-DA12 VME Microsystems VMIVM-3115-1 Xycom XVME-500/590 Xycom XVME-505/595

Page 276: Matlab Simulink

从Matlab/Simulink模型到代码实现 260

图 8.3 IO Devices库

8.3 Tornado (VxWorks) Real-Time Target运行结构

开发 VxWorks 实时应用系统的一个典型的配置,如图 8.4 所示。它通常包括运行Matlab、Simulink和 Real-Time Workshop的 UNIX/PC主机,运行 VxWorks的目标时,两者之间通过 Ethernet 连接。另外,在目标机上可能还有带有 A/D、D/A 转换的 IO 板,用以和外部的硬件通信。

图 8.4 VxWorks实时应用开发的典型配置

实时代码在 UNIX/PC 主机上,用 Torando 提供的交叉编译器编译。通过 Real-Time Workshop\Tornado(VxWorks)Real-Time Target 生成的目标文件(model.lo),可通过Tornado集成开发环境的命令 shell Windsh下载到 VxWorks目标机。实时程序在 VxWorks目标机上执行,通过 IO设备和外部硬件交换数据,并且保持和主机之间的相互通信。

实时程序运行在 VxWorks目标机上,而 Simulink和 StethoScope运行在相同或者不同的主机上。Simulink 和 StethoScope 都需要 VxWorks 目标机上运行的任务来处理通信过程。Tornado(VxWorks)Real-Time Target生成如下 VxWorks任务:一个用于和 Simulink通信,其他用于完成模型功能。对 StethoScope 的支持会另外生成和它进行通信的任务。Tornado(VxWorks)Real-Time Target的运行结构如图 8.5所示。

删除的内容: (没办法!,你可以用 Visio画一个)

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: 的

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

Page 277: Matlab Simulink

第 8章 面向 VxWorks的代码生成 261

图 8.5 (VxWorks) Real-Time Target的运行结构

StethoScope是 MATLAB的第三方厂商 Real-Time Innovations, Inc.提供的一个实时的数据采集、性能分析图形化工具,可用它来观测 Real-Time Workshop\Tornado (VxWorks) Real-Time Target目标程序变量的实时变化。StethoScope可用于:

数据的实时采集和显示; 观测变量的实时变化; 采集、存储和归档数据供以后分析; 以MATLAB格式输出数据; 测量和改善实时 VxWorks程序的性能。

主机进程

主机上也有两个进程用于和目标机上的实时程序通信(如图 8.5所示): 运行于外部模式的 Simulink 当 Simulink 运行于外部模式时,用户可以修改模块参数,Simulink 会调用外部接口

MEX-文件(例如在 Windows 平台上通常是 ext_com.dll),将新参数下载到 VxWorks 目标机中。

StethoScope用户接口模块 这个模块和运行在 VxWorks目标机上的 StethoScope实时模块通信,用以获取模型的

数据信息。

目标机上的 VxWorks任务

对于多采样速率模型,用户可以以单任务模式或者多任务模式生成实时程序(对于单

采样率模型,则只能生成单任务模式的实时程序),这可通过仿真参数设置对话框的

删除的内容: (

删除的内容: )

删除的内容: (你自己想办法!)

删除的内容:

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 278: Matlab Simulink

从Matlab/Simulink模型到代码实现 262

Solver选项卡的模式设置来选择,如图 8.6所示。

图 8.6 模式选择

两种模式需要的主程序代码都在文件%MATLABROOT%\rtw\c\tornado\rt_main.c 中。Tornado(VxWorks)Real-Time Target在生成代码的过程中,会编译和连接 rt_main.c文件代码。

单任务 默认方式下,模型运行在单任务 tSingleRate模式。这种方式可以提供最佳的性能。任

务 tSingleRate以模型的基采样速率(最高采样速率)运行,同时执行那些低采样模块需要的代码。任务 tSingleRate 的执行通常被一个 VxWorks semTake 调用阻塞,直到时钟中断发生,中断服务程序调用 semGive,才能导致 semTake 调用返回。一旦使能,任务tSingleRate执行一个时间步的模型代码,然后循环等待对 semTake的再一次调用。默认方式下,任务 tSingleRate运行在一个相对较高的优先级(30),这样可以不被后台系统任务所中断。

多任务 用户也可以选择让模型运行在多任务模式下,一个任务对应模型的一种采样速率(如

图 8.5所示): tBaseRate ——这个任务运行对应基速率(最高采样速率)的模型组件代码。默认方式下,它运行在较高的优先级(30),不被后台系统任务所 中断。

tRaten ——模型中其他的(基速率除外)每一种采样速率都对应一个独立的任务,分别命名为 tRate1、tRate2、⋯⋯、tRaten,它们对应的采样速率依次减慢,优先级也依次降低一级。tRate1 优先级最高,tRaten 的优先级最低(当然 tRate1的优先级比 tBaseRate低)。

带格式的

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: ,

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: —

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: 以

删除的内容: —

删除的内容: (

删除的内容: )

Page 279: Matlab Simulink

第 8章 面向 VxWorks的代码生成 263

用于和主机通信的任务 如果在生成 Tornado(VxWorks)Real-Time Target目标代码时,用户选择了外部模式

和支持 StethoScope,生成的代码中会创建如下几个任务(如图 8.5所示): tExtern —— 这个任务实现外部模式主-目标机连接的服务器端,它接收从

Simulink 传来的新参数让实时程序处理。tExtern 等待从 Simulink 中发来的消息,当消息到来时,tExtern 提取消息的内容,修改指定的参数。tExtern运行在比任务 tRaten(具有最低优先级的模型任务)更低的优先级上,任务tExtern的源代码位于文件%MATLABROOT%\rtw\c\src\ext_svr.c中。

tScopeDaemon and tScopeLink —— StethoScop 提供的自己的 VxWorks 任务用于实时数据的采集和显示。在单任务模式中,任务 tSingleRate 采集数据;在多任务模式中,任务 tBaseRate 采集数据。两者都是在基任务中采集数据。只有在模型运行空闲时,StethoScope 任务才将数据发送到主机上进行显示。

8.4 Tornado(VxWorks)Real-Time Target 的实现过程

为了通过 Real-Time Workshop实现和运行一个基于 VxWorks的实时程序,用户可按如下步骤进行:

(1)根据特定的应用,设计 Simulink模型; (2)如果需要的话,在 Simulink模型中添加适当的设备驱动程序模块; (3)针对实际情况,配置模板 makefile文件 tornado.tmf; (4)建立运行 Simulink的主机和 VxWorks目标机之间的 Ethernet连接(Simulink主

机和 VxWorks 目标机之间的连接可以不是 Ethernet 连接,只不过这时无法使用 Simulink的外部模式方式,而且要手工下载模型代码);

(5)通过模型参数设置对话框中的 Real-Time Workshop 选项卡,选择 Tornado (VxWorks)Real-Time Target目标,生成 VxWorks应用代码和相应的 makefile文件,激活 make命令编译连接生成的代码,然后下载并激活模型任务。

图 8.7显示了如图 8.8所示的 F-14飞控系统模型 f14.mdl所需的 Real-Time Workshop Tornado运行接口模块和产生的代码。图 8.7说明了用于创建一个 VxWorks实时应用程序需要的代码模块。虚线框表示可选的模块。

针对特定应用设计 Simulink模型

请用户使用 Simulink和各种模块库为特定的应用搭建 Simulink模型。

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: —

删除的内容: —

删除的内容: ,

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容:

Page 280: Matlab Simulink

从Matlab/Simulink模型到代码实现 264

添加设备驱动模块

运行在 VxWorks目标机上的实时程序,通过设备驱动程序和 IO设备交换数据。这些设备驱动程序包含特定 IO 设备的接口代码。为了让设备驱动程序便于用户使用,它们以Simulink C代码 S-函数的方式实现,这意味着用户只需像使用其他模块一样,将它们连接到系统模型。Real-Time Workshop代码生成器在生成的代码中会自动包括对这些模块 C代码的调用。用户也可以通过编辑 TLC 文件内嵌自己的 S-函数,内嵌可以提高代码的效率。在一个模型中,用户可以有若干个设备驱动模块的实例。如果用户想用 C 代码 S-函数创建特定 IO 设备的驱动程序,请参阅 MATLAB Document 安装盘上的 PDF 文档rtw_ug.pdf的 Targeting Real-Time Systems一章。

图 8.7 创建 VxWorks实时程序需要的源代码模块

配置模板 makefile文件

配置VxWorks模板makefile文件 tornado.tmf,是为了告知Real-Time Workshop有关VxWorks 使用的信息。以下是用户必须修改的 tornado.tmf 项目信息。

带格式的

删除的内容:

删除的内容:

Page 281: Matlab Simulink

第 8章 面向 VxWorks的代码生成 265

图 8.8 F-14飞控系统模型%MATLABROOT%\toolbox\simulink\simdemos\aerospace\f14.mdl

VxWorks配置 用户必须给定目标机和目标机 CPU 的类型,目标类型用于选择适当的交叉编译器和

连接器,CPU类型用于定义宏 CPU,许多 VxWorks头文件需要使用这些宏定义。关于如何正确给定目标机和目标机 CPU 的类型,请参阅 VxWorks 相关文档。目标机和目标机CPU的类型信息在 tornado.tmf中给定,由

#-------------- VxWorks Configuration -------------- 标识。请按实际情况修改如下几行: VX_TARGET_TYPE = 68k CPU_TYPE = MC68040

自动下载配置 为了在编译的过程中完成自动下载的功能,必须正确指定目标名和 Tornado Target

Server主机名。请根据实际情况修改如下的宏定义: #-------------- Macros for Downloading to Target-------------- TARGET = targetname

删除的内容: ,

Page 282: Matlab Simulink

从Matlab/Simulink模型到代码实现 266

TGTSVR_HOST = hostname

工具位置 为了定位在编译过程中需要使用的 Tornado 工具程序,必须在环境变量或者模板

makefile文件 tornado.tmf中指定如下 3个宏: #-------------- Tool Locations -------------- WIND_BASE = c:/Tornado WIND_HOST_TYPE = x86–win32 WIND_REGISTRY = $(COMPUTERNAME)

请根据实际情况进行修改。

程序的生成、编译、连接和下载

如果用户已经搭建了 Simulink模型,并且添加了适当的设备驱动模块,配置好了模板makefile文件,那么用户就可以设置编译连接选项,激活编译连接过程。

指定编译连接选项 使用模型仿真参数设置对话框的 Solver 选项卡(如图 8.9 所示)和 Real-Time

Workshop选项卡(如图 8.10所示),指定编译连接选项。

图 8.9 仿真参数 Solver设置

请在 Solver 选项卡中将求解器类型选择为 Fixed-step,并选择适当的积分算法。如果模型只有离散状态,请将积分算法选择为 discrete (no continuous status),这样可以加快程序的执行速度。

删除的内容: 三

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 283: Matlab Simulink

第 8章 面向 VxWorks的代码生成 267

在 Real-Time Workshop 选项卡选择 Target configuration 设置类别,然后单击Browse…按钮,打开 System Target File Browser窗口,如图 8.11所示。

图 8.10 仿真参数 Real-Time Workshop设置

图 8.11 System Target File Browser

在图 8.11 中,选择 Tornado (VxWorks) Real-Time Target 目标,然后单击 OK 按钮。这样就正确设置了 Target configuration设置类别:

System target file — tornado.tlc Template makefile — tornado.tmf,请根据 8.4节配置模板 makefile文件中的要求修改 tornado.tmf文件

Make command — make_rtw 代码生成选项

删除的内容: 分页符

删除的内容: (

删除的内容: )

Page 284: Matlab Simulink

从Matlab/Simulink模型到代码实现 268

为了设置 Tornado(VxWorks)Real-Time Target的代码生成选项,请打开模型仿真参数设置对话框的 Real-Time Workshop选项卡,并且选择 Tornado code generation options设置类别,如图 8.12所示。

图 8.12 Tornado code generation options

Real-Time Workshop提供了一些标志和开关项用于设置模板配置文件中的某些宏,由此配置编译连接过程。有关 Tornado(VxWorks)Real-Time Target的标志和开关项如下:

MAT-file logging:选择该项将在程序运行的过程中使能数据日志功能。程序运行结束时会创建一个名称为 model.mat 的文件,它包含用户在模型参数设置对话框的 Workspace I/O 选项卡指定的变量,Real-Time Workshop 可对这些变量名添加一个前缀或者后缀,MAT-file variable name modifier选项让用户选择是否添加前缀或者后缀。默认情况下,该文件保存在 VxWorks 默认文件设备的根目录中,典型的是 VxWorks 从其启动的主机文件系统。如果文件设备或者文件名不是默认情况,请在 Make command中添加 OPTS="-DSAVEFILE=filename" ,例如

make_rtw OPTS="-DSAVEFILE=filename" External mode:选择该项可让生成的实时程序支持 Simulink的外部模式。只要在Make command中添加 OPTS="-DVERBOSE" ,用户还可以使能外部模式的 verbose 方式,使得参数的下载信息能够显示在 VxWorks 的控制台窗口。

Code format:选择 RealTime或者 RealTimeMalloc代码格式。 StethoScope:选择该项,使得生成的执行代码支持主机上的 StethoScope。 Download to VxWorks target:选择该项,启动代码的自动下载。

激活编译连接过程 单击模型参数对话框 Real-Time Workshop 选项卡 Target Configuration 设置类别中的

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: :

删除的内容: :

Page 285: Matlab Simulink

第 8章 面向 VxWorks的代码生成 269

Build按钮(不要选择 Generate code only,否则 Build按钮会变为 Generate code按钮,单击后只生成代码和对应的 makefile 文件), 启动编译连接过程。生成的代码被交叉编译连接,生成相应的目标文件 model.lo(lo:loadable object)。

如果选择了自动下载功能(Download to VxWorks target),Target Server 将被启动,目标文件被自动下载到目标机中并开始运行(为了成功地自动下载

到目标机运行,可能还需要修改 perl 语言文件%MATLABROOT%\rtw\c\ tornado\downld.pl)。

如果选择了支持 StethoScope(StethoScope),支持 StethoScope 需要的目标文件 libxdr.so、libutilstssip.so和 libscope.so将自动下载到 VxWorks目标机,此时用户可以启动主机上的 StethoScope。

手动下载和运行可执行文件

如果在生成 Tornado(VxWorks)Real-Time Target目标代码时,没有选择自动下载功能,用户就必须使用 Tornado工具手工完成下载和运行的过程。这需要做如下工作:

建立主机和 VxWorks目标机之间的通信连接 在完成对模型的编译连接过程之后,用户可以启动主机和 VxWorks 目标机之间的连

接,即启动主机上 Target Server和 VxWorks目标机上的 Target Agent之间的通信连接。这可在 Tornado 集成开发环境中实现,也可在 DOS 命令窗口实现。如在 DOS 命令窗口实现,请使用如下命令行:

tgtsvr target_network_name

将目标文件从主机下载到 VxWorks目标机 在 Tornado 集成开发环境或者 DOS 命令窗口中启动 Tornado 工具 WindSh,再在

WindSh窗口执行如下命令: ld <model.lo

当然,如果在编译连接的过程中选择了支持 StethoScope ,用户还需要下载支持StethoScope需要的目标文件 libxdr.so、libutilstssip.so和 libscope.so。

运行程序 VxWorks 实时程序定义了一个函数 rt_main(),用来创建执行模型代码、完成与

Simulink 的通信(如果选择了外部模式方式)及初始化 StethoScope(如果选择了支持StethoScope)的任务。 rt_main 函数在文件 rt_main.c 中定义,这个文件位于目录%MATLABROOT%\rtw\c\tornado中。

/* Function: rt_main =========================================================== * Abstract:

带格式的

带格式的: 项目符号和编号

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: %

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容:

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: /* Function: rt_main =================================================== * Abstract: * Initialize the Simulink model pointed to by "model_name" and start * model execution. * * This routine spawns a task to execute the passed model. It will * optionally initialize StethoScope (via ScopeInitServer), if it * hasn't already been done. It also optionally sets up external mode * communications channels to Simulink. * * Parameters: ... [1]

Page 286: Matlab Simulink

从Matlab/Simulink模型到代码实现 270

* Initialize the Simulink model pointed to by "model_name" and start * model execution. * * This routine spawns a task to execute the passed model. It will * optionally initialize StethoScope (via ScopeInitServer), if it hasn't * already been done. It also optionally sets up external mode * communications channels to Simulink. * * Parameters: * * "model_name" is the entry point for the Simulink-generated code * and is the same as the Simulink block diagram model name. * * "optStr" is an option string of the form: * -option1 val1 -option2 val2 -option3 * * for example, "-tf 20 -w" instructs the target program to use a stop time * of 20 and to wait (in external mode) for a message from Simulink * before starting the "simulation". Note that -tf inf sets the stop time to * infinity. * * "scopeInstallString" determines which signals will be installed to * StethoScope. If scopeInstallString is NULL (the default) no signals * are installed. If it is "*", then all signals are installed. If it * is "[A-Z]*", signals coming from blocks whose names start with capital * letters will be installed. If it is any other string, then signals * starting with that string are installed. * * "scopeFullNames" parameter determines how signals are named: if * 0, the block names are used, if 1, then the full hierarchical * name is used. * * "priority" is the priority at which the model's highest priority task * will run. Other model tasks will run at successively lower priorities * (i.e., high priority numbers). * * Example: * To run the equalizer example from windsh, with printing of external mode * information, use: * * sp(rt_main,vx_equal,"0.0", "*", 0, 30) *

Page 287: Matlab Simulink

第 8章 面向 VxWorks的代码生成 271

* Returns: * EXIT_SUCCESS on success. * EXIT_FAILURE on failure. */ int_T rt_main( SimStruct * (*model_name)(void), char_T *optStr, char_T *scopeInstallString, int_T scopeFullNames, int_T priority, int_T port) { const char *status; int_T VxWorksTIDs[NUMST]; int optStrLen = strlen(optStr); SEM_ID rtClockSem = NULL; int_T parseError = FALSE; double finaltime = -2.0; int argc = 0; char_T **argv = NULL; #ifdef MULTITASKING SEM_ID rtTaskSemaphoreList[NUMST]; int_T i; #endif #ifdef EXT_MODE int_T extern_msg_tid; int_T extern_upload_tid; #endif /* * Do error checking on input args and parse the options string. */ if (model_name == NULL) { parseError = TRUE; goto PARSE_EXIT; } /* * Parse option string. */

Page 288: Matlab Simulink

从Matlab/Simulink模型到代码实现 272

if ((optStr != NULL) && (optStrLen > 0)) { int i; int count; char_T *thisStr; char_T *nextStr; /* * Convert to lower case. */ for (i=0; i<optStrLen; i++) { optStr[i] = tolower(optStr[i]); } /* * Convert error string to standard argc and argv format. */ /* count strings and allocate an argv */ argc = CountStrs(optStr) + 1; argv = (char **)calloc(argc,sizeof(char *)); if (argv == NULL) { (void)fprintf(stderr, "Memory allocation error while parsing options string."); exit(EXIT_FAILURE); } /* populate argv & terminate the individual substrings */ argv[0] = "dummyProgramName"; i=1; nextStr = optStr; while ((nextStr != NULL) && (thisStr = GetNextStr(nextStr, &nextStr)) != NULL && ( i < argc )) { argv[i] = thisStr; i++; } /* * Parse the standard RTW parameters. Let all unrecognized parameters * pass through to external mode for parsing. NULL out all args handled * so that the external mode parsing can ignore them. */ count = 1;

Page 289: Matlab Simulink

第 8章 面向 VxWorks的代码生成 273

while(count < argc) { const char_T *option = argv[count++]; /* final time */ if ((strcmp(option, "-tf") == 0) && (count != argc)) { char_T tmpstr[2]; char_T str2[200]; double tmpDouble; const char_T *tfStr = argv[count++]; sscanf(tfStr, "%200s", str2); if (strcmp(str2, "inf") == 0) { tmpDouble = RUN_FOREVER; } else { char_T tmpstr[2]; if ( (sscanf(str2, "%lf%1s", &tmpDouble, tmpstr) != 1) || (tmpDouble < 0.0) ) { (void)printf("finaltime must be a positive, real value or inf\n"); parseError = TRUE; break; } } finaltime = (real_T) tmpDouble; argv[count-2] = NULL; argv[count-1] = NULL; } } if (parseError) { PrintUsageMsg(); goto PARSE_EXIT; } #ifdef EXT_MODE { const char_T *extParseErrorMsg = ExtParseArgsAndInitUD(argc, (const char_T **)argv); if (extParseErrorMsg != NULL) { printf( "\nError processing External Mode command line arguments:\n");

Page 290: Matlab Simulink

从Matlab/Simulink模型到代码实现 274

printf("\t%s",extParseErrorMsg); parseError = TRUE; goto PARSE_EXIT; } } #endif /* * Check for unprocessed ("unhandled") args. */ { int i; for (i=1; i<argc; i++) { if (argv[i] != NULL) { if (strcmp(argv[i], "-w") == 0) { printf("Ignoring command line argument: '-w'\n'-w' only applies to external mode.\n"); continue; } else { printf("Unexpected command line argument: %s\n Exiting\n",argv[i]); parseError = TRUE; goto PARSE_EXIT; }

} } } PARSE_EXIT: free(argv); argv = NULL; if (parseError) { exit(EXIT_FAILURE); } } if (priority <= 0 || priority > 255-(NUMST)+1) { priority = BASE_PRIORITY; } /************************ * Initialize the model * ************************/

Page 291: Matlab Simulink

第 8章 面向 VxWorks的代码生成 275

rt_InitInfAndNaN(sizeof(real_T)); S = model_name(); if (S == NULL) { (void)fprintf(stderr,"Memory allocation error during model " "registration"); exit(EXIT_FAILURE); } if (ssGetErrorStatus(S) != NULL) { (void)fprintf(stderr,"Error during model registration: %s\n", ssGetErrorStatus(S)); TERMINATE(S); exit(EXIT_FAILURE); } if (finaltime >= 0.0 || finaltime == RUN_FOREVER) { ssSetTFinal(S, (real_T)finaltime); } INITIALIZE_SIZES(S); INITIALIZE_SAMPLE_TIMES(S); if ((status=rt_InitTimingEngine(S)) != NULL) { fprintf(stderr, "Failed to initialize sample time engine: %s\n", status); exit(EXIT_FAILURE); } rt_CreateIntegrationData(S); #if defined(RT_MALLOC) && NCSTATES > 0 if(ssGetErrorStatus(S) != NULL) { fprintf(stderr, "Error creating integration data.\n"); rt_DestroyIntegrationData(S); TERMINATE(S); exit(EXIT_FAILURE); } #endif #ifdef MAT_FILE if (rt_StartDataLogging(S) != NULL) { fprintf(stderr,"Error starting data logging.\n"); return(EXIT_FAILURE); } #endif

Page 292: Matlab Simulink

从Matlab/Simulink模型到代码实现 276

rtClockSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); startStopSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); #ifdef EXT_MODE uploadSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); rt_ExtModeInit(); extern_msg_tid = taskSpawn("tExternMsg", priority+(NUMST), VX_FP_TASK, STACK_SIZE, (FUNCPTR)rt_MsgServer, (int_T) S, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (extern_msg_tid == ERROR) { printf("handle taskpawn error"); /* xxx */ } extern_upload_tid = taskSpawn("tExternUpload", priority+(NUMST)+1,VX_FP_TASK, STACK_SIZE,(FUNCPTR)rt_UploadServer,(int_T) S, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (extern_upload_tid == ERROR) { printf("handle taskpawn error"); /* xxx */ } /* * Pause until receive model start message - if external mode. * Make sure the external mode tasks are running so that * we are listening for commands from the host. */ if (ExtWaitForStartMsg()) { printf("\nWaiting for start message from host.\n"); semTake(startStopSem, WAIT_FOREVER); } modelStatus = TARGET_STATUS_RUNNING; #endif START(S); if (ssGetErrorStatus(S) != NULL) { /* Need to execute MdlTerminate() before we can exit */ goto TERMINATE; } #ifdef STETHOSCOPE

Page 293: Matlab Simulink

第 8章 面向 VxWorks的代码生成 277

/* Make sure that Stethoscope has been properly initialized. */ ScopeInitServer(4*32*1024, 4*2*1024, 0, 0); rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,1); #endif sysAuxClkDisable(); rtSetSampleRate(1.0 / ssGetStepSize(S)); #ifdef MULTITASKING for (i = FIRST_TID + 1; i < NUMST; i++) { static char taskName[20]; sprintf(taskName, "tRate%d", i); rtTaskSemaphoreList[i] = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); VxWorksTIDs[i] = taskSpawn(taskName, priority + i, VX_FP_TASK, STACK_SIZE, tSubRate, (int_T) S, (int_T) rtTaskSemaphoreList[i], i, 0, 0, 0, 0, 0, 0, 0); } VxWorksTIDs[0] = taskSpawn("tBaseRate", priority, VX_FP_TASK, STACK_SIZE, tBaseRate, (int_T) S, (int_T) rtClockSem, (int_T) startStopSem, (int_T) rtTaskSemaphoreList, 0, 0, 0, 0, 0, 0); #else /*SingleTasking*/ VxWorksTIDs[0] = taskSpawn("tSingleRate", priority, VX_FP_TASK, STACK_SIZE, tSingleRate, (int_T) S, (int_T) rtClockSem, (int_T) startStopSem, 0, 0, 0, 0, 0, 0, 0); #endif if (sysAuxClkConnect((FUNCPTR) semGive, (int_T) rtClockSem) == OK) { rebootHookAdd((FUNCPTR) sysAuxClkDisable); printf("\nSimulation Starting\n"); sysAuxClkEnable(); /*start the real-time simulation*/ }

Page 294: Matlab Simulink

从Matlab/Simulink模型到代码实现 278

semTake(startStopSem, WAIT_FOREVER); /******************** * Cleanup and exit * ********************/ printf("\nSimulation Finished\n"); sysAuxClkDisable(); taskDelete(VxWorksTIDs[0]); semDelete(rtClockSem); semDelete(startStopSem); #ifdef EXT_MODE taskDelete(extern_msg_tid); taskDelete(extern_upload_tid); rt_ExtModeShutdown(); semDelete(uploadSem); #endif #ifdef STETHOSCOPE rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,0); #endif #ifdef MULTITASKING for (i = FIRST_TID + 1; i < NUMST; i++) { taskDelete(VxWorksTIDs[i]); semDelete(rtTaskSemaphoreList[i]); } #endif TERMINATE: #ifdef MAT_FILE rt_StopDataLogging(MATFILE,S); #endif #if defined(RT_MALLOC) && NCSTATES > 0 rt_DestroyIntegrationData(S); #endif TERMINATE(S);

Page 295: Matlab Simulink

第 8章 面向 VxWorks的代码生成 279

return(EXIT_SUCCESS); } /* end rt_main */

rt_main函数带有6个参数,它的定义如下: int_T rt_main( SimStruct * (*model_name)(void), char_T *optStr, char_T *scopeInstallString, int_T scopeFullNames, int_T priority, int_T port)

各参数的意义如下: model_name 指向模型产生代码入口点函数的指针,这个函数和 Simulink模型同名,它的指针保存

在模型的 SimStruct结构中。 optStr 选项字符串用于指定终止时间(-tf)和在外部模式时,运行前是否等待来自

Simulink的消息的触发(-w)。例如,“-tf 20 -w”表示程序运行 20秒,运行之前等待来自 Simulink外部模式控制面板的消息的触发。

scopeInstallString 用于指定将哪些信号安装到 StethoScope的字符串,可能的值包括:

NULL——不安装任何信号,这是默认设置; “*”——安装所有信号; “[A-Z]*”——安装名称以大写字母开头的模块输出的信号; 指定其他任何字符串,将安装名称为该字符串的模块输出的信号。

scopeFullName 这个参数决定 StethoScope 是用完整的层次模块名,还是仅用模块名标记信号。可能

的值为: 1——使用完整的模块名; 0——仅用模块名,这是默认设置值。

如果程序中有一个模块或者 S-函数的多个实例,请使用完整的模块名标记信号。 priority 指定程序最高优先级任务(tBaseRate)的优先级。

port 外部模式连接使用的 TCP端口号,有效值为 256~65535,默认值为 17725。 用户也可以在 tornado.tmf中定义宏 PROGRAM_OPTS,传递-w和-tf 选项给 rt_main

函数。例如:

删除的内容: in */(程序文本要与原稿一

致!!!)

删除的内容: 六

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (这句没问题!!)

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: ─

删除的内容: (

删除的内容: )

删除的内容: ─

删除的内容: ,

Page 296: Matlab Simulink

从Matlab/Simulink模型到代码实现 280

ROGRAM_OPTS = "-tf inf -w”

在WindSh窗口中调用rt_main函数,开始运行程序。例如: sp(rt_main, model, "-tf 20 -w", "*", 0, 30, 17725)

开始运行 model模型 指定终止时间为 20秒 提供 StethoScope对所有模块输出信号的访问 仅用模块名标记信号 使用默认优先级(30)作为 tBaseRate任务的优先级 使用 TCP端口号的默认值,17725

删除的内容:

删除的内容: ,

删除的内容: (

删除的内容: )

Page 297: Matlab Simulink

页 269: [1] 删除的内容 fcr 2002-9-17 15:32:00

/* Function: rt_main =================================================== * Abstract: * Initialize the Simulink model pointed to by "model_name" and start * model execution. * * This routine spawns a task to execute the passed model. It will * optionally initialize StethoScope (via ScopeInitServer), if it * hasn't already been done. It also optionally sets up external mode * communications channels to Simulink. * * Parameters: * * "model_name" is the entry point for the Simulink-generated code * and is the same as the Simulink block diagram model name. * * "optStr" is an option string of the form: * -option1 val1 -option2 val2 -option3 * * for example, "-tf 20 -w" instructs the target program to use a * stop time of 20 and to wait (in external mode) for a message * from Simulink before starting the "simulation". Note that -tf * inf sets the stop time to infinity. * * "scopeInstallString" determines which signals will be installed to * StethoScope. If scopeInstallString is NULL (the default) no signals * are installed. If it is "*", then all signals are installed. If it * is "[A-Z]*", signals coming from blocks whose names start with * capital letters will be installed. If it is any other string, then * signals starting with that string are installed. * * "scopeFullNames" parameter determines how signals are named: if * 0, the block names are used, if 1, then the full hierarchical * name is used. * * "priority" is the priority at which the model's highest priority * task will run. Other model tasks will run at successively lower * priorities (i.e., high priority numbers). * * Example: * To run the equalizer example from windsh, with printing of external * mode information, use: * * sp(rt_main,vx_equal,"0.0", "*", 0, 30) * * Returns: * EXIT_SUCCESS on success. * EXIT_FAILURE on failure. */

Page 298: Matlab Simulink

int_T rt_main( SimStruct * (*model_name)(void), char_T *optStr, char_T *scopeInstallString, int_T scopeFullNames, int_T priority, int_T port) { const char *status; int_T VxWorksTIDs[NUMST]; int optStrLen = strlen(optStr); SEM_ID rtClockSem = NULL; int_T parseError = FALSE; double finaltime = -2.0; int argc = 0; char_T **argv = NULL; #ifdef MULTITASKING SEM_ID rtTaskSemaphoreList[NUMST]; int_T i; #endif #ifdef EXT_MODE int_T extern_msg_tid; int_T extern_upload_tid; #endif /* * Do error checking on input args and parse the options string. */ if (model_name == NULL) { parseError = TRUE; goto PARSE_EXIT; } /* * Parse option string. */ if ((optStr != NULL) && (optStrLen > 0)) { int i; int count; char_T *thisStr; char_T *nextStr; /* * Convert to lower case. */ for (i=0; i<optStrLen; i++) { optStr[i] = tolower(optStr[i]);

Page 299: Matlab Simulink

} /* * Convert error string to standard argc and argv format. */ /* count strings and allocate an argv */ argc = CountStrs(optStr) + 1; argv = (char **)calloc(argc,sizeof(char *)); if (argv == NULL) { (void)fprintf(stderr, "Memory allocation error while parsing options string."); exit(EXIT_FAILURE); } /* populate argv & terminate the individual substrings */ argv[0] = "dummyProgramName"; i=1; nextStr = optStr; while ((nextStr != NULL) && (thisStr = GetNextStr(nextStr, &nextStr)) != NULL && ( i < argc )) {argv[i] = thisStr; i++; } /* * Parse the standard RTW parameters. Let all unrecognized * parameters pass through to external mode for parsing. NULL * out all args handled so that the external mode parsing can * ignore them. */ count = 1; while(count < argc) { const char_T *option = argv[count++]; /* final time */ if ((strcmp(option, "-tf") == 0) && (count != argc)) { char_T tmpstr[2]; char_T str2[200]; double tmpDouble; const char_T *tfStr = argv[count++]; sscanf(tfStr, "%200s", str2); if (strcmp(str2, "inf") == 0) { tmpDouble = RUN_FOREVER; } else { char_T tmpstr[2]; if ( (sscanf(str2, "%lf%1s", &tmpDouble, tmpstr) !=

Page 300: Matlab Simulink

1) || (tmpDouble < 0.0) ) { (void)printf("finaltime must be a positive, real value or inf\n"); parseError = TRUE; break; } } finaltime = (real_T) tmpDouble; argv[count-2] = NULL; argv[count-1] = NULL; } } if (parseError) { PrintUsageMsg(); goto PARSE_EXIT; } #ifdef EXT_MODE { const char_T *extParseErrorMsg = ExtParseArgsAndInitUD(argc, (const char_T **)argv); if (extParseErrorMsg != NULL) { printf( "\nError processing External Mode command line arguments:\n"); printf("\t%s",extParseErrorMsg); parseError = TRUE; goto PARSE_EXIT; } } #endif /* * Check for unprocessed ("unhandled") args. */ { int i; for (i=1; i<argc; i++) { if (argv[i] != NULL) { if (strcmp(argv[i], "-w") == 0) { printf("Ignoring command line argument: '-w'\n'-w' only applies to external mode.\n"); continue; } else { printf("Unexpected command line argument: %s\n Exiting\n",argv[i]);

Page 301: Matlab Simulink

parseError = TRUE; goto PARSE_EXIT; } } } } PARSE_EXIT: free(argv); argv = NULL; if (parseError) { exit(EXIT_FAILURE); } } if (priority <= 0 || priority > 255-(NUMST)+1) { priority = BASE_PRIORITY; } /************************ * Initialize the model * ************************/ rt_InitInfAndNaN(sizeof(real_T)); S = model_name(); if (S == NULL) { (void)fprintf(stderr,"Memory allocation error during model " "registration"); exit(EXIT_FAILURE); } if (ssGetErrorStatus(S) != NULL) { (void)fprintf(stderr,"Error during model registration: %s\n", ssGetErrorStatus(S)); TERMINATE(S); exit(EXIT_FAILURE); } if (finaltime >= 0.0 || finaltime == RUN_FOREVER) { ssSetTFinal(S, (real_T)finaltime); } INITIALIZE_SIZES(S); INITIALIZE_SAMPLE_TIMES(S); if ((status=rt_InitTimingEngine(S)) != NULL) { fprintf(stderr, "Failed to initialize sample time engine: %s\n", status); exit(EXIT_FAILURE); } rt_CreateIntegrationData(S); #if defined(RT_MALLOC) && NCSTATES > 0

Page 302: Matlab Simulink

if(ssGetErrorStatus(S) != NULL) { fprintf(stderr, "Error creating integration data.\n"); rt_DestroyIntegrationData(S); TERMINATE(S); exit(EXIT_FAILURE); } #endif #ifdef MAT_FILE if (rt_StartDataLogging(S) != NULL) { fprintf(stderr,"Error starting data logging.\n"); return(EXIT_FAILURE); } #endif rtClockSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); startStopSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); #ifdef EXT_MODE uploadSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); rt_ExtModeInit(); extern_msg_tid = taskSpawn("tExternMsg", priority+(NUMST), VX_FP_TASK, STACK_SIZE, (FUNCPTR)rt_MsgServer, (int_T) S,0, 0, 0, 0, 0, 0, 0, 0, 0); if (extern_msg_tid == ERROR) { printf("handle taskpawn error"); /* xxx */ } extern_upload_tid = taskSpawn("tExternUpload", priority+(NUMST)+1,VX_FP_TASK,STACK_SIZE,(FUNCPTR)rt_UploadServer, (int_T) S,0, 0, 0, 0, 0, 0, 0, 0, 0); if (extern_upload_tid == ERROR) { printf("handle taskpawn error"); /* xxx */ } /* * Pause until receive model start message - if external mode. * Make sure the external mode tasks are running so that * we are listening for commands from the host. */ if (ExtWaitForStartMsg()) { printf("\nWaiting for start message from host.\n"); semTake(startStopSem, WAIT_FOREVER); } modelStatus = TARGET_STATUS_RUNNING; #endif

Page 303: Matlab Simulink

START(S); if (ssGetErrorStatus(S) != NULL) { /* Need to execute MdlTerminate() before we can exit */ goto TERMINATE; } #ifdef STETHOSCOPE /* Make sure that Stethoscope has been properly initialized. */ ScopeInitServer(4*32*1024, 4*2*1024, 0, 0); rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,1); #endif sysAuxClkDisable(); rtSetSampleRate(1.0 / ssGetStepSize(S)); #ifdef MULTITASKING for (i = FIRST_TID + 1; i < NUMST; i++) { static char taskName[20]; sprintf(taskName, "tRate%d", i); rtTaskSemaphoreList[i] = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); VxWorksTIDs[i] = taskSpawn(taskName, priority + i, VX_FP_TASK, STACK_SIZE, tSubRate, (int_T) S, (int_T) rtTaskSemaphoreList[i], i, 0, 0, 0, 0, 0, 0, 0); } VxWorksTIDs[0] = taskSpawn("tBaseRate", priority, VX_FP_TASK, STACK_SIZE, tBaseRate, (int_T) S, (int_T) rtClockSem, (int_T) startStopSem, (int_T) rtTaskSemaphoreList, 0, 0, 0, 0, 0, 0); #else /*SingleTasking*/ VxWorksTIDs[0] = taskSpawn("tSingleRate", priority, VX_FP_TASK, STACK_SIZE, tSingleRate, (int_T) S, (int_T) rtClockSem, (int_T) startStopSem, 0, 0, 0, 0, 0, 0, 0); #endif if (sysAuxClkConnect((FUNCPTR) semGive, (int_T) rtClockSem) == OK) { rebootHookAdd((FUNCPTR) sysAuxClkDisable); printf("\nSimulation Starting\n"); sysAuxClkEnable(); /*start the real-time simulation*/

Page 304: Matlab Simulink

} semTake(startStopSem, WAIT_FOREVER); /******************** * Cleanup and exit * ********************/ printf("\nSimulation Finished\n"); sysAuxClkDisable(); taskDelete(VxWorksTIDs[0]); semDelete(rtClockSem); semDelete(startStopSem); #ifdef EXT_MODE taskDelete(extern_msg_tid); taskDelete(extern_upload_tid); rt_ExtModeShutdown(); semDelete(uploadSem); #endif #ifdef STETHOSCOPE rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,0); #endif #ifdef MULTITASKING for (i = FIRST_TID + 1; i < NUMST; i++) { taskDelete(VxWorksTIDs[i]); semDelete(rtTaskSemaphoreList[i]); } #endif TERMINATE: #ifdef MAT_FILE rt_StopDataLogging(MATFILE,S); #endif #if defined(RT_MALLOC) && NCSTATES > 0 rt_DestroyIntegrationData(S); #endif TERMINATE(S); return(EXIT_SUCCESS); } /* end rt_ma

Page 305: Matlab Simulink

第 9章 面向 DSP 和通信行业的应用

9.1 MATLAB R12.1 vs MATLAB 6.1

本节是想澄清一个概念,即通常所讲的 MATLAB X.X 和 MATLAB RY.Y 的区别。MATLAB RY.Y 是指 MATLAB 整个产品的发布版本,而 MATLAB X.X 是指 MATLAB RY.Y 中的 MATLAB 基本模块(也就是大家比较熟悉的 m 文件的基本编程环境)的版本。MATLAB RX.X包含了除基本开发环境 MATLAB X.X以外的其他一系列工具模块,尤其是它的系统级仿真环境 Simulink和目标代码生成环境 Real-Time Workshop。

MATLAB R12.1 总共包含大概 60 个模块,面向各个行业的应用。在 MATLAB 的命令窗口输入 ver,可查看各个模块的版本信息。例如在 MATLAB R12.1 的命令窗口输入ver命令,可以看到如下的信息(取决于安装了多少个模块):

>> ver -------------------------------------------------- MATLAB Version 6.1.0.450 (R12.1) on PCWIN MATLAB License Number: DEMO -------------------------------------------------- MATLAB Toolbox Version 6.1 (R12.1) 18-May-2001 Simulink Version 4.1 (R12.1) 06-Apr-2001 Stateflow Version 4.1 (R12.1) 21-May-2001 Stateflow Coder Version 4.1 (R12.1) 21-May-2001 Real-Time Workshop Version 4.1 (R12.1) 18-May-2001 Real-Time Windows Target Version 2.1 (R12.1) 02-Feb-2001 Real-Time Workshop Ada Coder Version 4.1 (R12.1) 18-May-2001 CDMA Reference Blockset Version 1.1 (R12.1) 18-May-2001 Communications Toolbox Version 2.0.1 (R12.1) 18-May-2001 Communications Blockset Version 2.0.1 (R12.1) 18-May-2001 MATLAB Compiler Version 2.2 (R12.1) 30-Mar-2001 Control System Toolbox Version 5.1 (R12.1) 18-May-2001 Data Acquisition Toolbox Version 2.1 (R12.1) 06-Apr-2001 Database Toolbox Version 2.2 (R12.1) 04-Jan-2001 Datafeed Toolbox Version 1.3 (R12.1) 03-Jan-2001 Dials & Gauges Blockset Version 1.1.1 (R12.1) 02-Feb-2001 DSP Blockset Version 4.1 (R12.1) 18-May-2001

MATLAB整个产品 的发布版本是 12.1

MATLAB基本 模块的版本是 6.1

删除的内容: (

删除的内容: )

删除的内容: X

删除的内容: X

删除的内容: 其它

删除的内容: 键入

删除的内容: 键入

删除的内容: (

删除的内容: 您

删除的内容: )

Page 306: Matlab Simulink

从Matlab/Simulink模型到代码实现 282

Real-Time Workshop Embedded Coder Version 2.0 (R12.1) 01-Mar-2001 Filter Design Toolbox Version 2.1 (R12.1) 01-Feb-2001 Financial Toolbox Version 2.1.3 (R12.1) 12-Mar-2001 Financial Derivatives Toolbox Version 1.0 (R12.1) 14-Aug-2000 Fixed-Point Blockset Version 3.1 (R12.1) 18-May-2001 Financial Time Series Toolbox Version 1.1 (R12.1) 01-Dec-2000 Fuzzy Logic Toolbox Version 2.1.1 (R12.1) 18-May-2001 GARCH Toolbox Version 1.0 (R12.1) 01-Jun-1999 System Identification Toolbox Version 5.0.1 (R12.1) 18-May-2001 Image Processing Toolbox Version 3.1 (R12.1) 18-May-2001 Instrument Control Toolbox Version 1.1 (R12.1) 18-May-2001 LMI Control Toolbox Version 1.0.7 (R12.1) 18-May-2001 Mapping Toolbox Version 1.2 (R12.1) 22-May-2000 Motorola DSP Developer's Kit Version 1.1 (R12.1) 01-Sep-2000 Model Predictive Control Toolbox Version 1.0.6 (R12.1) 18-May-2001 Mu-Analysis and Synthesis Toolbox Version 3.0.6 (R12.1) 18-May-2001 Nonlinear Control Design Blockset Version 1.1.5 (R12.1) 18-May-2001 Neural Network Toolbox Version 4.0.1 (R12.1) 02-Feb-2001 Optimization Toolbox Version 2.1.1 (R12.1) 18-May-2001

Partial Differential Equation Toolbox Version 1.0.4 (R12.1) 06-Apr-2001 Simulink Performance Tools Version 1.1 (R12.1) 18-May-2001 Power System Blockset Version 2.2 (R12.1) 06-Apr-2001 Requirements Management Interface Version 1.0.2 (R12.1) 30-Nov-2000 Robust Control Toolbox Version 2.0.8 (R12.1) 18-May-2001 MATLAB Report Generator Version 1.2 (R12.1) 01-Apr-2001 Simulink Report Generator Version 1.2 (R12.1) 01-Apr-2001 MATLAB Runtime Server Development Kit Version 6.1 (R12.1) 18-May-2001

SB2SL (converts SystemBuild to Simu... Version 2.2 (R12.1) 10-Apr-2001 Signal Processing Toolbox Version 5.1 (R12.1) 06-Apr-2001 Spline Toolbox Version 3.0 (R12.1) 13-Mar-2000 Statistics Toolbox Version 3.0 (R12.1) 01-Sep-2000 Symbolic Math Toolbox Version 2.1.2 (R12.1) 11-Sep-2000 Developer's Kit for TI(tm) DSP Version 1.1 (R12.1) 08-Jun-2001 Virtual Reality Toolbox Version 2.0 (R12.1) 06-Apr-2001 Wavelet Toolbox Version 2.1 (R12.1) 06-Apr-2001 MATLAB Web Server Version 1.2.1 (R12.1) 23-Apr-2001 xPC Target Version 1.2 (R12.1) 09-Apr-2001 xPC Target Embedded Option Version 1.2 (R12.1) 09-Apr-2001

删除的内容:

删除的内容:

删除的内容: 1

删除的内容:

Page 307: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 283

9.2 MATLAB R12.1中适用于 DSP和通信行业的模块

DSP/通信产品的开发通常包含三个重要的阶段:算法的设计和分析、系统级设计与仿真、实现。在MATLAB产品家族中,有不同的模块对这三个阶段进行支持:

算法设计与分析 MATLAB基本模块 Communications Toolbox Filter Design Toolbox Image Processing Toolbox MATLAB C/C++ Math Library MATLAB C/C++ Graphics Library Signal Processing Toolbox Wavelet Toolbox

系统级设计与仿真 Simulink Stateflow CDMA Reference Blockset Communications Blockset DSP Blockset Motorola DSP Developer’s Kit Xilinx Blockset Altera DSP Builder

实现 Real-Time Workshop Developer’s kit for TI DSP Real-time Windows Target RTW Embedded Coder Stateflow Coder Tornado (VxWorks) Real-Time Target Xilinx’s System Generator for Simulink Altera SignalCompiler for Simulink xPC Target

删除的内容:

删除的内容: 与

删除的内容: /

删除的内容: 与

Page 308: Matlab Simulink

从Matlab/Simulink模型到代码实现 284

9.3 MATLAB基本模块

MATLAB基本模块是 MATLAB整个产品体系的基础,它支持一种高效的工程计算语言——m 语言。它将科学计算、可视化和编程集成在一个简单易用的环境中,这个环境就是大家所熟悉的 m 文件编程环境。用户可以用类似于数学符号的表达方式来阐述所面对的问题,求解它的解决方案。MATLAB m语言开发的典型应用包括:

数学计算

>> A=magic(3) A = 8 1 6 3 5 7 4 9 2 >> invA=inv(A) invA = 0.1472 -0.1444 0.0639 -0.0611 0.0222 0.1056 -0.0194 0.1889 -0.1028 >> [v,d]=eig(A) v = -0.5774 -0.8131 -0.3416 -0.5774 0.4714 -0.4714 -0.5774 0.3416 0.8131 d = 15.0000 0 0 0 4.8990 0

删除的内容: —

删除的内容: 你

Page 309: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 285

0 0 -4.8990 >> rankofA=rank(A) rankofA = 3

算法开发

以下所列是用 m 语言实现的功率谱估计的 Welch 方法(%MATLABROOT%\toolbox\ signal\signal\pwelch.m)。

function varargout = pwelch(x,win,noverlap,varargin) %PWELCH Power Spectral Density estimate via Welch's method. % Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate, % Pxx, of a discrete-time signal vector X using Welch's averaged, % modified periodogram method. By default, X is divided into eight % sections with 50% overlap, each section is windowed with a Hamming % window and eight modified periodograms are computed and averaged. % % If the length of X is such that it cannot be divided exactly into % eight sections with 50% overlap, X will be truncated accordingly. % % Pxx is the distribution of power per unit frequency. For real signals, % PWELCH returns the one-sided PSD by default; for complex signals, it % returns the two-sided PSD. Note that a one-sided PSD contains the % total power of the input signal. % % Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into % overlapping sections of length equal to the length of WINDOW, and then % windows each section with the vector specified in WINDOW. If WINDOW is % an integer, X is divided into sections of length equal to that integer % value, and a Hamming window of equal length is used. If the length of % X is such that it cannot be divided exactly into integer number of % sections with 50% overlap, X will be truncated accordingly. If WINDOW % is omitted or specified as empty, a default window is used to obtain % eight sections of X. % % Pxx = PWELCH(X,WINDOW,NOVERLAP) uses NOVERLAP samples of overlap from % section to section. NOVERLAP must be an integer smaller than the WINDOW % if WINDOW is an integer. NOVERLAP must be an integer smaller than the

删除的内容: %

删除的内容: (程序文本请与原稿一致!!!)

删除的内容: function varargout = pwelch(x,win,noverlap,varargin)%PWELCH Power Spectral Density estimate via Welch's method.% Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate, % Pxx, of a discrete-time signal vector X using Welch's averaged, % modified periodogram method. By default, X is divided into eight% sections with 50% overlap, each section is windowed with a Hamming% window and eight modified periodograms are computed and averaged.%% If the length of X is such that it cannot be divided exactly into% eight sections with 50% overlap, X will be truncated accordingly. %% Pxx is the distribution of power per unit frequency. For real % signals,PWELCH returns the one-sided PSD by default; for complex % signals, it returns the two-sided PSD. Note that a one-sided PSD % contains the total power of the input signal.%% Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into% overlapping sections of length equal to the length of WINDOW, and % then windows each section with the vector specified in WINDOW. If % WINDOW is an integer, X ... [1]

Page 310: Matlab Simulink

从Matlab/Simulink模型到代码实现 286

% length of WINDOW if WINDOW is a vector. If NOVERLAP is omitted or % specified as empty, the default value is used to obtain a 50% overlap. % % [Pxx,W] = PWELCH(X,WINDOW,NOVERLAP,NFFT) specifies the number of FFT % points used to calculate the PSD estimate. For real X, Pxx has length % (NFFT/2+1) if NFFT is even, and (NFFT+1)/2 if NFFT is odd. For complex % X, Pxx always has length NFFT. If NFFT is specified as empty, the % default NFFT -the maximum of 256 or the next power of two % greater than the length of each section of X- is used. % % W is the vector of normalized frequencies at which the PSD is % estimated. W has units of rad/sample. For real signals, W spans the % interval [0,Pi] when NFFT is even and [0,Pi) when NFFT is odd. For % complex signals, W always spans the interval [0,2*Pi). % % [Pxx,F] = PWELCH(X,WINDOW,NOVERLAP,NFFT,Fs) returns a PSD computed as % a function of physical frequency (Hz). Fs is the sampling frequency % specified in Hz. If Fs is empty, it defaults to 1 Hz. % % F is the vector of frequencies at which the PSD is estimated and has % units of Hz. For real signals, F spans the interval [0,Fs/2] when NFFT % is even and [0,Fs/2) when NFFT is odd. For complex signals, F always % spans the interval [0,Fs). % % [...] = PWELCH(...,'twosided') returns a two-sided PSD of a real signal % X. In this case, Pxx will have length NFFT and will be computed over % the interval [0,2*Pi) if Fs is not specified and over the interval % [0,Fs) if Fs is specified. Alternatively, the string 'twosided' can be % replaced with the string 'onesided' for a real signal X. This would % result in the default behavior. The string 'twosided' or 'onesided' % may be placed in any position in the input argument list after NOVERLAP. % % PWELCH(...) with no output arguments by default plots the PSD % estimate in dB per unit frequency in the current figure window. % % EXAMPLE: % Fs = 1000; t = 0:1/Fs:.296; % x = cos(2*pi*t*200)+randn(size(t)); % A cosine of 200Hz plus noise % pwelch(x,[],[],[],Fs,'twosided'); % Uses default window, overlap & NFFT. % % See also PERIODOGRAM, PCOV, PMCOV, PBURG, PYULEAR, PEIG, PMTM, PMUSIC % and PSDPLOT.

Page 311: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 287

% Author(s): R. Losada % Copyright 1988-2001 The MathWorks, Inc. % $Revision: 1.27 $ $Date: 2001/04/02 20:21:06 $ % References: % [1] Petre Stoica and Randolph Moses, Introduction To Spectral % Analysis, Prentice-Hall, 1997, pg. 15 % [2] Monson Hayes, Statistical Digital Signal Processing and % Modeling, John Wiley & Sons, 1996. error(nargchk(1,6,nargin)); error(nargoutchk(0,2,nargout)); x = x(:); isreal_x = isreal(x); M = length(x); if nargin < 3, noverlap = []; if nargin < 2, win = []; end end % Obtain the necessary information to segment X [L,noverlap,win,msg] = segment_info(M,win,noverlap); error(msg); % Parse optional args nfft, fs [options,msg] = pwelch_options(isreal_x,L,varargin{:}); % Compute the number of segments k = (M-noverlap)./(L-noverlap); % Uncomment the following line to produce a warning each time the data % segmentation does not produce an integer number of segements. %if fix(k) ~= k), % warning('The number of segments is not an integer, truncating data.'); %end k = fix(k);

Page 312: Matlab Simulink

从Matlab/Simulink模型到代码实现 288

% Compute the periodogram power spectrum of each segment and average % always compute the twosided power spectrum, we force Fs = 1 to get % a spectrum not a spectral density Sxx = zeros(options.nfft,1); % Initialize xindx = 1; for i = 1:k, Sxx = Sxx + periodogram(x(xindx:xindx+L-1),win,options.nfft,1,'twosided'); xindx = xindx + L - noverlap; end Sxx = Sxx./k; % Average the sum of the periodograms % Generate the frequency vector in [rad/sample] at which Sxx was computed % If Fs is not empty, w will be converted to Hz in computepsd below w = 2.*pi.*(0:options.nfft-1)./options.nfft; % Compute the one-sided or two-sided PSD [Power/freq]. % Also compute the corresponding one-sided or two-sided power spectrum [Power], % the frequency at which the psd is computed and the corresponding frequency units [Pxx,Sxx,w,units] = computepsd(Sxx,w,options.range,options.nfft,options.Fs); if nargout==0, % Plot when no output arguments are specified yscale = 'db'; titlestring = 'Welch PSD Estimate'; psdplot(Pxx,w,units,yscale,titlestring); elseif nargout == 1, varargout = {Pxx}; elseif nargout == 2, varargout = {Pxx,w}; end %-------------------------------------------------------------------------------------- function [L,noverlap,win,msg] = segment_info(M,win,noverlap) %SEGMENT_INFO Determine the information necessary to segment the input data. % % Inputs: % M - An integer containing the length of the data to be segmented % WIN - A scalar or vector containing the length of the window or the window respectively % (Note that the length of the window determines the length of the segments) % NOVERLAP - An integer containing the number of samples to overlap (may be empty) %

Page 313: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 289

% Outputs: % L - An integer containing the length of the segments % NOVERLAP - An integer containing the number of samples to overlap % WIN - A vector containing the window to be applied to each section % MSG - A string containing possible error messages % % % The key to this function is the following equation: % % K = (M-NOVERLAP)/(L-NOVERLAP) % % where % % K - Number of segments % M - Length of the input data X % NOVERLAP - Desired overlap % L - Length of the segments % % The segmentation of X is based on the fact that we always know M and two of the set % {K,NOVERLAP,L}, hence determining the unknown quantity is trivial from the above % formula. % Initialize outputs L = []; msg = ''; % Check that noverlap is a scalar if any(size(noverlap) > 1), msg = 'You must specify an integer number of samples to overlap.'; return end if isempty(win), % Use 8 sections, determine their length if isempty(noverlap), % Use 50% overlap L = fix(M./4.5); noverlap = fix(0.5.*L); else L = fix((M+7.*noverlap)./8); end % Use a default window

Page 314: Matlab Simulink

从Matlab/Simulink模型到代码实现 290

win = hamming(L); else % Determine the window and its length (equal to the length of the segments) if ~any(size(win) <= 1) | ischar(win), msg = 'The WINDOW argument must be a vector or a scalar.'; return elseif length(win) > 1, % WIN is a vector L = length(win); elseif length(win) == 1, L = win; win = hamming(win); end if isempty(noverlap), % Use 50% overlap noverlap = fix(0.5.*L); end end % Do some argument validation if L > M, msg = 'The length of the segments cannot be greater than the length of the input signal.'; return end if noverlap >= L, msg = 'The number of samples to overlap must be less than the length of the segments.'; return end %------------------------------------------------------------------------------ function [options,msg] = pwelch_options(isreal_x,N,varargin) %PWELCH_OPTIONS Parse the optional inputs to the PWELCH function. % PWELCH_OPTIONS returns a structure, OPTIONS, with following fields: % % options.nfft - number of freq. points at which the psd is estimated % options.Fs - sampling freq. if any % options.range - 'onesided' or 'twosided' psd % Generate defaults options.nfft = max(256,2^nextpow2(N)); options.Fs = []; % Work in rad/sample

Page 315: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 291

if isreal_x, options.range = 'onesided'; else options.range = 'twosided'; end msg = ''; [options,msg] = psdoptions(isreal_x,options,varargin{:}); % [EOF] pwelch.m

数据分析和可视化

>> which e2pi D:\MATLAB6p1\toolbox\matlab\demos\e2pi.m >> e2pi 运行结果如图 9.1所示。

图 9.1 输入 e2pi的运行结果

科学与工程图形

>> which lorenz D:\MATLAB6p1\toolbox\matlab\demos\lorenz.m >> help lorenz LORENZ Plot the orbit around the Lorenz chaotic attractor. This demo animates the integration of the three coupled nonlinear differential equations that define the "Lorenz Attractor", a chaotic

删除的内容: 分页符

Page 316: Matlab Simulink

从Matlab/Simulink模型到代码实现 292

system first described by Edward Lorenz of the Massachusetts Institute of Technology. As the integration proceeds you will see a point moving around in a curious orbit in 3-D space known as a strange attractor. The orbit is bounded, but not periodic and not convergent (hence the word "strange"). Use the "Start" and "Stop" buttons to control the animation. >> Lorenz

运行结果如图 9.2所示。

图 9.2 输入 lorenz的运行结果

应用程序开发

>> which wrldtrv D:\MATLAB6p1\toolbox\matlab\demos\wrldtrv.m >> wrldtrv >> which wrldtrv D:\MATLAB6p1\toolbox\matlab\demos\wrldtrv.m >> help wrldtrv WRLDTRV Show great circle flight routes around the globe. This demonstration illustrates the Great

删除的内容: 分页符

Page 317: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 293

Circle flight paths and distances between a number of cities around the world. Use the popup menus to select your city of origin and your city of destination. Then by pushing the "Fly" button, you can watch an animation of the flight between the two cities. The distance between the two cities is also calculated. Use the "W. Hemisphere" and "E. Hemisphere" radio buttons to choose which hemisphere you want to view. >> wrldtrv

结果如图 9.3所示。

图 9.3 输入 wrldtrv的运行结果

9.4 Communications Toolbox

通信工具箱是用来帮助用户设计/分析现代通信系统的 MATLAB函数的集合。它可以实现的功能包括:

删除的内容: 分页符

Page 318: Matlab Simulink

从Matlab/Simulink模型到代码实现 294

随机信号产生,用以产生随机的噪声和信号源 >> randint(8,8,[0 1]) ans = 1 0 0 0 0 1 1 0 1 0 0 0 1 0 0 0 0 1 1 0 0 1 1 0 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 0 1 0 0 1 1 1 0 0 0 0

0 0 1 1 0 0 0 1 >> Y = wgn(1, 10, 3, 75, 'linear', 'complex') Y = Columns 1 through 3 3.1227 - 4.2414i -14.1723 + 7.3185i 7.5766 + 8.6510i Columns 4 through 6 17.2205 + 7.5509i -7.3374 +13.6852i 9.1004 + 7.0916i Columns 7 through 9 13.3007 +12.6307i -16.9041 -12.7540i -15.2837 - 0.2099i Column 10 6.0579 - 1.6622i

误码分析,画眼图和星座图,如图 9.4和图 9.5所示 >>x = 4*(rand(1000,2)-1/2); >>y = demodmap(x,1,1,'psk',4); >>red = find(y==0); >>h = scatterplot(x(red,:),1,0,'r.');

删除的内容: 。

Page 319: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 295

图 9.4 星座图(1)

>>hold on >>blue = find(y==2); >>scatterplot(x(blue,:),1,0,'b.',h);

图 9.5 星座图(2)

信源编码,包括标量量化、差分脉冲编码调制、压缩扩展器等许多功能,如图 9.6所示

predictor = [0 1]; % y(k)=x(k-1) partition = [-1:.1:.9];

删除的内容: ScaTTER Plot运行结果

删除的内容: 。

Page 320: Matlab Simulink

从Matlab/Simulink模型到代码实现 296

codebook = [-1:.1:1]; t = [0:pi/50:2*pi]; x = sawtooth(3*t); % Original signal % Quantize x using DPCM. encodedx = dpcmenco(x,codebook,partition,predictor); % Try to recover x from the modulated signal. decodedx = dpcmdeco(encodedx,codebook,predictor); plot(t,x,t,decodedx,'--')

图 9.6 DPCM调制

差错控制编码,包括卷积编码和线性块编码 >> t = poly2trellis([3 3],[4 5 7;7 4 2]); msg = [1 1 0 1 0 0 1 1]; [code1 state1]=convenc([msg(1:end/2)],t); [code2 state2]=convenc([msg(end/2+1:end)],t,state1); [codeA stateA]=convenc(msg,t); >> code1 code1 = 0 0 1 0 1 0 >> code2 code2 = 0 1 0 1 0 1

删除的内容: 信源编码

Page 321: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 297

>> codeA codeA = Columns 1 through 8 0 0 1 0 1 0 0 1 Columns 9 through 12 0 1 0 1

模拟和数字调制/解调 >> modmap('qam',16)

运行结果如图 9.7所示。

图 9.7 16QAM星座图

特殊滤波 希尔伯特变换滤波 滚降余弦滤波

伽罗华域的计算

删除的内容: 与

删除的内容: 模拟和数字调制与解调

Page 322: Matlab Simulink

从Matlab/Simulink模型到代码实现 298

9.5 Filter Design Toolbox

滤波器设计工具箱提供了建立在 MATLAB 基本模块和信号处理工具箱之上的高级滤波器设计方法,可用来设计、仿真和分析定点/浮点滤波器。Filter Design Toolbox 可以实现的滤波器结构如表 9.1和 9.2所示。

表 9.1 Filter Design Toolbox可实现的 FIR滤波器结构

滤波器结构 描 述

‘antisymmetricfir’ 反对称有限冲激响应结构

‘fir’ 直接型有限冲激响应结构

‘firt’ 直接型有限冲激响应结构的转置形式

‘latticema’ Lattice MA 滤波器结构

‘symmetricfir’ 对称的有限冲激响应结构

表 9.2 Filter Design Toolbox可实现的 IIR滤波器结构

滤波器结构 描 述

‘df1’ 直接 I型结构

‘df1t’ 直接 I型结构的转置形式

‘df2’ 直接 II型结构

‘df2t’ 直接 II型结构的转置形式

‘latticeca’ Lattice耦合全通滤波器结构

‘latticecapc’ Lattice耦合全通功率补偿滤波器结构

‘latticear’ Lattice AR滤波器结构

‘latticearma’ Lattice ARMA滤波器结构

‘statespace’ 单输入/单输出状态空间滤波器结构

9.6 Image Processing Toolbox

图像处理工具箱提供一系列的函数来支持各种各样的图像处理算法,包括: 几何操作 邻域/块操作 线性滤波/滤波器的设计 各种变换 图像分析和增强

带格式的

带格式的

带格式的

带格式的

带格式的

带格式的

删除的内容: 分页符

删除的内容: 。它

删除的内容: (表 9.1和表9.2请替换成我发给你的中文形式,文件名为修正

表.doc,本目录下也有!)

删除的内容: 表 9.1 Filter Design Toolbox可实现的FIR滤波器结构

删除的内容: 表 9.2 Filter Design Toolbox可实现的 IIR滤波器结构

删除的内容:

Page 323: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 299

二进制图像操作 区域操作

9.7 Matlab C/C++ Math/Graphics Library

MATLAB C/C++ Math/Graphics Library 封装了许多用 C/C++语言编写的用于科学计算/可视化的函数,它是 MATLAB的科学计算/可视化内核。MATLAB Compiler在将 m程序转化成 C/C++源代码的过程中,要调用这些函数。C/C++语言编写的程序可以直接调用MATLAB C/C++Math Library 中的函数,完成有关科学计算的功能,而不需要 MATLAB的存在。

9.8 Signal Processing Toolbox

信号处理工具箱是建立在 MATLAB 数值计算环境之上的、支持各种各样的信号处理方法的函数的集合。它支持的信号处理操作包括:

波形产生 >> xn=sin(pi/16*(0:31)); >> stem(xn)

结果如图 9.8所示。

图 9.8 数字序列波形

删除的内容:

删除的内容: ,结果如图 9.8所示。

删除的内容: 波形产生

Page 324: Matlab Simulink

从Matlab/Simulink模型到代码实现 300

滤波器设计/实现,如图 9.9所示 滤波器类型 滤波器设计和分析工具 fdatool

>>fdatool

图 9.9 滤波器设计与实现

用 sptool分析滤波器,如图 9.10所示 >>sptool

图 9.10 用 sptool分析滤波器

带格式的: 项目符号和编号

删除的内容: 结果

删除的内容: 。

Page 325: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 301

IIR滤波器的设计 FIR滤波器的设计

参数化建模 谱分析

统计信号处理 谱分析理论 谱分析方法 谱分析函数 时变谱

>> which specgramdemo D:\MATLAB6p1\toolbox\signal\sigdemos\specgramdemo.m >> specgramdemo Loading demo file (mtlb.mat).

结果如图 9.11所示。

图 9.11 输入 specgramdemo的运行结果

>> help specgramdemo SPECGRAMDEMO Spectrogram Demo SPECGRAMDEMO(y,Fs) displays a spectrogram of signal y, assuming a sample rate of Fs Hz. If y is specified but Fs is not,

删除的内容: 结果如图 9.11所示。

删除的内容: :

删除的内容:

删除的内容:

删除的内容: 删除的内容: n

Page 326: Matlab Simulink

从Matlab/Simulink模型到代码实现 302

a sample rate of 1 Hz is assumed. If no input arguments are supplied, y and Fs are taken from the default data file "mtlb.mat." Context menus and context-sensitive help are enabled throughout the GUI. Explore the visualization options by right-clicking on various GUI items including the spectrogram, the colorbar, etc. For example, the panner may be zoomed by dragging the mouse on the left- and right-hand edges of the highlighted zoom region. Right-clicking the highlighted zoom area brings up a menu for focusing in on the zoom region, and provides a link to context help. See also SPECGRAM, SPTOOL, FDATOOL.

9.9 Wavelet Toolbox

小波分析工具箱是建立在 MATLAB 科学计算环境之上的用于小波分析的函数的 集合。

9.10 Simulink概述

Simulink是用来对系统进行建模、仿真和分析的图形界面软件模块,如图 9.12所示。 它可用来仿真:

线性/非线性系统 连续/离散系统 混合系统 同时,它还可以仿真多速率的系统,也就是允许系统的不同部分有不同的采样更新

速率。 Simulink 是进行系统级仿真的强大工具。Simulink 提供了一个简单易用的图形化界面

和各种各样的模块来搭建系统模型。在 Simulink中,用户可以实现自顶而下或是自底而上的设计,可以非常方便地引入自己开发的算法。同时,由于 Simulink 和 Matlab 是高度集成的,用户可以选择用Matlab/Simulink来分析系统模型中任何一点的信号。

删除的内容: 并且它

Page 327: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 303

图 9.12 Simulink建模仿真环境

9.11 Stateflow

Stateflow 是解决复杂的逻辑控制问题的强大的图形化界面设计和开发工具。它和Matlab/Simulink高度集成。Stateflow创建的框图可以看作是 Simulink中的一个模块,它可用于:

基于有限状态机理论,可视化地建模和仿真复杂的事件驱动的系统; 设计和开发确定性的管理控制系统; 可以非常容易地修改用户的设计,评估结果和验证系统的行为; 从 Stateflow模型自动生成定点/浮点 C代码。 图 9.13 所示是用 Stateflow 搭建的开关切换控制逻辑系统,每一个上升沿的到来都会

删除的内容: 你

Page 328: Matlab Simulink

从Matlab/Simulink模型到代码实现 304

触发开关状态的切换,并且使计数器加 1。

图 9.13 开关切换控制逻辑

9.12 CDMA Reference Blockset

CDMA Reference Blockset是包含 IS-95A CDMA无线通信系统物理层基本模块的 Simulink模块的集合,如图 9.14和图 9.15所示。图 9.16所示是 IS-95A前向业务信道的模型。

图 9.14 CDMA Reference Blockset(a)

删除的内容: 分页符

删除的内容: 15

Page 329: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 305

图 9.15 CDMA Reference Blockset(b)

带格式的

删除的内容: 图 9.14(续) CDMA Reference Blockset(a)续在上面还是

删除的内容: 图 9.14(续) CDMA Reference Blockset(a)

删除的内容: !!也可

删除的内容:

删除的内容: 14

Page 330: Matlab Simulink

从Matlab/Simulink模型到代码实现 306

图 9.16 %MATLABROOT%\toolbox\cdma\cdmademos\is95fwdchendtoend2.mdl

9.13 Communications Blockset

Communications Blockset是用于研究、设计、仿真、分析和开发通信系统的 Simulink模块的集合,如图 9.17 所示。用户可以直接使用这些模块或是修改它们来实现自己的通信算法和系统。Communications Blockset可以用于实现整个通信链路,包括:

信号产生/信源编码 差错控制编码 交织 调制/解调 搭建信道模型 同步

删除的内容: 15

删除的内容: 16

删除的内容: 你

删除的内容: 用

删除的内容: 你

Page 331: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 307

图 9.17 Communications Blockset

9.14 DSP Blockset

DSP Blockset 是专门为数字信号处理应用设计的 Simulink 模块的集合,如图 9.18 所示。它可用于实现各种各样的 DSP 算法,例如多速率/自适应滤波、矩阵运算、统计、时频转换等。

图 9.18 DSP Blockset

删除的内容: 16

删除的内容: 17

删除的内容: ,

删除的内容: 17

Page 332: Matlab Simulink

从Matlab/Simulink模型到代码实现 308

为了查看 DSP Blockset相关的演示程序,可以使用如下命令: >> demo blocksets dsp

运行结果如图 9.19所示。

图 9.19 MATLAB演示程序

9.15 Motorola DSP Developer’s Kit

Motorola DSP Developer’s Kit 使得用户能够在 Matlab/Simulink 环境中,为 Motorola DSP56300/56600开发应用程序。它为编写调用Motorola Suite56 DSP Simulator的MEX文件和 S-函数提供了一个面向对象的接口。使用Motorola DSP Developer’s Kit,能够开发基于Motorola Suite56 DSP56300/56600产品的实现方案。Motorola DSP Developer’s Kit允许用户用 Motorola DSP 汇编语言 /C 来实现算法。用户可以选择 Motorola Suite56 DSP simulator,以便在 Matlab/Simulink 中直接运行产生的目标代码。图 9.20 所示是 Motorola DSP Developer’s Kit提供的Motorola DSP Blockset。

删除的内容: 18

删除的内容: :

删除的内容: 18

删除的内容: Demos

删除的内容: 你

删除的内容: Developer's

删除的内容: 你

删除的内容: 你

删除的内容: 你

删除的内容: 19

Page 333: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 309

图 9.20 Motorola DSP Blockset

>> mot_dsp563_filterdemo

运行和仿真结果分别如图 9.21和图 9.22所示。

删除的内容: 19

删除的内容: 20

删除的内容: 21

删除的内容: :

Page 334: Matlab Simulink

从Matlab/Simulink模型到代码实现 310

图 9.21 mot_dsp563_filterdemo.mdl

图 9.22 仿真结果

删除的内容: 20

删除的内容: 1

删除的内容: Scope

Page 335: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 311

9.16 Xilinx Blockset

Xilinx Blockset是 Xilinx公司提供的用于创建可以生成 FPGA代码的 Simulink模型的模块的集合。使用它搭建的 Simulink 组件可直接转化为可综合的 Xilinx FPGA 的 VHDL代码。图 9.23所示是使用 Xilinx Blockset中的模块搭建的 Costas锁相环模型。

图 9.23 %MATLABROOT%\toolbox\xilinx\sysgen\examples\costas_loop\costas_tb.mdl中的 Costas锁相环

9.17 Real-Time Workshop

Real-Time Workshop用于将 Simulink搭建的系统模型自动转化为实现代码(C/Ada代码)。它提供五种不同的代码格式,各种代码格式确定了生成适用于某种特定应用的代码

的框架。这五种代码格式如下: 适用于快速原型的实时代码; 适用于快速原型的实时且动态分配内存的代码; 适用于代码重用和加速仿真过程的 S-函数代码格式; 适用于嵌入式系统的嵌入式 C代码; Ada。

Real-Time Workshop的各种目标代码支持的功能如表 9.3所示。

删除的内容: 22

删除的内容: 22

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容: 。

删除的内容:

Page 336: Matlab Simulink

从Matlab/Simulink模型到代码实现 312

表 9.3 Real-Time Workshop目标代码的支持的功能

目标

支持的功能 GRT

Real-time malloc

RTW Embedded Coder

DOS Ada Tomado S-func RSIM RTWin xPC TI DSP

Static memory allocation × × × × × × × × × Dynamic memory allocation

× × × ×

Continuous time × × × × × × × × CMES S-function (noninline) × × × × × × × × × ×

Any S-functions (inlined) × × ×

Optimized for min RAM/ROM usage

× ×

Supports external mode × × × × × × Intended for rapid prototyping

× × × × × × ×

Intended for production code

× × × ×

Batch parameter tuning and Monte Carlo methods

×

Executes in hard real time × × × × × × × × ×

Non real-time executable included

× × × × ×

Multiple instances of one model ( if no Stateflow blocks in model)

× ×

9.18 Developer’s Kit for TI DSP

Developer’s Kit for TI DSP是MathWorks公司和 TI公司联合开发的一个工具包,它将 Simulink/Matlab 和 TI eXpressDSPTM开发工具连接起来,使用户能够很容易地实现数字信

号处理应用从概念到代码的开发和验证过程。这个开发工具包主要由三个接口组件组成: Target for C6701 EVM Link for Real-Time Data Exchange(RTDX) Link for Code Composer Studio IDE 有了这个开发工具,用户可以直接将 Simulink模型自动转化为 TI DSP可以实现的 C

代码,加速快速原型的开发进程。

带格式的: 项目符号和编号

删除的内容: 9.18 Developer’s Kit for TI DSPDeveloper’s Kit for TI DSP是MathWorks公司和 TI公司联合开发的一个工具包,

它将 Simulink/Matlab和 TI eXpressDSPTM

开发工具连

接起来,使用户能够很容易

地实现数字信号处理应用从

概念到代码的开发和验证过

程。这个开发工具包主要由

三个接口组件组成:Target for C6701 EVMLink for Real-Time Data Exchange (RTDX)Link for Code Composer Studio IDE有了这个开发工具,用户可

以直接将 Simulink模型自动转化为 TI DSP

删除的内容: s

删除的内容: 可以实现的 C代码,加速快速原型的开发

进程。

删除的内容: (

删除的内容: 请翻译一下

删除的内容: 此表不需翻译!)

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

删除的内容: (

删除的内容: )

Page 337: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 313

9.19 Real-Time Windows Target

Real-Time Windows Target 是实时系统原型开发和测试的 PC 解决方案。通过 Real-Time Windows Target,用户可以用同一台 PC机作为主机和目标机,用它来创建 Simulink系统模型,又可用它以 Simulink外部模式的形式实时地运行模型代码。

9.20 RTW Embedded Coder

RTW Embedded Coder 提供了一个适用于嵌入式应用的代码生成框架。它对所生成的代码的速度、内存的使用和大小都进行了优化,生成的代码格式为 Embedded-C 格式。它 支持:

定点代码生成; 浮点代码生成; 单一速率或者多速率的异步中断驱动执行模式; S-函数外包器的自动生成,使得可以在 Simulink中验证生成的代码。

9.21 Stateflow Coder

Stateflow Coder用于将 Stateflow创建的框图自动生成高效的 C代码。 >> sf_car 运行结果如图 9.24所示。 单击图 9.24中的 Build按钮,将在当前目录中创建目录 sfprj\build\sf_car\shiftlogic\src

和 sfprj\build\sf_car\shiftlogic\info。目录 sfprj\build\sf_car\shiftlogic\info 中生成了相关信息文件 binfo.mat,目录 sfprj\build\sf_car\shiftlogic\src生成了 Stateflow框图 shift_logic的 C语言代码实现文件。

删除的内容: 既

Page 338: Matlab Simulink

从Matlab/Simulink模型到代码实现 314

图 9.24 将 sf_car.mdl中的 Stateflow框图生成 C代码

sf_car_shiftlogic.h sf_car_shiftlogic.c 文件代码如下所列:

删除的内容: 23

删除的内容: 单击图 9.24中的 Build按钮,将在当前目录中创建目录sfprj\build\sf_car\shiftlogic\src和sfprj\build\sf_car\shiftlogic\info。目录sfprj\build\sf_car\shiftlogic\info中生成了相关信息文件binfo.mat,目录sfprj\build\sf_car\shiftlogic\src生成了 Stateflow框图shift_logic的 C语言代码实现文件。

删除的内容: :

删除的内容:

Page 339: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 315

/*

* * Stateflow code generation for machine: * sf_car * * Target Name : shiftlogic * Model Version : 1.188 * Stateflow Version : 4.1.0.12.10.1.000000 * Date of code generation : 09-Mar-2002 02:03:15 * */ #define IN_SF_MACHINE_SOURCE 1 #include "sf_car_shiftlogic.h" #include "shift_logic.h" int8_T _sfEvent_sf_car_=CALL_EVENT; void sf_car_initializer( void ) { /* Initialize machine's broadcast event variable */ _sfEvent_sf_car_ = CALL_EVENT; } void sf_car_terminator(void) { } shift_logic.h shift_logic.c 文件代码如下所列: /* * * Stateflow code generation for chart: * sf_car/shift_logic * * Target Name : shiftlogic * Model Version : 1.188 * Stateflow Version : 4.1.0.12.10.1.000000 * Date of code generation : 09-Mar-2002 02:03:15 *

删除的内容: shift_logic.h shift_logic.c

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 340: Matlab Simulink

从Matlab/Simulink模型到代码实现 316

*/ #include "sf_car_shiftlogic.h" #include "shift_logic.h" #define IN_NO_ACTIVE_CHILD (0) #define IN_c1_s2_first 1 #define IN_c1_s3_fourth 2 #define IN_c1_s4_second 3 #define IN_c1_s5_third 4 #define IN_c1_s7_downshifting 1 #define IN_c1_s8_steady_state 2 #define IN_c1_s9_upshifting 3 #define TWAIT (2) #define event_c1_e8_DOWN 2 #define event_c1_e9_UP 0 static SFshift_logicInstanceStruct chartInstance; void shift_logic(void); static void c1_s1_gear_state(void); void shift_logic(void) { { /* During: shift_logic */ if(_sfEvent_sf_car_ == CALL_EVENT) { if(chartInstance.Counters.i1<0xffU) { chartInstance.Counters.i1++; } } if(chartInstance.State.is_active_shift_logic == 0) { /* Entry: shift_logic */ chartInstance.State.is_active_shift_logic = 1; /* Entry: gear_state */ chartInstance.State.is_active_c1_s1_gear_state = 1; /* Entry: first */ if(chartInstance.State.is_c1_s1_gear_state != IN_c1_s2_first) { chartInstance.State.is_c1_s1_gear_state = IN_c1_s2_first; gear = 1; } /* Entry: selection_state */ chartInstance.State.is_active_c1_s6_selection_state = 1;

删除的内容:

删除的内容:

删除的内容:

删除的内容:

删除的内容:

Page 341: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 317

/* Entry: steady_state */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s8_steady_state; } else { c1_s1_gear_state(); { /* During: selection_state */ if(chartInstance.State.is_active_c1_s6_selection_state != 0) { broadcast_shift_logic_CALC_TH(); switch(chartInstance.State.is_c1_s6_selection_state) { case IN_c1_s7_downshifting: { /* During: downshifting */ if((_sfEvent_sf_car_ == CALL_EVENT) && (chartInstance.Counters.i1 >= (uint8_T )TWAIT) && (speed <= down_th)) { { int8_T previousEvent; previousEvent = _sfEvent_sf_car_; _sfEvent_sf_car_ = event_c1_e8_DOWN; c1_s1_gear_state(); _sfEvent_sf_car_ = previousEvent; } /* Exit: downshifting */ /* Entry: steady_state */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s8_steady_state; } else if(speed > down_th) { /* Exit: downshifting */ /* Entry: steady_state */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s8_steady_state; } } break; case IN_c1_s8_steady_state: /* During: steady_state */ if(speed > up_th) { /* Exit: steady_state */ /* Entry: upshifting */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s9_upshifting; chartInstance.Counters.i1=0; } else if(speed < down_th) { /* Exit: steady_state */

Page 342: Matlab Simulink

从Matlab/Simulink模型到代码实现 318

/* Entry: downshifting */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s7_downshifting; chartInstance.Counters.i1=0; } break; case IN_c1_s9_upshifting: { /* During: upshifting */ if((_sfEvent_sf_car_ == CALL_EVENT) && (chartInstance.Counters.i1 >= (uint8_T )TWAIT) && (speed >= up_th)) { { int8_T previousEvent; previousEvent = _sfEvent_sf_car_; _sfEvent_sf_car_ = event_c1_e9_UP; c1_s1_gear_state(); _sfEvent_sf_car_ = previousEvent; } /* Exit: upshifting */ /* Entry: steady_state */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s8_steady_state; } else if(speed < up_th) { /* Exit: upshifting */ /* Entry: steady_state */ chartInstance.State.is_c1_s6_selection_state = IN_c1_s8_steady_state; } } break; } } } } } } static void c1_s1_gear_state(void) { { /* During: gear_state */

Page 343: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 319

if(chartInstance.State.is_active_c1_s1_gear_state != 0) { switch(chartInstance.State.is_c1_s1_gear_state) { case IN_c1_s2_first: /* During: first */ if(_sfEvent_sf_car_ == event_c1_e9_UP) { /* Exit: first */ /* Entry: second */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s4_second; gear = 2; } break; case IN_c1_s3_fourth: /* During: fourth */ if(_sfEvent_sf_car_ == event_c1_e8_DOWN) { /* Exit: fourth */ /* Entry: third */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s5_third; gear = 3; } break; case IN_c1_s4_second: /* During: second */ if(_sfEvent_sf_car_ == event_c1_e9_UP) { /* Exit: second */ /* Entry: third */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s5_third; gear = 3; } else if(_sfEvent_sf_car_ == event_c1_e8_DOWN) { /* Exit: second */ /* Entry: first */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s2_first; gear = 1; } break; case IN_c1_s5_third: /* During: third */ if(_sfEvent_sf_car_ == event_c1_e9_UP) { /* Exit: third */ /* Entry: fourth */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s3_fourth; gear = 4; } else if(_sfEvent_sf_car_ == event_c1_e8_DOWN) {

Page 344: Matlab Simulink

从Matlab/Simulink模型到代码实现 320

/* Exit: third */ /* Entry: second */ chartInstance.State.is_c1_s1_gear_state = IN_c1_s4_second; gear = 2; } break; } } } } void initialize_shift_logic(void) { /* Initializing chart output data */ gear = (uint8_T)0; /* Initialize chart's state configuration */ memset((void*)&(chartInstance.State),0,sizeof(chartInstance.State)); }

9.22 Tornado (VxWorks) Real-Time Target

Tornado(VxWorks)Real-Time Target 用于将 Simulink 模型自动生成 VxWorks/Tornado中的任务实现。

9.23 Xilinx’s System Generator for Simulink

Xilinx’s System Generator for Simulink用于将用 Xilinx Blockset搭建的系统组件自动转化成可综合的 Xilinx FPGA的 VHDL代码实现。

9.24 xPC Target

xPC Target 是实现实时系统快速原型、测试的主-目标 PC 解决方案。可以用台式 PC作为主机,用Matlab/Simulink/Stateflow(可选)创建系统模型和生成执行代码。生成可执

删除的内容: (

删除的内容: )

删除的内容: 你

删除的内容: (

删除的内容: )

Page 345: Matlab Simulink

第 9章 面向 DSP和通信行业的应用 321

行的代码之后,可以在另一台 PC 机上实时地运行目标应用。主、目标机的两种连接方式如图 9.25和图 9.26所示。

图 9.25 xPC Target主-目标机串口连接方式

图 9.26 xPC Target主-目标机 Ethernet 连接方式

带格式的

删除的内容: 5

删除的内容: 24

删除的内容: 25

Page 346: Matlab Simulink

页 285: [1] 删除的内容 fcr 2002-9-17 15:50:00

function varargout = pwelch(x,win,noverlap,varargin) %PWELCH Power Spectral Density estimate via Welch's method. % Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate, % Pxx, of a discrete-time signal vector X using Welch's averaged, % modified periodogram method. By default, X is divided into eight % sections with 50% overlap, each section is windowed with a Hamming % window and eight modified periodograms are computed and averaged. % % If the length of X is such that it cannot be divided exactly into % eight sections with 50% overlap, X will be truncated accordingly. % % Pxx is the distribution of power per unit frequency. For real % signals,PWELCH returns the one-sided PSD by default; for complex % signals, it returns the two-sided PSD. Note that a one-sided PSD % contains the total power of the input signal. % % Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into % overlapping sections of length equal to the length of WINDOW, and % then windows each section with the vector specified in WINDOW. If % WINDOW is an integer, X is divided into sections of length equal to % that integer value, and a Hamming window of equal length is used. % If the length of X is such that it cannot be divided exactly into % integer number of sections with 50% overlap, X will be truncated % accordingly. If WINDOW is omitted or specified as empty, a default % window is used to obtain eight sections of X. % % Pxx = PWELCH(X,WINDOW,NOVERLAP) uses NOVERLAP samples of overlap % from section to section. NOVERLAP must be an integer smaller than % the WINDOW if WINDOW is an integer. NOVERLAP must be an integer % smaller than the length of WINDOW if WINDOW is a vector. If % NOVERLAP is omitted or specified as empty, the default value is used % to obtain a 50% overlap. % % [Pxx,W] = PWELCH(X,WINDOW,NOVERLAP,NFFT) specifies the number of FFT % points used to calculate the PSD estimate. For real X, Pxx has % length (NFFT/2+1) if NFFT is even, and (NFFT+1)/2 if NFFT is odd. % For complex X, Pxx always has length NFFT. If NFFT is specified as % empty, the default NFFT -the maximum of 256 or the next power of two % greater than the length of each section of X- is used. % % W is the vector of normalized frequencies at which the PSD is % estimated. W has units of rad/sample. For real signals, W spans % the interval [0,Pi] when NFFT is even and [0,Pi] when NFFT is odd. % For complex signals, W always spans the interval [0,2*Pi). % % [Pxx,F] = PWELCH(X,WINDOW,NOVERLAP,NFFT,Fs) returns a PSD computed % as a function of physical frequency (Hz). Fs is the sampling % frequency specified in Hz. If Fs is empty, it defaults to 1 Hz.

Page 347: Matlab Simulink

% % F is the vector of frequencies at which the PSD is estimated and has % units of Hz. For real signals, F spans the interval [0,Fs/2] when % NFFT is even and [0,Fs/2] when NFFT is odd. For complex signals, F % always spans the interval [0,Fs). % % [...] = PWELCH(...,'twosided') returns a two-sided PSD of a real % signal X. In this case, Pxx will have length NFFT and will be % computed over the interval [0,2*Pi] if Fs is not specified and over % the interval [0,Fs] if Fs is specified. Alternatively, the string % 'twosided' can be replaced with the string 'onesided' for a real % signal X. This would result in the default behavior. The string % 'twosided' or 'onesided'may be placed in any position in the input % argument list after NOVERLAP. % % PWELCH(...) with no output arguments by default plots the PSD % estimate in dB per unit frequency in the current figure window. % % EXAMPLE: % Fs = 1000; t = 0:1/Fs:.296; % x = cos(2*pi*t*200)+randn(size(t)); % A cosine of 200Hz plus % noise pwelch(x,[],[],[],Fs,'twosided'); % Uses default window, % overlap & NFFT. % % See also PERIODOGRAM, PCOV, PMCOV, PBURG, PYULEAR, PEIG, PMTM, % PMUSIC and PSDPLOT. % Author(s): R. Losada % Copyright 1988-2001 The MathWorks, Inc. % $Revision: 1.27 $ $Date: 2001/04/02 20:21:06 $ % References: % [1] Petre Stoica and Randolph Moses, Introduction To Spectral % Analysis, Prentice-Hall, 1997, pg. 15 % [2] Monson Hayes, Statistical Digital Signal Processing and % Modeling, John Wiley & Sons, 1996. error(nargchk(1,6,nargin)); error(nargoutchk(0,2,nargout)); x = x(:); isreal_x = isreal(x); M = length(x); if nargin < 3, noverlap = []; if nargin < 2, win = []; end

Page 348: Matlab Simulink

end % Obtain the necessary information to segment X [L,noverlap,win,msg] = segment_info(M,win,noverlap); error(msg); % Parse optional args nfft, fs [options,msg] = pwelch_options(isreal_x,L,varargin{:}); % Compute the number of segments k = (M-noverlap)./(L-noverlap); % Uncomment the following line to produce a warning each time the data % segmentation does not produce an integer number of segements. %if fix(k) ~= k), % warning('The number of segments is not an integer, truncating % data.'); %end k = fix(k); % Compute the periodogram power spectrum of each segment and average % always compute the twosided power spectrum, we force Fs = 1 to get % a spectrum not a spectral density Sxx = zeros(options.nfft,1); % Initialize xindx = 1; for i = 1:k, Sxx = Sxx + periodogram(x(xindx:xindx+L-1),win,options.nfft,1, 'twosided'); xindx = xindx + L - noverlap; end Sxx = Sxx./k; % Average the sum of the periodograms % Generate the frequency vector in [rad/sample] at which Sxx was % computed If Fs is not empty, w will be converted to Hz in computepsd below w = 2.*pi.*(0:options.nfft-1)./options.nfft; % Compute the one-sided or two-sided PSD [Power/freq]. % Also compute the corresponding one-sided or two-sided power spectrum % [Power],the frequency at which the psd is computed and the corresponding frequency units [Pxx,Sxx,w,units] = computepsd(Sxx,w, options.range,options.nfft,options.Fs); if nargout==0, % Plot when no output arguments are specified yscale = 'db'; titlestring = 'Welch PSD Estimate'; psdplot(Pxx,w,units,yscale,titlestring); elseif nargout == 1,

Page 349: Matlab Simulink

varargout = {Pxx}; elseif nargout == 2, varargout = {Pxx,w}; end %---------------------------------------------------------------------- function [L,noverlap,win,msg] = segment_info(M,win,noverlap) %SEGMENT_INFO Determine the information necessary to segment the input data. % % Inputs: % M - An integer containing the length of the data to be segmented % N - A scalar or vector containing the length of the window or the % window respectively (Note that the length of the window determines the length of the segments) % NOVERLAP - An integer containing the number of samples to overlap (may be empty) % % Outputs: % L - An integer containing the length of the segments % NOVERLAP - An integer containing the number of samples to overlap % WIN - A vector containing the window to be applied to each section % MSG - A string containing possible error messages % % % The key to this function is the following equation: % % K = (M-NOVERLAP)/(L-NOVERLAP) % % where % % K - Number of segments % M - Length of the input data X % NOVERLAP - Desired overlap % L - Length of the segments % % The segmentation of X is based on the fact that we always know M and % two of the set {K,NOVERLAP,L}, hence determining the unknown % quantity is trivial from the above formula. % Initialize outputs L = []; msg = ''; % Check that noverlap is a scalar if any(size(noverlap) > 1), msg = 'You must specify an integer number of samples to overlap.'; return end

Page 350: Matlab Simulink

if isempty(win), % Use 8 sections, determine their length if isempty(noverlap), % Use 50% overlap L = fix(M./4.5); noverlap = fix(0.5.*L); else L = fix((M+7.*noverlap)./8); end % Use a default window win = hamming(L); else % Determine the window and its length (equal to the length of the segments) if ~any(size(win) <= 1) | ischar(win), msg = 'The WINDOW argument must be a vector or a scalar.'; return elseif length(win) > 1, % WIN is a vector L = length(win); elseif length(win) == 1, L = win; win = hamming(win); end if isempty(noverlap), % Use 50% overlap noverlap = fix(0.5.*L); end end % Do some argument validation if L > M, msg = 'The length of the segments cannot be greater than the length of the input signal.'; return end if noverlap >= L, msg = 'The number of samples to overlap must be less than the length of the segments.'; return end %---------------------------------------------------------------------- function [options,msg] = pwelch_options(isreal_x,N,varargin) %PWELCH_OPTIONS Parse the optional inputs to the PWELCH function. % PWELCH_OPTIONS returns a structure, OPTIONS, with following fields: %

Page 351: Matlab Simulink

% options.nfft - number of freq. points at which the psd is estimated % options.Fs - sampling freq. if any % options.range - 'onesided' or 'twosided' psd % Generate defaults options.nfft = max(256,2^nextpow2(N)); options.Fs = []; % Work in rad/sample if isreal_x, options.range = 'onesided'; else options.range = 'twosided'; end msg = ''; [options,msg] = psdoptions(isreal_x,options,varargin{:}); % [EOF] pwelch.m

Page 352: Matlab Simulink

附录 带命令行参数的独立应用程序

本附录是为了说明怎样编写带多个输入参数的独立应用程序。将下面三个文件

commsmtr.m(主程序)、disphelp.m和 prcsofcmdline.m放在当前目录下,再 >mcc –B sgl commsmtr.m

即可生成可执行文件 commsmtr.exe。三个代码文件见本书附带光盘。 >> !commsmtr sui4bpsk.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p 0.25 **********system parameter for current simulation********** the sampling frequency: Fs=5 (MHz)

the ratio of energy of each bit to noise power spectral density: Eb/N0= 0 5 10 15 20 25 30 35 40 the channel mode: SUI-4 + AWGN the mapping method: BPSK the size of IFFT: 256 the total bits of transmitted data: 10240 the size of cyclic prefix: 64 the simulation results will be saved in file sui4bpsk.mat >> !commsmtr /? A certain communications system simulator console application commsmtr [filename] [/S Fs] [/R Eb_N0] [/C channel_model] [/M mapping_mode] [/F points_in_a_IFFT] [/T total_transmitted_data_bits] [/P cyclic_prefix_length] filename the Matlab MAT-file name in which the simulation results will be saved. Fs the Sampling frequency of transmitted data(MHz). Eb_N0 the ratio of energy of each bit to noise power spectral density. channel_model the channel mode 0 - AWGN 1 - SUI-1 + AWGN 2 - SUI-2 + AWGN

删除的内容: A

删除的内容: 代码

删除的内容: 如下:

删除的内容: function commsmtr(varargin)

% COMMSMTR - simulator console application for a certain communications system% Please compile it into windows console application commsmtr.exe % as the following MATLAB commands:% >>mex -setup% >>mbuild -setup% >>mcc -B sgl commsmtr.m% then run it as a executable program in Windows console, just like% >commsmtr /?% >commsmtr sui416qam.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p 0.25% and so on.%% Note!!!% This example is just for explaining how to input multiple command line parameters% not for simulation.%% author: YongchunChen% date: 2002/02/08% version: 1.0

%% defining default system parameters commSys.Fs=5000000; % sampling frquency=5MHzcommSys.Eb_N0=0:5:40; % the ratio of Energy of each bit to noise power spectral densitycommSys.channelType=4; % SUI-channel typecommSys.channelMode=strvcat('AWGN',... % channel type 'SUI-1 +

删除的内容:

删除的内容:

... [1]

Page 353: Matlab Simulink

附录 带命令行参数的独立应用程序 323

3 - SUI-3 + AWGN 4 - SUI-4 + AWGN 5 - SUI-5 + AWGN 6 - SUI-6 + AWGN 7 - Jakes + AWGN mapping_mode the mapping method 1 - BPSK 2 - QPSK 4 - 16QAM 6 - 64QAM. points_in_a_IFFT the size of IFFT. total_transmitted_data_bits the total bits of transmitted data. cyclic_prefix_length the size of cyclic prefix(points_in_a_IFFT). The argument Eb_N0 must be an array. You can input an array by the expressions such as 0:30, 0:5:30, [0,1,2,3,4,5,10,20,30], in which an blank is not permitted. The argument total_transmitted_data_bits must be a scalar. The arguments Fs, channel_model,mapping_mode, points_in_a_IFFT and cyclic_prefix_length can be a scalar or an array, but only one of them can be an array at the same time. The following examples are all correct using method of commsmtr: commsmtr /? commsmtr commsmtr data.mat /s [3,5] /r 0:5:40 /c 4 /m 6 /F 256 /t 65536 /p 0.25 commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m [1,2,4,6] /F 256 /t 65536 /p 0.25 commsmtr data.mat /s 5 /r 0:5:40 /c 1:4 /m 1 /F 256 /t 65536 /p 0.25 commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m 1 /F 256 /t 65536 /p 0.25 commsmtr data.mat /s 5 /r 0:1:20 /c 4 /m 2 /F [256,512] /t 65536 /p 0.25 commsmtr data.mat /s 5 /r 0:5:20 /c 4 /m 2 /F 256 /t 65536 /p [0.2,0.25] If you want to break the running of this program, please press Ctrl+C.

也可以在 Windows 98/2000 操作系统的 DOS 命令窗口,执行生成的应用程序,如附图 1所示。

如果想在另一台操作系统为 Windows 98/2000 但没有安装 MATLAB的计算机(假设为计算机 A)上执行 commsmtr.exe,要完成的步骤如下:

步骤 1. 将当前目录中的、由命令 mcc –B sgl commsmtr.m生成的 commsmtr.exe文件和 bin目录(包括其中的文件)复制到计算机 A上,例如复制到目录 C:\applications下。

步骤 2. 将文件 %MATLABROOT%\extern\lib\win32\mglinstaller.exe展开至计算机 A的某个目录下,例如 C:\matlablib,这样执行 Matlab 独立应用程序需要的动态库文件会展开在目录 C:\matlablib\bin\win32中。 步骤 3. 在计算机 A 上,将目录 C:\matlablib\bin\win32 添加至系统的环境变量 PATH 中

删除的内容: A

带格式的

带格式的

带格式的

带格式的

删除的内容: 和原文一样就没错误!

删除的内容: 我们

删除的内容: A.

删除的内容: 图 A.1 在 DOS命令窗口执行 commsmtr.exe

删除的内容: (

删除的内容: )

删除的内容: ,

删除的内容:

删除的内容: ,

删除的内容: %

删除的内容: 自

删除的内容: ,

删除的内容: ,则

Page 354: Matlab Simulink

从Matlab/Simulink模型到代码实现 324

(如果计算机 A 上已安装了 MATLAB 操作系统,请将 C:\matlablib\bin\win32 添加在%MATLABROOT%\bin\win32之前)。

步骤 4. 在计算机 A的 DOS命令窗口即可执行 commsmtr.exe程序。

附图 1 在 DOS命令窗口执行 commsmtr.exe

带格式的

删除的内容: 。(

删除的内容:

删除的内容: %

删除的内容: 。)

Page 355: Matlab Simulink

页 322: [1] 删除的内容 陈永春 2002-9-14 9:26:00

function commsmtr(varargin) % COMMSMTR - simulator console application for a certain communications system % Please compile it into windows console application commsmtr.exe % as the following MATLAB commands: % >>mex -setup % >>mbuild -setup % >>mcc -B sgl commsmtr.m % then run it as a executable program in Windows console, just like % >commsmtr /? % >commsmtr sui416qam.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p

0.25 % and so on. % % Note!!! % This example is just for explaining how to input multiple command line

parameters % not for simulation. % % author: YongchunChen % date: 2002/02/08 % version: 1.0 %% defining default system parameters commSys.Fs=5000000; % sampling frquency=5MHz commSys.Eb_N0=0:5:40; % the ratio of Energy of each bit to noise

power spectral density commSys.channelType=4; % SUI-channel type commSys.channelMode=strvcat('AWGN',... % channel type 'SUI-1 + AWGN',... 'SUI-2 + AWGN',... 'SUI-3 + AWGN',... 'SUI-4 + AWGN',... 'SUI-5 + AWGN',... 'SUI-6 + AWGN',... 'Jakes + AWGN'); commSys.ifftSize=256; % IFFT size commSys.wordSize=1; % word size corresponding to modulation method % 1 BPSK <==>2QAM % 2 QPSK <==>4QAM % 4 16QAM % 6 64QAM commSys.energyNormalized=[1,1/sqrt(2),1,1/sqrt(10),1,1/sqrt(42)]; commSys.mappingMode=strvcat('BPSK',... % mapping type 'QPSK ',... ' ',... '16QAM',...

Page 356: Matlab Simulink

' ',... '64QAM'); % total transmitted data bits including data used to estimate channel commSys.totalBits=commSys.ifftSize*commSys.wordSize*256; commSys.cpLenRatio=1/4; % cyclic prefix length in unit:(ifftSize) % length of CP equal to 1/4 of IFFT size commSys.cpLen=round(commSys.ifftSize*commSys.cpLenRatio); commSys.dataFileName='commsimulation.mat'; commSys.thirdDemension=0; % nothing as the third demension % preamble symbol column used to estimate channel, here we assume it as 1 commSys.estimatingColumn=1; %% end of definding default system parameters % processing command line parameters paramLen=length(varargin); % display helping text for the simulator console application if paramLen==1&strmatch('/?',varargin) disphelp; return; end if paramLen~=0 [cmdLineErr,commSys]=prcsOfCmdLine(commSys,varargin,paramLen); if cmdLineErr return; end end % display system parameters disp('**********system parameter for current simulation**********'); disp(['the sampling frequency: Fs=',num2str(commSys.Fs/1000000),'

(MHz)']); disp(['the ratio of energy of each bit to noise power spectral density:

Eb/N0=', ... num2str(commSys.Eb_N0)]); disp('the channel mode:'); disp(cat(2,zeros(length(commSys.channelType),17),commSys.channelMode( ... commSys.channelType+1,:))); disp('the mapping method:'); disp(cat(2,zeros(length(commSys.wordSize),17),commSys.mappingMode( ... commSys.wordSize,:))); disp(['the size of IFFT: ',num2str(commSys.ifftSize)]); disp(['the total bits of transmitted data: ',num2str (commSys.totalBits)]); disp(['the size of cyclic prefix: ',num2str(commSys.cpLen)]); disp(['the simulation results will be saved in file ',commSys.dataFileName]); disp(' '); % the processing is omitted % ...... %

Page 357: Matlab Simulink

%%% end of simulator console application

下面为 disphelp.m文件代码: function disphelp % DISPHELP - display helping text for communications simulator console

application disp(strvcat( ... 'communications simulator console application', ... ' ',... 'commsmtr [filename] [/S Fs] [/R Eb_N0] [/C channel_model]',... '[/M mapping_mode] [/F points_in_a_IFFT] [/T total_transmitted_

data_bits]',... '[/P cyclic_prefix_length]',... ' ',... 'filename the Matlab MAT-file name in which the simulation

results',... ' will be saved.',... 'Fs the Sampling frequency of transmitted data(MHz).',... 'Eb_N0 the ratio of energy of each bit to noise power ‘ spectral',... ' density.',... 'channel_model the channel mode',... ' 0 - AWGN',... ' 1 - SUI-1 + AWGN',... ' 2 - SUI-2 + AWGN',... ' 3 - SUI-3 + AWGN',... ' 4 - SUI-4 + AWGN',... ' 5 - SUI-5 + AWGN',... ' 6 - SUI-6 + AWGN',... ' 7 - Jakes + AWGN',... 'mapping_mode the mapping method',... ' 1 - BPSK',... ' 2 - QPSK',... ' 4 - 16QAM',... ' 6 - 64QAM.',... 'points_in_a_IFFT the size of IFFT.',... 'total_transmitted_data_bits the total bits of transmitted data.',... 'cyclic_prefix_length the size of cyclic prefix(points_in_a_

IFFT).',... ' ',... 'The argument Eb_N0 must be an array. You can input an array by

the',... 'expressions such as 0:30, 0:5:30, [0,1,2,3,4,5,10,20,30], in

which',... 'an blank is not permitted. The argument total_transmitted_

data_bits',... 'must be a scalar. The arguments Fs, channel_model,mapping_mode,',...

Page 358: Matlab Simulink

'points_in_a_IFFT and cyclic_prefix_length can be a scalar or an array,',...

'but only one of them can be an array at the same time.', ... 'The following examples are all correct using method of

commsmtr:', ... 'commsmtr /?', ... 'commsmtr', ... 'commsmtr data.mat /s [3,5] /r 0:5:40 /c 4 /m 6 /F 256 /t 65536 /p

0.25', ... 'commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m [1,2,4,6] /F 256 /t 65536

/p 0.25', ... 'commsmtr data.mat /s 5 /r 0:5:40 /c 1:4 /m 1 /F 256 /t 65536

/p 0.25', ... 'commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m 1 /F 256 /t 65536

/p 0.25', ... 'commsmtr data.mat /s 5 /r 0:1:20 /c 4 /m 2 /F [256,512] /t 65536

/p 0.25', ... 'commsmtr data.mat /s 5 /r 0:5:20 /c 4 /m 2 /F 256 /t 65536

/p [0.2,0.25]', ... 'If you want to break the running of this program, please press

Ctrl+C.' ... ));

下面为 prcsofcmdline.m文件代码: function [cmdLineErr, commSysNew]=prcsofcmdline(commSysDefault,

varargin,paramLen) % PRCSOFCMDLINE - processing command line parameters commSysNew=commSysDefault; cmdLineErr=0; cmdLine=lower(varargin); k=1; while k<=paramLen % beginning of while if findstr('.mat',cmdLine{k})~=[] % beginning of if FID=fopen(cmdLine{k},'w'); if FID~=-1 commSysNew.dataFileName=cmdLine{k}; fclose(FID); k=k+1; else disp('Argument filename error! The filename should be *.mat,

such as data.mat, file1.mat and so on.'); cmdLineErr=1; end else % else of if switch cmdLine{k} case '/s'

Page 359: Matlab Simulink

if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a

sampling frequency if temp~=-1&isnumeric(temp) commSysNew.Fs=temp*1000000; k=k+2; else disp('Argument Fs! The Fs should be a positive

scalar or array.'); cmdLineErr=1; end else disp('Argument Fs! The Fs should be a positive scalar or

array.'); cmdLineErr=1; end case '/r' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a Eb/N0 if temp~=-1&isnumeric(temp) commSysNew.Eb_N0=temp; k=k+2; else disp('Argument Eb_N0 error! The Eb_N0 should be a

positive scalar or array.'); cmdLineErr=1; end else disp('Argument Eb_N0 error! The Eb_N0 should be a )

positive scalar or array.'); cmdLineErr=1; end case '/c' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a channel

type if temp~=-1&isnumeric(temp) commSysNew.channelType=temp; k=k+2; else disp('Argument channel_model error! The channel_model is

presented by a integral scalar or array between 0-7.'); cmdLineErr=1; end else disp('Argument channel_model error! The channel_model is

presented by a integral scalar or array between 0-7.'); cmdLineErr=1; end

Page 360: Matlab Simulink

case '/m' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a mapping

mode if temp~=-1&isnumeric(temp) commSysNew.wordSize=temp; k=k+2; else disp('Argument mapping_mode error! The mapping_mode is presented by a

integral scalar or array including 1,2,4 or 6.'); cmdLineErr=1; end else disp('Argument mapping_mode error! The mapping_mode is presented by a

integral scalar or array including 1,2,4 or 6.'); cmdLineErr=1; end case '/f' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a IFFT

size if temp~=-1&isnumeric(temp) commSysNew.ifftSize=temp; k=k+2; else disp('Argument points_in_a_IFFT IFFT size error! The points_in_a_IFFT

should be a positive integral scalar or array.'); cmdLineErr=1; end else disp('Argument points_in_a_IFFT IFFT size error! The points_in_a_IFFT

should be a positive integral scalar or array.'); cmdLineErr=1; end case '/t' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a total

transmitted bits if temp~=-1&isnumeric(temp) commSysNew.totalBits=temp; k=k+2; if length(commSysNew.totalBits)>1|commSysNew.totalBits < 1 disp('Argument total_transmitted_data_bits error! The total_transmitted_

data_bits should be a positive integral scalar.'); cmdLineErr=1; end else disp('Argument total_transmitted_data_bits error! The total_transmitted_

data_bits should be a positive integral scalar.');

Page 361: Matlab Simulink

cmdLineErr=1; end else disp('Argument total_transmitted_data_bits error! The total_transmitted_

data_bits should be a positive integral scalar.'); cmdLineErr=1; end case '/p' if k+1<=paramLen temp=eval(cmdLine{k+1},'-1'); % -1 can not be a cyclic

prefix length if temp~=-1&isnumeric(temp) commSysNew.cpLenRatio=temp; if max(commSysNew.cpLenRatio)> 1|

min(commSysNew.cpLenRatio)<0 disp('Argument cyclic_prefix_length error! The cyclic_prefix_length

should be a numeric scalar or array between 0.0-1.0.'); cmdLineErr=1; end k=k+2; else disp('Argument cyclic_prefix_length error! The cyclic_prefix_length

should be a numeric scalar or array between 0.0-1.0.'); cmdLineErr=1; end else disp('Argument cyclic_prefix_length error! The cyclic_prefix_length

should be a numeric scalar or array between 0.0-1.0.'); cmdLineErr=1; end otherwise disp('Command Line error!'); cmdLineErr=1; end end % end of if if cmdLineErr disphelp; return; end end % end of while % check if the input parameters is correct % ..... % temp=commSysNew.ifftSize*commSysNew.wordSize; LstComMult=1; for i=1:length(temp) LstComMult=lcm(LstComMult,temp(i));

Page 362: Matlab Simulink

end commSysNew.totalBits=max(ceil(commSysNew.totalBits/LstComMult),1)*LstCom

Mult; commSysNew.cpLen=ceil(max(commSysNew.ifftSize)*commSysNew.cpLenRatio);

Page 363: Matlab Simulink

读者意见反馈卡

请您认真填写本卡并寄给我们。对于发现本书中技术问题的读者,我们另有答谢。 1.您对本书的总体感觉: □满意 □一般 □不满意 2.您认为本书的层次结构: □很好 □一般 □不好 3.您认为本书的语言文字水平: □很好 □一般 □不好 4.您认为本书的版式编排: □很好 □一般 □不好 5.您认为本书中所涉及各项操作说明的准确性: □准确 □较准确 □不准确 6.您最需要哪方面的图书? 7.您是从哪里第一次听说这本书的? □书店 □广告 □从朋友、同事等处听说 □其他 8.您一年中购买计算机类图书的数量: □2~5本 □6~10本 □多于 10本 9.您使用的操作系统是: □DOS □Windows □OS/2 □Macintosh □Unix □Linux □其他 10.您感兴趣的计算机类新书为: □操作系统类 □办公软件类 □程序设计语言类 □图形、图像设计类 □排版软件类 □网络技术类 □多媒体制作类 □其他 11.您使用 PC机的地方: □家庭 □单位 □学校 □其他 12.您是否有 CD-ROM: □有 □无 读者姓名: 单位名称: 联系电话: 请填好本卡后寄给: 清华大学校内金地公司(E-mail:[email protected])

《从Matlab/Simulink模型到代码实现》编辑部收 邮编:100084 联系电话:(010)62791976 传真:(010)62788903 公司网址:www.thjd.com.cn

如需本书可与本编辑部联系邮购,汇款请按以上地址填写,另加邮费 15%(挂号)