You are on page 1of 363

从 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 元(附光盘)
删除的内容: 引

前 言

2001 年,我曾在 MATLAB 中国代理公司北京九州恒润科技有限公司做 MATLAB 在 DSP


和通信领域的技术支持工作。现在,我在一家著名的电子通信公司从事 4G 关键技术研究,
经常要用 MATLAB 编写仿真程序或者建模,将 m 语言程序转成 C/C++代码,经常要考虑
如何从 C/C++语言中调用 MATLAB 的科学计算功能函数(即 MATLAB C/C++ Math 删除的内容: l

Library),如何从 VB 调用 MATLAB 科学计算和可视化功能的问题。本书就是为了告诉读


者如何解决这些问题,并且向读者阐述了如何从 Simulink 模型生成面向 TI DSPs/Xilinx
FPGA/WindRiver VxWorks 的代码,这对于负责硬件实现的开发人员来说,的确是一个福音。
我相信许多以 MATLAB 作为算法开发、系统仿真和实现工具的科研人员,都会深切关
注上述问题。本书的目的一是为了向读者介绍 MATLAB 各个模块在产品开发流程中的作
用,让读者对整个 MATLAB 产品的体系结构有一个全面的认识;二是要解决在使用
MATLAB 的过程中碰到的上述难题。本书不仅适用于以 MATLAB 作为开发、仿真、实现
工具的科研人员,而且适用于广大的 MATLAB 爱好者和正在使用或者将要使用 MATLAB
的在校学生。本书力图让读者站在 MATLAB 之上看 MATLAB,而并非局限于 MATLAB 工
具箱内部。本书的内容如下:
z 第 1 章全面论述 MATLAB 产品的体系结构及使用 MATLAB 工具进行产品开发的
流程。
z 第 2 章介绍 MATLAB 的算法开发功能,告诉读者编写 m 程序的高级用法,例如 删除的内容:

如何调用 C/Fortran 程序,如何建立自己的函数库,如何编写变参数的 m 函数等。


z 第 3 章告诉读者如何利用 MATLAB Compiler 把 m 程序转成独立的应用,如何从
VC++中调用 m 函数,如何从 VC++/VB 中调用 MATLAB 科学计算及可视化功能
等。
z 第 4 章介绍 MATLAB 系统级设计工具 Simulink,让大家明白 Simulink 的仿真机
理和一些重要概念,同时告诉读者如何使用 Simulink 模块封装自己的 C 算法和 m
语言算法,如何定制自己的模块库。
z 第 5 章介绍从 Simulink 模型生成面向目标代码的工具 Real-Time Workshop,告诉
读者 Real-Time Workshop 支持的目标代码和代码的自动生成过程。
z 第 6 章全面介绍面向 TI DSP 的自动代码生成工具 Development Kit for TI DSP,告
诉读者如何从 Matlab 实时或者非实时地访问 TI DSP,如何从 Simulink 模型生成
面向 TI DSP 的 Code Composer Studio 工程文件。
z 第 7 章介绍面向 Xilinx FPGA 的自动代码生成过程,告诉读者如何从 Simulink 模
型生成面向 Xilinx FPGA 的 VHDL 代码。
II 从 Matlab/Simulink 模型到代码实现

z 第 8 章介绍面向 WindRiver VxWorks 的自动代码生成过程,告诉读者如何从


Simulink 模型生成面向 VxWorks/Tornado 的代码。
z 第 9 章简单介绍了 MATLAB 产品中面向 DSP 和通信行业应用的一些模块的基本
特征。
本书中有一些需要特殊说明的地方:
z 本书中>>command_name/command_name(arg1,…,argN)表示在 MATLAB 命令窗口 删除的内容: …

输入命令 command_name 或者 command_name(arg1,…,argN),其中 command_name 删除的内容: …

可以是一个脚本 m 文件名或者函数名,>>为默认的 MATLAB 命令提示符。


z 本书中大写的 MATLAB 表示 MATLAB 整个产品,有时也指 MATLAB 基本模块,
即 MATLAB Toolbox;Matlab 指由 MATLAB 产品中的 MATLAB 基本模块和一些 删除的内容:

工具箱模块(例如,Image Processing Toolbox)及工具模块(例如 MATLAB 删除的内容: (

Compiler)组成的 m 语言开发环境。MATLAB Toolbox 是所有 MATLAB 产品的基 删除的内容: )

础,它只提供 m 语言开发的基本环境,不包括各种工具箱函数。 删除的内容: (

z 本书中%MATLABROOT%指 MATLAB 安装目录。 删除的内容: )

z 本书中某些命令的输出结果篇幅较长,为了说明问题,书中原样给出。如果不关
心命令的输出,读者可以跳过这些内容。
本书的出版首先要感谢我的导师北京航空航天大学电子工程系的万国龙教授对我的帮
助和教诲;感谢北京九州恒润科技有限公司的总经理吉英存博士在工作中给我的教益和启
发;感谢所有帮助支持过我的同事、朋友以及清华大学出版社的编辑们!
最后还要对我的父亲母亲致以深深谢意!
如果本书的出版,能给使用 MATLAB 的读者带来一些帮助和启发,我将深感荣幸!欢
迎读者朋友通过 E-mail yongchunchen@hotmail.com 和我交流 MATLAB 使用经验或者讨论
相关问题。读者也可登录北京九州恒润科技有限公司的网址 http://www.hirain.com 或者
MathWorks 公司的网址 http://www.mathworks.com 查询有关 MATLAB 的最新信息。有关
MATLAB 的购买事宜,请与北京九州恒润科技有限公司联系。

陈永春
2002 年 7 月 30 日
目 录

第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
IV 从 Matlab/Simulink 模型到代码实现

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
目 录 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
第1章 MATLAB 产品的体系结构

1.1 科研及设计人员的最爱

MATLAB 是美国 MathWorks 公司开发的用于教育、工程与科学计算的软件产品。


MATLAB 产品家族向用户提供从概念设计、算法开发、建模仿真到实时实现的理想集成
环境。无论是进行科学研究和产品开发,还是从事教育事业,MATLAB 产品都是必不可
少的工具。MATLAB 产品可用来进行:
z 数据分析和可视化

z 数值和符号计算

z 控制系统设计

z 数字信号处理

z 图像处理

z 财务工程

z 系统建模与仿真

z 图形用户界面设计

z 原型与应用开发

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
--------------------------------------------------
2 从 Matlab/Simulink 模型到代码实现

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
第 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.
4 从 Matlab/Simulink 模型到代码实现

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 运行结果 在同一页)
第 1 章 MATLAB 产品的体系结构 5

>> doc ver

运行结果如图 1.3 所示。

图 1.3 输入 doc ver 运行结果

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

1.2 MATLAB 产品的体系结构

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

删除的内容: (图题应该和图
图 1.4 MATLAB 产品的体系结构 在同一页)
6 从 Matlab/Simulink 模型到代码实现

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)
第 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) 删除的内容: Toolbox
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. 删除的内容: 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.
8 从 Matlab/Simulink 模型到代码实现

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.


第 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.
10 从 Matlab/Simulink 模型到代码实现

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.
第 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.
12 从 Matlab/Simulink 模型到代码实现

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.
第 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.
14 从 Matlab/Simulink 模型到代码实现

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.
第 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).
16 从 Matlab/Simulink 模型到代码实现

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.
第 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.
18 从 Matlab/Simulink 模型到代码实现

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.
第 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.
删除的内容: Contents
ipexdeconvwnr - Wiener deblurring.
删除的内容: fir2
ipexdeconvreg - Regularized deblurring.
ipexdeconvlucy - Lucy-Richardson deblurring. 删除的内容: aboutsignaltbx
ipexdeconvblind - Blind deblurring. 删除的内容: fircls
ipextform - Image transform gallery. 删除的内容: ac2poly
ipexshear - Image padding and shearing. 删除的内容: fircls1
ipexmri - 3-D MRI slices. 删除的内容: ac2rc
ipexconformal - Conformal mapping.
删除的内容: firls
ipexnormxcorr2 - Normalized cross-correlation.
删除的内容: arburg
ipexrotate - Rotation and scale recovery.
ipexregaerial - Aerial photo registration. 删除的内容: firrcos
删除的内容: arcov
>> what signal 删除的内容: freqs
删除的内容: armcov
M-files in directory D:\MATLAB6p1\toolbox\signal\signal 删除的内容: freqz
删除的内容: aryule
Contents fir2 psdplot
删除的内容: freqzplot
aboutsignaltbx fircls pulstran
删除的内容: barthannwin
ac2poly fircls1 pwelch
ac2rc firls pyulear 删除的内容: gauspuls
arburg firrcos rc2ac 删除的内容: bartlett
arcov freqs rc2is 删除的内容: gausswin
armcov freqz rc2lar 删除的内容: besselap
aryule freqzplot rc2poly 删除的内容: gmonopuls
barthannwin gauspuls rceps
删除的内容: besself
bartlett gausswin rectpuls
删除的内容: goertzel
besselap gmonopuls rectwin
删除的内容: bilinear
besself goertzel remez
bilinear grpdelay remezord 删除的内容: grpdelay
bitrevorder hamming resample 删除的内容: bitrevorder
blackman hann residuez 删除的内容: hamming
blackmanharris hanning rlevinson 删除的内容:
bohmanwin hilbert rooteig
删除的内容: hann
boxcar icceps rootmusic
删除的内容: blackmanharris
bscost idct sawtooth
删除的内容: hanning
buffer impinvar schurrc
删除的内容: bohmanwin
20 从 Matlab/Simulink 模型到代码实现

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


第 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 删除的内容: Contents


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 删除的内容:
22 从 Matlab/Simulink 模型到代码实现

convmtx2 ind2gray 删除的内容: convmtx2


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 删除的内容: fliptform
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
第 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 , 用 户 可 以 在 网 址
24 从 Matlab/Simulink 模型到代码实现

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
第 1 章 MATLAB 产品的体系结构 25

Blockset。Blocksets 是 Simulink 基本功能的扩展,在 Simulink Library Browser 中可以看到


已安装的所有模块库。基于 MATLAB 产品的第三方厂商也可以开发自己的模块库,如图
1.10 所示。

图 1.7 DSP 模块库

图 1.8 电力系统模块库

图 1.9 通信模块库
26 从 Matlab/Simulink 模型到代码实现

删除的内容: .
图 1.10 已安装的所有 Simulink 模块库
删除的内容: (
删除的内容: )
Real-Time Workshop(RTW)

Real-Time Workshop(RTW)是基于 Simulink 的目标代码生成工具。通过 RTW,用 删除的内容: (


户可由 Simulink 模型生成面向不同目标的实现代码。RTW 支持的目标如图 1.11 所示。 删除的内容: )

图 1.11 Real-Time Workshop 支持的目标


第 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 基
28 从 Matlab/Simulink 模型到代码实现

本环境,结合各种 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 公司联合开发的
第 1 章 MATLAB 产品的体系结构 29

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


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

z 获得清晰的系统设计规范;

z 仿真系统组件间的行为;

z 设计和测试整个系统;

z 尽早发现设计中的瑕疵;

z 降低设计风险缩短产品上市时间。

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 所示的 删除的内容: 网
安装界面。 删除的内容: 你的
30 从 Matlab/Simulink 模型到代码实现

图 1.14 Welcome to The MathWorks Installer

图 1.15 MATLAB 安装指南

图 1.16 退出安装对话框
第 1 章 MATLAB 产品的体系结构 31

图 1.17 Personal License Password

图 1.18 License Agreement

步骤 5. 图 1.18 显示的是 MathWorks 公司的软件许可证协议,只有单击 Yes 按钮,表 删除的内容: 选择


示同意此协议,才能继续安装过程,进入如图 1.19 所示的界面。
步骤 6. 在如图 1.19 所示界面中输入用户名和公司名,然后单击 Next 按钮,继续安装 删除的内容: 8
过程 , 进入 图 1.20 所示 界 面。 单 击 Yes 按 钮, 安 装程 序将 通 过 Internet 检 查 相 关 删除的内容: 19
MATLAB 产品的更新和升级信息;单击 No 按钮,进入图 1.21 所示的安装界面。 删除的内容: 网
32 从 Matlab/Simulink 模型到代码实现

图 1.19 Customer Information

图 1.20 Check for Updates and New Releases

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

Windows 系统目录 Program Files 中;


z 安装产品和对应的帮助文档,选择仅安装产品,还是仅安装帮助文档,或者两者

全部安装;
z 选择帮助文档的不同的语言版本;
第 1 章 MATLAB 产品的体系结构 33

删除的内容: 22
图 1.21 Product List

z选择想要安装的 MATLAB 产品模块和/或相应的帮助文档。只有已经购买了的 带格式的: 项目符号和编号

(也即用户的 PLP 允许使用的)MATLAB 产品模块才会显示出来,并且默认选 删除的内容: (

中。用户也可通过单击鼠标来选中或不选某个模块。值得注意的是某些模块之间 删除的内容: )
有一定的依赖关系,例如:MATLAB 模块是其他 MATLAB 产品的基础,要安装
其他模块,必须要选中或目标目录中已安装了 MATLAB 模块。MATLAB 各个模
块之间的相互关系,相信 MATLAB 代理商会代为处理,所以对用户来讲,默认选
择或是全选即可(如果磁盘空间足够的话)。在图 1.21 的右侧显示的是有效磁盘 删除的内容: (
空间、MATLAB 产品需要的磁盘空间、MATLAB 帮助文档需要的磁盘空间和总 删除的内容: )
共需要的磁盘空间信息。
单击 Next 按钮开始安装,如图 1.22 所示。当然,如果在图 1.21 中指定的安装目录不
存在,会提示创建此目录。

图 1.22 Installation Status


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

步骤 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


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

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


过 Internet 注册为 MATLAB 用户。

图 1.25 Installation Complete

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

z 如下的子目录:

\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;
36 从 Matlab/Simulink 模型到代码实现

\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 环境的文件 删除的内容: Matalb

¾ \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 默认的初始当前目录。
第 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 默认的工作界面


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

默认的 MATLAB 工作界面除了菜单和工具条之外,主要包括如下几部分:


z Command Window,即 MATLAB 的命令窗口

在该窗口中,可以运行 MATLAB 的各种命令,包括 MATLAB 内建函数、m 文件脚


本、m 文件函数等。
z Launch Pad
Launch Pad 是查询 MATLAB 各模块帮助文档、示例程序和启动相关工具命令的快捷
面板。
z Workspace,即 MATLAB 工作空间

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


都存储在该工作空间中。
z Command History,即 MATLAB 命令的历史记录窗口

在 MATLAB 命令窗口输入的命令会记录在此窗口,以供再次使用或者生成 m 文件。


z 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 快捷方式的属性对话框


第 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 所示。
40 从 Matlab/Simulink 模型到代码实现

图 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 工作空间中的变量。
第 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.
42 从 Matlab/Simulink 模型到代码实现

%
% 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
第 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;
44 从 Matlab/Simulink 模型到代码实现

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
第 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


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

if usejava('mwt')
删除的内容: %MATLABRC
initprefs Master startup M-file.
end % MATLABRC is
automatically executed by
MATLAB during startup.
%% Text-based preferences % It establishes the
NumericFormat = system_dependent('getpref','GeneralNumFormat'); MATLAB path, sets the
default figure size,
if ~isempty(NumericFormat) % and sets a few uicontrol
eval(['format ' NumericFormat(2:end)]); defaults.
end %
% On multi-user or
NumericDisplay = system_dependent('getpref','GeneralNumDisplay'); networked systems, the system
if ~isempty(NumericDisplay) manager can put
% any messages, definitions,
format(NumericDisplay(2:end));
etc. that apply to all users here.
end %
MaxTab = system_dependent('getpref','CommandWindowMaxCompletions'); % MATLABRC also invokes
a STARTUP command if the
if ~isempty(MaxTab) & MaxTab(1) == 'I'
file 'startup.m'
EnableTab = system_dependent('getpref','CommandWindowTabCompletion'); % exists on the MATLAB
TabSetting = strcmpi(EnableTab,'BTrue') * str2num(MaxTab(2:end)); path.
system_dependent('TabCompletion', TabSetting);
% Copyright 1984-2000 The
end MathWorks, Inc.
if (strcmpi(system_dependent('getpref','GeneralEightyColumns'),'BTrue')) % $Revision: 1.142 $ $Date:
2001/04/27 17:29:20 $
feature('EightyColumns',1);
end % Set up path.
if exist('pathdef','file')
ptime0 = [];
% Clean up workspace. if exist([matlabroot
clear '/toolbox/local/toolbox_cache.
mat'], 'file') &...
% Execute startup M-file, if it exists. strcmpi(system_dependent('get
if (exist('startup','file') == 2) pref','GeneralUseToolboxCach
e'),...
startup
'BTrue')
end disp(' MATLAB Toolbox
Path being initialized using
Toolbox Path
% Defer echo until startup is complete
Cache.')
if strcmpi(system_dependent('getpref','GeneralEchoOn'),'BTrue') if
echo on strcmpi(system_dependent('get
pref','GeneralUseToolboxCach
end
eDiag'),...
'BTrue')
ptime0 = clock;
end
end
matlabpath(pathdef);
if ~isempty(ptime0)
disp(sprintf(' MATLAB
Path initialized in %.2f
seconds.',
etime(clock, ptime0)));... [1]
页 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
% 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
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'));
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'))
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
第2章 算 法 开 发

MathWorks 公司一直致力于提高工程师与科研人员的研发效率,加速产品的开发过
程。为了达到这个目标,MathWorks 公司的 MATLAB 产品向用户提供了:
z Matlab:具有世界领先水准的工程计算、算法开发和数据可视化的软件;

z 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】下面这个例子是要解一个联立方程组:
⎧− 1.5 x1 + x 2 + 2 x3 = 2.5

⎨3x1 − x 2 + x3 = 5
⎪− x1 + 3x 2 + 5 x3 = 8

用 Matlab 来解这个方程组,只需在 MATLAB 命令窗口中,依次输入如下命令:

>> A=[-1.5 1 2;3 -1 1;-1 3 5];


>> b=[2.5;5;8];
>> x=A\b

x=
从 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]);
}
第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
50 从 Matlab/Simulink 模型到代码实现

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.
第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


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

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 的运行结果
删除的内容:
删除的内容:
删除的内容: 将 mymean.m 改
写成如图 2.3 所示,再使用
help 和 helpwin 命令,得到的
是不一样的结果:

删除的内容:
图 2.3 在线帮助各行之间不应有空格
删除的内容:

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


第2章 算法开发 53
删除的内容: >> help mymean

MYMEAN Average or mean


H1 help line value.
For vectors, MYMEAN(X)
在线帮助的第一行称为 H1 help line,用 lookfor 命令可以查询位于该行中的单词。 is the mean value.
For matrices, MYMEAN(X) is
Lookfor 命令可用于搜索 H1 help line 中带有特定单词的函数: a row vector
>> helpwin mymean
>> lookfor 'average or mean' 结果如图 2.4 所示。
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.4 修改 mymean.m 后输
入 helpwin mymean 的运行结

删除的内容: ,

删除的内容:
图 2.5 带有多个输入输出变量的函数
删除的内容:
【例 2】输入参数可变的 m 函数。如图 2.6 所示是一个输入参数可变的 m 函数。编写 删除的内容: (应该和图在同
输入参数可变的函数,要注意的几点是: 一页)
z 输入参数可变的函数的最后一个输入参数一定要是 varargin;

z 使用 nargin 命令或者 length(varargin)来检测到底输入了多少个参数; 删除的内容: )


z 使用元胞数组内容提取符 {} 来提取可变输入参数中的输入内容。 删除的内容: (
图 2.6 所示的函数,目的是要接收可变个数据点(x,y),然后将其依次连接成线。 删除的内容: )
z 第 1 行是函数定义行,如果输入参数中部分是不可变的(例如 N 个固定的输入参 删除的内容: 有一
数),部分是可变的,函数定义可改写为: 删除的内容: (
删除的内容: )
54 从 Matlab/Simulink 模型到代码实现

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

z 第 2~4 行是在线帮助,删除之后并不会影响函数的功能,但不利于他人使用。 删除的内容: ─


z 第 6~11 行是检查输入参数的个数是否大于 1,如果不大于 1,则提示函数至少输 删除的内容: ─
入两个点。当然在此这只是为了说明问题,并没有对参数的数据形式作严格
检查。
删除的内容: ─
z 第 13~17 行是从输入的数据点中,提取出 x 坐标和相应的 y 坐标。
删除的内容: 分页符

删除的内容:
图 2.6 输入参数可变的 m 函数
删除的内容:
z 第 19~20 行是获得输入的数据点中 x 坐标和 0 的最小值,y 坐标和 0 的最小值。 删除的内容: ─
z 第 22 行是作出输入数据点的连线图。
z 第 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!
第2章 算法开发 55

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

删除的内容:
删除的内容:
删除的内容:
删除的内容:
删除的内容: >> myvarin([0 1])
Usage:myvarin([x1,y1],[x2,y2]
图 2.8 输入 myvarin([0 1],[2 3],[3 10],[-1 -16])的运行结果 ,...,[xN,yN]),where N>=2
Input more than one
【例 3】输出参数可变的 m 函数。图 2.9 所示是一个输出参数可变的函数。编写输出 points,Please!
>> myvarin
参数可变的函数,要注意的几点是: Usage:myvarin([x1,y1],[x2,y2]
z 输出参数可变的函数的最后一个输出参数一定要是 varargout; ,...,[xN,yN]),where N>=2
Input more than one
z 使用 nargout 命令或者 length(varargout)来检测到底有多少个输出参数;
points,Please!
z 使用元胞数组内容提取符 {} 来对可变输出参数赋值。
删除的内容: )
56 从 Matlab/Simulink 模型到代码实现

图 2.9 所示的函数,目的是要产生可变个随机数据点(x,y)。 删除的内容: (


z 第 1 行是函数定义行,如果输出参数中有部分是不可变的(例如 N 个固定的输出 删除的内容: )
参数),部分是可变的,函数定义可改写为: 删除的内容: (
删除的内容: )
function [p1,p2,…,pN,varargout]=myvarout

z 第 2~4 行是在线帮助,删除之后并不会影响函数的功能,但不利于他人使用。 删除的内容: ─


z 第 6~11 行是检查输出参数的个数是否大于 0,如果不大于 0,则提示函数至少要 删除的内容: ─
有一个输出参数。
删除的内容: 分页符

删除的内容:
图 2.9 输出参数可变的 m 函数
删除的内容:
z 第 13~17 行是产生坐标在[0 9]间均匀分布的随机整型数据点,返回(x,y)坐标。 删除的内容: ─
删除的内容: (
>> p1=myvarout
删除的内容: )

p1 =

6 2

>> [p1 p2 p3]=myvarout

p1 =

4 0

p2 =

9 5
第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 模块:
z MATLAB 基本模块

zSignal Processing Toolbox


z Image Processing Toolbox

z Wavelet Toolbox

如果用户需要把用 Matlab 开发的图像处理程序转成独立的应用或者 C/C++源代码,


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

MATLAB 提供的主要工具箱在第 1 章中已经列举出来了。如有用户需要查看某个工 删除的内容: 用


具箱中封装的函数的信息,只要把上一章中各个工具箱的缩写当作参数来使用 help 、 删除的内容: 图 1.6
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.
58 从 Matlab/Simulink 模型到代码实现

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.
删除的内容:
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. 删除的内容:
第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. 删除的内容:
60 从 Matlab/Simulink 模型到代码实现

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 的运行结果
删除的内容:
删除的内容:
第2章 算法开发 61

2.5 调用 C/Fortran 程序

在 MATLAB 中,只要按照 MATLAB 规定的语法,编写一个适当的 MexFunction 函


数作为接口,就可以调用 C 或者 Fortran 编写的算法函数。

删除的内容:

图 2.12 %MATLABROOT%\extern\examples\mex\yprime.m 删除的内容:


带格式的
图 2.12 所示是一个描述微分方程组
( ) ( )
删除的内容: (
⎧ y ′′ = 2 * y ′′′ + y − µs * ( y + µ ) ( y + µ )2 + ( y ′′)2 3 − µ * ( y − µs ) ( y − µs )2 + ( y ′′)2 3

( ) ( )
删除的内容: )
⎪ y ( 4 ) = −2 * y ′ + y ′′ − µs * y ′′ ( y + µ )2 + ( y ′′)2 − µ * y ′′ ( y − µs )2 + ( y ′′)2
3 3

⎨ 删除的内容: (
⎪µ = 1 82.54 删除的内容: )

⎩µs = 1 − µ 删除的内容: (
的 m 语言函数。输入参数 t 表示求解的时间段 [t 0 ,t1 ] 或者时间向量 [t 0 t1 L t N ] ,输入参 删除的内容: )
数 y 表示微分方程组对应时刻 t 0 的初值 [ y, y ′, y ′′, y ′′′] ,返回参数表示 [y ′, y ′′, y ′′′, y ( ) ] 。要得 4
删除的内容: (

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


(4 )
= y ′′ , yp ( 3 ) = y ′′′ , yp ( 4 ) = y , 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= 删除的内容: (
删除的内容: )
62 从 Matlab/Simulink 模型到代码实现

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
第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
64 从 Matlab/Simulink 模型到代码实现

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
第2章 算法开发 65

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


[1 2 3 4],返回值 t 包含积分时刻,返回值 y 为对应积分时刻 t 的 [ y, y ′, y ′′, y ′′′] 值。如果我 删除的内容: (

们想作出微分方程组的解(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
66 从 Matlab/Simulink 模型到代码实现

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
第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
68 从 Matlab/Simulink 模型到代码实现

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
第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
70 从 Matlab/Simulink 模型到代码实现

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 * 删除的内容: [yp] = yprime
3 * YPRIME.C Sample .MEX file corresponding to YPRIME.M 带格式的: 项目符号和编号
4 * 删除的内容: (
5 The calling syntax is: 删除的内容: (t, y
6 * 删除的内容: )
删除的内容: )
删除的内容: *
带格式的: 项目符号和编号
删除的内容: <#> ... [1]
删除的内容: (
删除的内容: (MAX
删除的内容: )
第2章 算法开发 71 删除的内容: )
删除的内容: #define MAX
7 [ yp] = yprime(t, y) 删除的内容: (A
8 * 删除的内容: )
9 You may also want to look at the corresponding M-code, yprime.m. 带格式的: 项目符号和编号
10 *=================================================================*/ 删除的内容: (
11 删除的内容: (A, B
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 删除的内容: (B
20 删除的内容: )
21 /* Output Arguments */ 删除的内容: ) ?
22
删除的内容: (
23 #define YP_OUT plhs[0]
删除的内容: (A
24
删除的内容: )
25 #if !defined(MAX)
删除的内容: ) :
26 #define MAX(A, B) ((A) > (B) ? (A) : (B))
删除的内容: (
27 #endif
删除的内容: (B
28
删除的内容: )
29 #if !defined(MIN)
删除的内容: )
30 #define MIN(A, B) ((A) < (B) ? (A) : (B))
删除的内容: )
31 #endif
删除的内容: ) ... [2]
32
删除的内容: #if !defined
33 #define PI 3.14159265
删除的内容: (
34
删除的内容: (MIN
35 static double mu = 1/82.45;
删除的内容: )
36 static double mus = 1 - 1/82.45;
删除的内容: ) ... [3]
37
删除的内容: (
38
删除的内容: (A, B
39 static void yprime(
删除的内容: )
40 double yp[],
删除的内容: )
41 double *t,
删除的内容: (
42 double y[]
删除的内容: (
43 )
删除的内容: (
44 {
删除的内容: (A
删除的内容: )
删除的内容: ) <
删除的内容: (
删除的内容: (B
删除的内容: )
删除的内容: ) ?
删除的内容: (
删除的内容: r1 = sqrt
删除的内容: (
删除的内容: (
删除的内容: (
带格式的: 项目符号和编号
删除的内容: (y[0]+mu
72 从 Matlab/Simulink 模型到代码实现 删除的内容: )
删除的内容: )*
45 double r1,r2; 删除的内容: (
46 删除的内容: (y[0]+mu
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]); 删除的内容: ) + y[2]*y[2]
49 删除的内容: )
50 /* Print warning if dividing by zero. */ 删除的内容: ); ... [5]
51 if (r1 == 0.0 || r2 == 0.0 ){
删除的内容: (
52 mexWarnMsgTxt("Division by zero!\n");
删除的内容: (y[0]-mus
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);
删除的内容: (y[0]-mus
59 return;
删除的内容: )
60 }
删除的内容: ) + y[2]*y[2]
61
删除的内容: )
62 void mexFunction( int nlhs, mxArray *plhs[],
删除的内容: ); ... [6]
63 int nrhs, const mxArray*prhs[] )
带格式的: 项目符号和编号
64
删除的内容: if
65 {
删除的内容: (
66 double *yp;
删除的内容: (r1 == 0.0 || r2[7]
...
67 double *t,*y;
删除的内容: )
68 unsigned int m,n;
删除的内容: ){
69
删除的内容: mexWarnMsgTx
... [8]
70 /* Check for proper number of arguments */
带格式的: 项目符号和编号
71
删除的内容: (
72 if (nrhs != 2) {
删除的内容: ("Division by[9]
...
73 mexErrMsgTxt("Two input arguments required.");
删除的内容: )
74 } else if (nlhs > 1) {
删除的内容: );
75 mexErrMsgTxt("Too many output arguments.");
带格式的: 项目符号和编号
76 } 带格式的: 项目符号和编号
77 删除的内容: yp[1] =... [10]
78 /* Check the dimensions of Y. Y can be 4 X 1 or 1 X 4. */ 带格式的: 项目符号和编号
79 删除的内容: (
80 m = mxGetM(Y_IN); 删除的内容: (y[0]+mu
81 n = mxGetN(Y_IN); 删除的内容: )
82 if (!mxIsDouble(Y_IN) || mxIsComplex(Y_IN) || 删除的内容: )/
删除的内容: (
删除的内容: (r1*r1*r1
删除的内容: )
删除的内容: )-mu*
删除的内容: (
删除的内容: (y[0]-mus
删除的内容: )
删除的内容: )/

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

... [11]
第2章 算法开发 73

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


删除的内容: YP_OUT =
84 mexErrMsgTxt("YPRIME requires that Y be a 4 x 1 vector."); mxCreateDoubleMatrix
85 } 删除的内容: (
86 删除的内容: (4, 1, mxREAL
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);
删除的内容: yp = mxGetPr
92
带格式的: 项目符号和编号
93 t = mxGetPr(T_IN);
删除的内容: (
94 y = mxGetPr(Y_IN);
删除的内容: (YP_OUT
95
删除的内容: )
96 /* Do the actual computations in a subroutine */
删除的内容: );
97 yprime(yp,t,y);
98 return; 带格式的: 项目符号和编号
99 删除的内容: t = mxGetPr
100 } 带格式的: 项目符号和编号
删除的内容: (
程序说明如下: 删除的内容: (T_IN
z 第 12~36 行,头文件、宏定义和数据定义。 删除的内容: )
z 第 39~60 行,C 算法函数 yprime。 删除的内容: );
z 第 62~100 行,Matlab 调用 C 算法的接口函数 mexFunction。关于如何编写该函 y = mxGetPr

数,请参考 MATLAB HTML 帮助 MATLAB\Using MATLAB\External Interfaces/ 删除的内容: (

API\Calling C and Fortran Programs from MATLAB 一节。 删除的内容: (Y_IN


要在 MATLAB 中调用该函数,首先要用 mex 命令将其编译为动态链接库。过程 删除的内容: )
如下: 删除的内容: );
带格式的: 项目符号和编号
>> mex -setup 删除的内容: yprime
Please choose your compiler for building external interface (MEX) files: 删除的内容: (
删除的内容: (yp,t,y
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
删除的内容:
74 从 Matlab/Simulink 模型到代码实现

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 函数。
第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
76 从 Matlab/Simulink 模型到代码实现

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
第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
78 从 Matlab/Simulink 模型到代码实现

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
第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
80 从 Matlab/Simulink 模型到代码实现

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
第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
82 从 Matlab/Simulink 模型到代码实现

-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
第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 搜索路径设置对话框
删除的内容:
84 从 Matlab/Simulink 模型到代码实现 删除的内容:
删除的内容:
删除的内容:
删除的内容:
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. 删除的内容: the
%
% 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 删除的内容: of
% ALPHABET are distinct, then the probability distribution is 删除的内容: of
% uniform. 删除的内容: is
% 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. 删除的内容: The
%
% OUT = RANDSRC(M,N,ALPHABET,STATE) resets the state of RAND to STATE.
第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
86 从 Matlab/Simulink 模型到代码实现

% --- 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))
第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) 带格式的
88 从 Matlab/Simulink 模型到代码实现

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
第2章 算法开发 89

1 + 2 z −1 删除的内容:
【例 5】作出传递函数 H (z ) = 的零极点分布图,可使用如下的脚本 m
1 + 2 z −1 + 3z − 2
文件 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.
90 从 Matlab/Simulink 模型到代码实现

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');
第2章 算法开发 91

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

删除的内容: 分页符

删除的内容:
图 2.16 edge_detect('blood1.tif')运行结果(1)
删除的内容:

删除的内容:
图 2.17 edge_detect('blood1.tif')运行结果(2)
删除的内容:
92 从 Matlab/Simulink 模型到代码实现

删除的内容:
图 2.18 edge_detect('rice.tif')运行结果(1)
删除的内容:
删除的内容: 3

删除的内容:
图 2.19 edge_detect('rice.tif')运行结果(2)
删除的内容:
>> whos
删除的内容: 4
Name Size Bytes Class

canny 256x256 65536 uint8 array (logical)


sobel 256x256 65536 uint8 array (logical)

Grand total is 131072 elements using 131072 bytes


页 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]/
第3章 将 m 程序转换成独立的应用

MATLAB Compiler 可以将开发出来的 m 程序自动转成独立的应用。这种转换需要的 删除的内容: ,


MATLAB 产品模块包括:
z MATLAB Compiler
z MATLAB C/C++ Math Library

如果 m 程序中包含图形功能,则还需要 删除的内容: (不需要缩进)


zMATLAB C/C++ Graphics Library
转换过程如图 3.1 所示。 删除的内容: (不需要缩进)

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

MATLAB Compiler

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

C/C++编译器

目标文件 ™ MATLAB C/C++ Graphics Library


™ MATLAB Math m-file Library
™ MATLAB Math Built-in Library
™ MATLAB API Library
™ MATLAB MAT-file Library
™ ANSI C/C++ Library
连接器

独立应用

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

MATLAB Compiler 的作用是将 m 程序转成 C/C++源代码,这种源代码需要用 C/C++


编译器编译连接成独立应用。在将 m 程序转成独立应用的过程中生成的 C/C++源代码,
94 从 Matlab/Simulink 模型到代码实现

原则上是可以被其他的 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++编 删除的内容: 1
译器。

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...
第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 操作系统来说,包括:
z MATLAB 自带的 Lcc C version 2.4

z Watcom C/C++ versions 10.6 & 11.0


z Borland C++ versions 5.0, 5.2, 5.3, 5.4, & 5.5
z Microsoft Visual C++(MSVC) versions 5.0 & 6.0 删除的内容: (
对于 UNIX 平台来说,包括: 删除的内容: )
z GNU C compiler, gcc(HP 和 SGI64 工作站除外) 删除的内容: (
z 所有 UNIX 平台系统自带的 ANSI C compiler 删除的内容: )
z 所有 U N IX 平台自带的 C ++ com piler(L inux 除外) 删除的内容: (
z 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 下同)
96 从 Matlab/Simulink 模型到代码实现

该插件的用途在后面会讲到。 删除的内容:
删除的内容: ,
>> 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 删除的内容: )
文件时使用。 删除的内容: (
删除的内容: )
第3章 将 m 程序转换成独立的应用 97

图 3.2 MATLAB Project Wizard

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

【例 7】设计一个 16 阶 Butterworth 滤波器,要求采样频率 Fs=16kHz,从 1.5kHz 到 删除的内容:


5kHz 带通,作出其频率响应图,并将该 m 程序转成独立的应用程序和对应的 C/C++源 删除的内容: kHz
代码。 删除的内容:
删除的内容:
function designbutworth 删除的内容: kHz
%designbutworth.m 删除的内容:
%used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz 删除的内容: kHz
%passband with a sampling rate 16kHz.
删除的内容: KHz
Fs=16;
删除的内容: KHz
[b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass')
删除的内容: (大写 K 按规
freqz(b,a,512,16000)
定要改成小写,此处是否能
>> designbutworth
改?)
删除的内容: KHz
b=

Columns 1 through 6

0.0040 0 -0.0320 0 0.1120 0


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

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


第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
100 从 Matlab/Simulink 模型到代码实现

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 所示。


第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
102 从 Matlab/Simulink 模型到代码实现

-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
第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.
104 从 Matlab/Simulink 模型到代码实现

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
第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.
106 从 Matlab/Simulink 模型到代码实现

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. 删除的内容:
第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.
108 从 Matlab/Simulink 模型到代码实现

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.
第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
110 从 Matlab/Simulink 模型到代码实现

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
第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 函数带一个字符串参数(如果确实想输入多个参 删除的内容: 。
数,用法请见附录)。 删除的内容: A。
【例 8】按给定的偶数阶数设计一个 Butterworth 滤波器,要求阶数大于 16,采样频
率 Fs=16kHz,1.5kHz~5kHz 带通,作出其频率响应图,并将该 m 程序转成独立的应用程 删除的内容: kHz
序和对应的 C 源代码。 删除的内容:
删除的内容: 从
function dsgnbutworth_varorder(order) 删除的内容: kHz
%dsgnbutworth_varorder.m
删除的内容: 到
%used to design a Butterworth filter,which has a variable
删除的内容: kHz
%even order(>=16)and a 1.5kHz-5kHz passband with a sampling
删除的内容: KHz
%rate 16kHz.
if order<16|(mod(order,2)~=0) 删除的内容: KHz
disp('The order should be an even integer,not less than 16!'); 删除的内容: KHz
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=
112 从 Matlab/Simulink 模型到代码实现

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 滤波器的频率响应
第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 删除的内容: KHz
%even order(>=16)and a 1.5kHz-5kHz passband with a sampling 删除的内容: KHz
%rate 16kHz.
删除的内容: KHz
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 删除的内容:
114 从 Matlab/Simulink 模型到代码实现

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


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

Columns 15 through 17

0.0181 -0.0032 0.0004

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


删除的内容: 分页符

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

其次,即使是满足上述要求的 m 函数,要用 MATLAB Compiler 转成 C/C++源代码或


者独立的应用,编写时也有一些限制。
z 不能使用 MATLAB 对象。

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

function designbutworthand2df2
%designbutworthand2df2.m
%used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz passband 删除的内容: KHz
%a sampling rate 16kHz, then construct a direct-form II object. 删除的内容: KHz
Fs=16; 删除的内容:
[b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass'); 删除的内容: KHz
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,会产生运行时的
116 从 Matlab/Simulink 模型到代码实现

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

EXITING

z 不能用 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=

ERROR: Reference to unknown function or variable 'a' while evaluating 删除的内容:


expression.

EXITING
>> !testinputandeval
Input MATLAB expression: sin(10)

R=

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

ans =

-0.5440

z 不能动态地命名变量,然后用 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
118 从 Matlab/Simulink 模型到代码实现

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 所示的编译日志显示界面。 删除的内容: (


删除的内容: )
第3章 将 m 程序转换成独立的应用 119

删除的内容: 分页符

图 3.9 MATLAB Project Wizard 项目设置

图 3.10 New Project Information

图 3.11 选择 m 文件
120 从 Matlab/Simulink 模型到代码实现

图 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 中没有显示菜 删除的内容: 中的
单和工具条。
第3章 将 m 程序转换成独立的应用 121

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

图 3.15 plotfreqprj.exe 运行结果


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

图 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 带格式的


第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 所示。


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

图 3.20 New Project Information

图 3.21 consoleprj 工程文件


第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);
126 从 Matlab/Simulink 模型到代码实现

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 库函数的算法程序。


第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 所示。 带格式的
128 从 Matlab/Simulink 模型到代码实现

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

删除的内容:
删除的内容:
删除的内容: 步骤 9. 如图
3.27 所示,使用 Microsoft
Visual C++ IDE 中的菜单命
图 3.26 添加库文件搜索路径%MATLABROOT%\extern\lib\win32\Microsoft\msvc60 令 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.27 添加库文件
3.28 所示。
分页符
第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)


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

步骤 2. 在图 3.30 所示界面中选择 Single document,后续步骤都按默认状态选择,直 带格式的

至生成如图 3.31 所示的工程文件。

删除的内容:
图 3.30 选择 Single document
删除的内容: 步骤 3. 修改
mfcprjView.h,在视类定义中
添加一行 int mysvd
删除的内容: (
删除的内容: (CDC *pDC
删除的内容: )
删除的内容: );,如下所
示。
删除的内容: 分页符

图 3.31 mfcprj 工程文件

步骤 3. 修改 mfcprjView.h,在视类定义中添加一行语句:int mysvd(CDC *pDC);,如 带格式的

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

#if !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_) 删除的内容: #if !defined(AF


#define AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_ X_MFCPRJVIEW_H__8A4E
40B9_A69C_4760_AE4C_06
D3FB7B69CC__INC
#if _MSC_VER > 1000 #LUDED_)define
#pragma once AFX_MFCPRJVIEW_H__8A
4E40B9_A69C_4760_AE4C_
#endif // _MSC_VER > 1000 06D3FB7B69CC__
#INCLUDED_
删除的内容: (请与我给你的
class CMfcprjView : public CView 原文一致,程序不能随便换
{ 行!!!)
protected: // create from serialization only 删除的内容:
CMfcprjView();
删除的内容:
DECLARE_DYNCREATE(CMfcprjView) #if _MSC_VER > 1000
#pragma once
// Attributes #endif // _MSC_VER > 1000
public:
CMfcprjDoc* GetDocument(); class CMfcprjView : public
CView
{
// Operations protected: // create from
public: serialization only
int mysvd(CDC *pDC); CMfcprjView();
// Overrides
DECLARE_DYNCREATE(C
// ClassWizard generated virtual function overrides MfcprjView)
//{{AFX_VIRTUAL(CMfcprjView)
public: // Attributes
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view CMfcprjDoc*
virtual BOOL PreCreateWindow(CREATESTRUCT& cs); GetDocument();
protected:
// Operations
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); public:
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); int mysvd(CDC *pDC);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // Overrides
// ClassWizard generated
//}}AFX_VIRTUAL
virtual function overrides
//{{AFX_VIRTUAL(CMfcp
// Implementation rjView)
public:
public:
virtual void OnDraw(CDC*
virtual ~CMfcprjView(); pDC); // overridden to draw
#ifdef _DEBUG this view
virtual void AssertValid() const; virtual BOOL
PreCreateWindow(CREATES
virtual void Dump(CDumpContext& dc) const; TRUCT& cs);
#endif protected:
virtual BOOL
OnPreparePrinting(CPrintInfo*
protected: pInfo);
virtual void
// Generated message map functions OnBeginPrinting(CDC* ...pDC,
[1]
132 从 Matlab/Simulink 模型到代码实现

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. 修改生成的视类的实现代码,主要包括:
z 添加头文件 matlab.h;
z 定义静态全局数组;
z 编写函数 mysvd(CDC *pDC)的实现代码; 删除的内容: (
z 在函数 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 };


第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);
134 从 Matlab/Simulink 模型到代码实现

// 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-
pDC->TextOut(0,3*nHeight,"siminar functionality as the MATLAB function"); >TextOut(0,nHeight,"This is a
demo of calling SVD function
pDC->TextOut(0,4*nHeight,"SVD - Singular value decomposition."); directly");

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:");
第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)));
136 从 Matlab/Simulink 模型到代码实现

//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();
}
第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 运行结果


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

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


第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 按 删除的内容: 你的


钮,安装过程结束。 删除的内容: (
删除的内容: 请与你的
删除的内容: )
140 从 Matlab/Simulink 模型到代码实现

图 3.37 Installing

图 3.38 MatrixVB License

安装完 MatrixVB 后,在 MatrixVB 程序组中会有如图 3.39 所示的一些项目。图 3.40


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

删除的内容: r
图 3.39 MatrixVB 程序项
第3章 将 m 程序转换成独立的应用 141

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

删除的内容: L
图 3.41 VB 中调用 MATLAB 的 invhilb 和 plot 函数功能的运行结果

>> plot(invhilb(5))

运行结果如图 3.42 所示。


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

图 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.


页 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()
};

#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章 系统级设计工具 Simulink

Simulink 是 MATLAB 产品中的图形化建模工具,它主要用于系统级的设计和仿真,


同时也可用于算法开发。用 Simulink 搭建的模型,通过 Real-Time Workshop 可以自动生
成面向不同目标的 C 代码。

4.1 图形化建模

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

z 动力学系统

z 控制系统

z 数字信号处理系统

z 电力系统

z 生物系统

z 金融系统

为了建立各种各样的系统的模型,Simulink 提供了一些基本库(由 Simulink 基本模块 删除的内容: (


提供)和针对特定领域的扩展库。用户可以使用这些库中的模块搭建自己的模型。用户为 删除的内容: )
了实现特定领域的系统建模,购买 MATLAB 产品时通常需要选择 Simulink 基本模块和自
己所属领域的扩展模块。例如要做通信系统的建模和仿真,就需要如下几个模块: 删除的内容: 比
z Simulink
z DSP Blockset

z Communications Blockset

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


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

4.2 基本模块库

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

图 4.1 Simulink 基本模块库

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

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

z 用于离散系统的基本模块(Simulink/Discrete),如图 4.3 所示。 删除的内容: (


删除的内容: )
第4章 系统级设计工具 Simulink 145

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

z 函数调用、S-函数和查表运算模块(Simulink/Functions & Tables),如图 4.4 删除的内容: (


所示。 删除的内容: )

图 4.4 函数调用 S-函数和查表运算模块 删除的内容: (

z 数学运算基本模块(Simulink/Math),如图 4.5 所示。 删除的内容: )

z 非线性模块(Simulink/Nonlinear),如图 4.6 所示。 删除的内容: (

z 信号与系统基本模块(Simulink/Signals & Systems),如图 4.7 所示。 删除的内容: )


删除的内容: (
删除的内容: )
146 从 Matlab/Simulink 模型到代码实现

图 4.5 数学运算基本模块

图 4.6 非线性模块
第4章 系统级设计工具 Simulink 147

图 4.7 信号与系统基本模块

z 信宿模块(Simulink/Sinks),如图 4.8 所示。 删除的内容: (


删除的内容: )
删除的内容: ,

图 4.8 信宿模块
148 从 Matlab/Simulink 模型到代码实现

z 信源模块(Simulink/Sources),如图 4.9 所示。 删除的内容: (


删除的内容: )

图 4.9 信源模块

z 子系统基本模块(Simulink/Subsystems),如图 4.10 所示。 删除的内容: (


删除的内容: )

图 4.10 子系统基本模块
第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 仿真的模块库。
150 从 Matlab/Simulink 模型到代码实现

图 4.12 扩展模块库

4.4 Simulink 仿真机理

对 Simulink 系统模型的仿真主要包含两个阶段:
z 初始化阶段
初始化阶段主要完成以下工作:
¾ 每个模块的所有参数都传递给 MATLAB 进行求值,得到的数值作为实际的 删除的内容:
参数使用。 删除的内容:
¾ 展开模型的层次结构,每个子系统被它们所包含的模块替代,带有触发和使 带格式的: 项目符号和编号

能模块的子系统被视为原子单元进行处理。
¾ 检查信号的宽度和模块的连接情况,提取状态和输入/输出依赖关系方面的
信息,确定模块的更新顺序。
第4章 系统级设计工具 Simulink 151

¾ 确定状态的初值和采样时间。
z 运行阶段

初始化之后,仿真进入运行阶段。仿真是由求解器控制的,它计算模块的输出,更新
离散状态,计算连续状态。在采用变步长求解器时,求解器还会确定时间步长。计算连续
状态包含下面两个步骤:
¾ 首先,求解器为待更新的系统提供当前状态、时间和输入值,反过来,求解 删除的内容: 展开模型的层次
结构,每个子系统被它们所
器需要状态导数的值;
包含的模块替代,带有触发
¾ 然后,求解器对状态的导数进行积分,计算新的状态的值。 和使能模块的子系统被视为
状态计算完成后,再进行一次模块的输出更新。这时,一些模块可能会发出过零的警 原子单元进行处理。
告,促使求解器探测出发生过零的准确时间。 <#>检查信号的宽度和模块
Simulink 的仿真过程是在 Simulink 求解器和系统相互作用之下完成的,系统和求解器 的连接情况,提取状态和输
在仿真过程中的对话作用如图 4.13 所示。 入/输出依赖关系方面的信
息,确定模块的更新顺序。
<#>确定状态的初值和采样
时间。
时间、输入、状态 运行阶段初始化之后,仿真
进入运行阶段。仿真是由求
解器控制的,它计算模块的
SIMULINK

输出,更新离散状态,计算
连续状态。在采用变步长求
系统 解器时,求解器还会确定时
计算
求解器 间步长。计算连续状态包含
™ 模块输出
™ 传递模块输出 下面两个步骤:
™ 状态的导数
™ 对状态导数积分
™ 状态的更新
™ 确定采样时间 带格式的
生成
™ 过零事件 带格式的
带格式的: 项目符号和编号
带格式的
删除的内容: 然后,求解器对
输出、导数、事件通知 状态的导数进行积分,计算
新的状态的值。

状态计算完成后,再进行一
图 4.13 系统和求解器之间的对话
次模块的输出更新。这时,
一些模块可能会发出过零的
在图 4.13 中,求解器的作用是传递模块的输出,对状态导数进行积分,并确定采样
警告,促使求解器探测出发
时间。系统的作用是计算模块的输出,对状态进行更新,计算状态的导数,生成过零 生过零的准确时间。
事件。从求解器传递给系统的信息包括时间、输入和当前状态;反过来,系统为求解器提
供模块的输出、状态的更新和状态的导数。整个仿真过程如图 4.14 所示。
152 从 Matlab/Simulink 模型到代码实现

设置初始条件

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

计算输出

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

计算输出

计算导数

结束

图 4.14 Simulink 仿真过程

4.5 重 要 概 念

系统模型搭建完成之后,可以对其进行各种各样的仿真,以测试系统的性能。仿真过
程涉及到一些重要的概念。

过零检测

过零检测通过在系统和求解器之间建立对话的方式工作(如图 4.13 所示)。对话包 删除的内容: (


含的一个内容是事件通知,即系统告知求解器在前一时间步发生了一个事件。事件由过零 删除的内容: )
表示,过零在下列两个条件下产生:
z 信号在上一个时间步改变了符号(含变为 0 和离开 0)。 带格式的: 项目符号和编号

z 模块在上一个时间步改变了模式(例如积分器进入了饱和区段) 。

过零是一个重要的事件,表征系统中的不连续性,例如响应中的跳变。如果仿真中不
对过零进行检测,可能会导致不准确的仿真结果。 当采用变步长求解器时,Simulink 能
够检测到过零(使用固定步长的求解器,Simulink 不检测过零)。当一个模块通知系统前 删除的内容: (
一时间步发生了过零,变步长求解器就会缩小步长,即便绝对误差和相对误差是可接受 删除的内容: )
第4章 系统级设计工具 Simulink 153

的。缩小步长的目的是判定事件发生的准确时间。当然,这样会降低仿真的速度,但这样
做对有些模块来讲是至关重要和必要的,因为这些模块的输出可能表示了一个物理值,它
的零值有着重要的意义。事实上,只有少量的模块能够发出过零事件通知。每个模块发出
专属于自己的事件通知,而且可能与不止一个类型的事件发生关联。
能够产生过零通知的 Simulink 模块如图 4.15 所示。

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

各个模块的过零的类型是有差异的。例如,Abs 模块在输入改变符号时产生一个事
件,而 Saturation 模块能够生成两个不同的过零,一个用于下饱和,一个用于上饱和。
Signals&Systems 库中的 HitCrossing 模块输入穿过零点时产生一个过零,可以用来为 删除的内容: ,当它的
不带过零能力的模块提供过零检测的能力。一些过零只是用来通知求解器模式已经发生了
改变,另外一些则与信号相关,用于触发其他模块。触发包含三种类型:
z 上升沿 – 信号上升到或穿过零或者信号离开零变正; 带格式的: 项目符号和编号

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

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

【例 9】模型如图 4.16 所示,采用 Fcn 模块和 Abs 模块计算输入的绝对值。注意, 删除的内容: 上升沿 – 信号上
升到或穿过零或者信号离开
Fcn 块不支持过零,结果一些拐角点被漏掉了;而由于 Abs 块能够产生过零,每当它的输
零变正;
入改变符号时,都能够精确地得到零点结果,如图 4.17 所示。
如果想关闭对系统模型中能够产生过零事件的模块的过零检测功能,例如为了加快仿 下降沿 – 信号下降到或穿过
零或者信号离开零变负;
真 速 度 , 那 么 可 以 如 图 4.18 所 示 设 置 仿 真 参 数 对 话 框 Advanced 选 项 卡 中 的 选 项
Opimimations/Zero crossing detection 为 Off,但这样可能会导致不正确的仿真结果。对图 <#>双边沿 –上升或下降两者
之一发生。
4.16 所示界面中的模型作上述设定后,仿真结果如图 4.19 所示。
154 从 Matlab/Simulink 模型到代码实现

图 4.16 zerocrossing_detect.mdl

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

图 4.18 关闭过零检测
第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
156 从 Matlab/Simulink 模型到代码实现

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

图 4.21 求解 x − x − 2 = 0 的模型,得到两个解
2

图 4.22 求解 x − x − 2 = 0 的模型,仅得到一个解
2
第4章 系统级设计工具 Simulink 157

对比图 4.21 和图 4.22,可以看到,初始估计值不同,得到的结果可能不同,用户不


是总能得到方程 x 2 − x − 2 = 0 的两个解,除非给出恰当的 Algebraic Constraint 模块的初始
删除的内容: 如
估计值。
删除的内容: ,
如果想在仿真时查看某个模型中是否含有代数环,可按图 4.23 所示那样设置仿真参
数对话框中的诊断选项,设置 Configuration options/Algebraic loop 为 Warning,这样仿真 删除的内容: 我们

时在 MATLAB 命令窗口会出现对代数环的警告信息。例如,如果用户按图 4.23 设置图 删除的内容: 警告信息是否


也要按格式走?
4.21 中 模 型 algebraic_constraint.mdl 的 仿 真 参 数 对 话 框 中 的 诊 断 选 项 , 仿 真
删除的内容: Warning: Block
algebraic_constraint 模型时,MATLAB 命令窗口出现的警告信息如下所示: diagram 'algebraic_constraint'
contains 2 algebraic
Warning: Block diagram 'algebraic_constraint' contains 2 algebraic loop(s). 删除的内容:
Found algebraic loop containing block(s): 删除的内容: loop(s).
'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Initial Guess' Found algebraic loop
'algebraic_constraint/Sum' containing block(s):
'algebraic_constraint/Sum1' 'algebraic_constraint/Algebraic
'algebraic_constraint/Product' Constraint Initial Guess: -
'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Sum' (algebraic variable) 5/Initial

Found algebraic loop containing block(s): 删除的内容:


'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Initial ]Guess' 删除的内容: Guess'
'algebraic_constraint/Sum2' 'algebraic_constraint/Sum'
'algebraic_constraint/Sum1'
'algebraic_constraint/Sum3' 'algebraic_constraint/Product'
'algebraic_constraint/Product1'
'algebraic_constraint/Algebraic
'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Sum' (algebraic variable)
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'
图 4.23 代数环检查
删除的内容:
删除的内容: (algebraic
variable)
158 从 Matlab/Simulink 模型到代码实现

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

在 Simulink 模型中可以集成自己的 C 算法和 m 语言算法。要让 Simulink 模型能够使


用自己的 C 算法或者 m 语言算法,先要对其进行封装。这要求用户必须用 C 语言或者 m
语言编写 S-函数。编写 S-函数有一套固定的规则,这是由 Simulink 的仿真机制决定的。
是用 m 语言还是 C 语言编写,取决于用户的需要。
z C 语言编写的 S- 函数不仅能够用于 Simulink 仿真,也可用于通过 Real-Time

Workshop 转成面向不同目标的代码,而 m 语言编写的 S-函数只能用于 Simulink 删除的内容: 则


仿真。
z 用 C 语言编写 S-函数比用 m 语言复杂,但一般来讲运行速度要快一些,如果速度

是用户关注的焦点,则宜用 C 语言编写 S-函数。


z 用户应尽量采用 Simulink 和各种模块库中的模块来搭建系统模型,除非上述模块

不能满足要求,或者用户确实关注仿真速度,才宜编写 S-函数,以免带来不必要
的错误。
本书我们不讲解怎样编写 S- 函数(关于如何编写 S- 函数,用户可参考 MATLAB 删除的内容: (
Document 安装盘上的 PDF 文档 sfunctions.pdf),而是重点介绍封装自己的 C 算法和 m 语 删除的内容: )
言算法的整个过程。
【例 10】在 Simulink 模型中使用自己的 y = 10 * x 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 *
*================*/
第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;
160 从 Matlab/Simulink 模型到代码实现

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
第4章 系统级设计工具 Simulink 161

步骤 3. 拖放如图 4.24 所示的 Simulink/Functions & Tables 中的 S-Function 模块,创建 删除的内容:


需要使用 y = 10 * x 算法的系统模型,例如想将 x = sin(t ) 放大 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 倍。
162 从 Matlab/Simulink 模型到代码实现

图 4.26 Sine Wave 模块参数设置

图 4.27 S-Function 模块参数设置

图 4.28 修改完成后的 sintx10.mdl


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

图 4.29 sintx10.mdl 仿真结果

【例 11】在 Simulink 模型中使用自己的 y = 10 * x 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);
164 从 Matlab/Simulink 模型到代码实现

%%%%%%%%%%%%%%%%%%%
% 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
第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】是一样的。 修改时首先应该遵守的原
则,因为如果程序有语法错
误,别人会认为我 MATLAB
没有学好;而如果某些文字
表达不好,他们最多说我语
文不过关。。。。。。事实
上如果你做格式修改时,忠
实于原稿,可能不会有什么
逻辑错误(当然会有一些我
未发现的错误),我也不需
要把你改错的东西,再改正
过来。)
带格式的
删除的内容: 22
删除的内容: (
图 4.30 S-Function 模块参数设置
删除的内容: )
删除的内容: 22

4.7 定制自己的 Blockset


删除的内容:
如果用户自己开发了一些模块,在建模时需要经常使用,这时,可以选择将这些模块 删除的内容: [例 10]
封装在自己的 Blockset 中,再将其加在 Simulink Library Browser 里面,就可以像使用标准 删除的内容: [例 11]
模块库那样使用定制模块库中的模块了。 带格式的
【例 12】将【例 10】和【例 11】中的模块封装成 Blockset。步骤如下: 删除的内容: (
步骤 1. 将文件 times10_c 动态库文件(Windows 平台上为 times10_c.dll)、times10_c.c 删除的内容: )
166 从 Matlab/Simulink 模型到代码实现

(这个文件不是必要的,但如不涉及知识产权保护,一般还是将它包括在内,以供用户参 删除的内容: (
考)和 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 中的两个 带格式的


第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 带格式的

所示。
168 从 Matlab/Simulink 模型到代码实现

删除的内容: 分页符

图 4.37 删除输入输出端口后的子系统

图 4.38 封装子系统

图 4.39 Mask Editor 对话框参数设置


第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.
170 从 Matlab/Simulink 模型到代码实现

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

程序说明如下:
z 第 7 行,定义打开模块库的命令,一般为模块库文件名(不带 mdl 扩展名)。 删除的内容: (
z 第 14 行,定义模块库文件名(不带 mdl 扩展名)。 删除的内容: )
z 第 15 行,定义显示在 Simulink Library Browser 中的模块库名称。 删除的内容: (
Simulink Library Browser 在启动的过程中会搜索 MATLAB 的搜索路径下的各个 删除的内容: )
slblocks.m 文件,将其中定义的模块库调入 Simulink Library Browser 中。
步骤 11. 将 e:\material\book\myblksetdemo 添加至 MATLAB 搜索路径,如图 4.43 带格式的

所示。

图 4.43 设置 MATLAB 搜索路径


第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


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

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 所示。
第4章 系统级设计工具 Simulink 173

图 4.47 f14.mdl 仿真结果

图 4.48 bluetooth_voice.mdl
174 从 Matlab/Simulink 模型到代码实现

图 4.49 tpc95.mdl

图 4.50 tpc95.mdl 仿真结果


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

【例 16】图 4.51 所示模型是 GSM 和 EDGE 调制方式的一个比较,它的仿真结果如


图 4.52、图 4.53、图 4.54 和图 4.55 所示。

图 4.51 gsm_edge.mdl
删除的内容: 分页符

图 4.52 GSM 调制星座图


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

图 4.53 GSM/EDGE 调制的频谱


删除的内容: 分页符

图 4.54 滤波后的 EDGE 调制星座图


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

图 4.55 未滤波的 EDGE 调制星座图

【例 17】图 4.56 所示是 IS-95A 移动台呼叫处理模型,其中用到了用来描述有限状态


机的 Stateflow 模型。
178 从 Matlab/Simulink 模型到代码实现

图 4.56 IS-95A 移动台呼叫处理模型


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

【例 18】图 4.57 所示是软件无线电的一个欠采样处理模型。

删除的内容:
图 4.57 softdec.mdl
第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 所示。通过
第5章 Real-Time Workshop 181

Simulink 模型,RTW 能够自动生成面向不同目标系统的执行代码。通过这种方式,可以


方便地建立系统的模型,作为一个动态可执行规范,供各个小组快速地对系统进行检验,
提出改进措施。更为重要的是,自动代码生成的功能实现了从系统设计到实现的完美过
渡,大大减轻了软件工程师的编码工作量。

图 5.2 RTW 提供的产品开发流程

5.2 自动代码生成过程

Real-Time Workshop 的代码生成过程如图 5.3 所示。Real-Time Workshop 是若干执行 删除的内容:


工具和文件的集合。RTW 大多数操作都是在 Matlab 中执行的,也就是说,Matlab 是
图 5.3 RTW 自动代码生成
RTW 运行的环境。当使用 RTW 生成程序代码时, Simulink 框图可以视为程序的规范。 过程
建立一个程序代码的过程中生成以下的文件: 删除的内容: (
z model.rtw:这是一个由 model.mdl 生成的中间文件(model 指用 Simulink 搭建的系 删除的内容: )
统模型的文件名),它是由 Matlab 的内建函数 rtwgen 创建的。model.rtw 文件包 删除的内容: (
含对应于模型 model.mdl 中的每一个块(包含 S-函数块)的记录。这些记录通过 删除的内容: )
花括号和 TLC 关键字“Block”分隔。model.rtw 与 model.mdl 文件非常相似。 删除的内容: (
z 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-函数),那么对这些函 删除的内容: )
182 从 Matlab/Simulink 模型到代码实现

数的调用是在 model.c 中进行的。

图 5.3 RTW 自动代码生成过程

z 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 变量,用具体项
目中的值来代替。
z model.exe:这是已编译的目标程序(这里显示的.exe 扩展名,是 Microsoft 平台特 删除的内容: (
有的)。它是通过安装在本机的编译器和连接器产生的。注意,并不是所有提供 删除的内容: )
的目标最终都生成 exe 执行文件。

5.3 RTW 支持的目标

如果安装了 Real-Time Workshop 模块,在 Simulink 模型的仿真参数对话框中,会出 删除的内容: …


现 Real-Time Workshop 设置页面,如图 5.4 所示。单击 Browse 按钮,可以选择特定的 删除的内容: (
目标。 删除的内容: )
每个目标都对应两个特定的文件: 删除的内容: (
z 系统目标文件(*.tlc),是一个目标语言编译器(Target Language Compiler)。 删除的内容: )
z 模板 makefile 文件(*.tmf)。 删除的内容: (
例 如 , 目 标 Tornado ( VxWorks ) Real-Time Target 对 应 的 系 统 目 标 文 件 和 模 板 删除的内容: )
makefile 文件分别为 tornado.tlc、tornado.tmf。这两个文件在代码生成过程中的作用在 5.2 删除的内容: (
节中已有描述。 删除的内容: )
删除的内容:
第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 文件的 删除的内容: )
目标:
z ASAM-ASAP2 Data Definition Target 只产生一个 ASAP2 文件,而不会生成可执行
184 从 Matlab/Simulink 模型到代码实现

文件;
z 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 删除的内容: on
*
* 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
第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
186 从 Matlab/Simulink 模型到代码实现

/begin RECORD_LAYOUT Lookup1D_UBYTE


NO_AXIS_PTS_X 1 UBYTE
RESERVED 2 UBYTE
AXIS_PTS_X 3 UBYTE INDEX_INCR DIRECT 删除的内容: X
FNC_VALUES 4 UBYTE COLUMN_DIR DIRECT 删除的内容: VALUES
/end RECORD_LAYOUT

/begin RECORD_LAYOUT Lookup1D_BYTE


NO_AXIS_PTS_X 1 UBYTE
RESERVED 2 UBYTE 删除的内容: RESERVED
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 删除的内容: VALUES
/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
第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 删除的内容: RESERVED
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
188 从 Matlab/Simulink 模型到代码实现

/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 删除的内容: RESERVED
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 删除的内容: RESERVED
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 环境中实时 删除的内容: 你
第5章 Real-Time Workshop 189

地运行代码,请选择 Real-Time Windows Target。

RTW Embedded Coder

RTW Embedded Coder 是 MathWorks 提供的基于 RTW 的一个单独的模块产品,它提


供了生成嵌入式代码的一个框架。这种代码对速度、内存和代码量都作了优化。RTW
Embedded Coder 生成的代码适于嵌入式系统的代码实现,它生成的是嵌入式 C 代码。
RTW Embedded Coder 有如下特点:
z 可生成定点代码;

z 可生成浮点代码;

z 对单速率或者多速率系统,都支持异步中断方式;

z 自动生成 S-函数封装模块,使得用户可在 Simulink 中验证 RTW Embedded Coder

生成的代码(软件在回路仿真); 删除的内容:
z 自动生成 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++工程文件。 删除的内容:


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

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


第5章 Real-Time Workshop 191

解决方案 。它在 Microsoft Windows 环境中实时地运行模型,同时在 Simulink 环境中观测


仿真的结果。Real-Time Windows Target 的典型应用包括:
z 实时控制

z 实时的硬件在回路仿真

z 教学为学生树立建模、仿真和测试实时系统及进行迭代设计的整个流程和概念 删除的内容: ─

S-function Target

S-function target,可让用户创建 S-函数模块,该模块可用于其他 Simulink 模型中。S-


function Target 生成的代码格式遵循 Simulink C MEX S-函数 API。 S-function Target 可 删除的内容: target
用于: 删除的内容: :
z 将一个 Simulink 模型转换成一个模块,该模块可用于其他模型中;

z 将一个子系统转换成一个模块;

z 加速仿真;

z 代码重用。

S-function Target 生成的是非内嵌的(noninlined)S-函数,它不能被 RTW Embedded 删除的内容: target


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 查询。
192 从 Matlab/Simulink 模型到代码实现

5.4 RTW 的价值

RTW 的价值在于能够从系统设计的 Simulink 模型直接生成面向目标的代码,减少了


用户编写代码的工作量,对于某些目标用户甚至不需要编写一行代码,例如针对目标
C6701 EVM,就可以完成从编译、连接、下载直至运行的整个过程。
RTW 具有完全可定制的生成过程,可从任意固定步长的模型中生成代码,它的用途
主要体现在以下几个方面:
z 快速仿真;

z 快速原型;

z 实时实现;

z 提供了建立实时程序的框架; 带格式的: 项目符号和编号

z 提供了开放的接口以支持第三方硬件和工具。 带格式的: 项目符号和编号

本书的后续章节将介绍一些产品实现中常用的 Real-Time Workshop 支持的目标。


删除的内容: 提供了开放的接
口以支持第三方硬件和工具
本书的后续章节将介绍一些
产品实现中常用的 Real-Time
Workshop 支持的目标。
第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 模型自动生成面


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

向 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 对用户的价值
在于:
z 有助于实现 DSP 算法原型; 删除的内容:
z 系统级的算法验证; 带格式的: 项目符号和编号

z 从 Simulink 模型到 CCS IDE 工程的无缝转换; 带格式的: 项目符号和编号

z 降低编写 DSP 代码的难度和工作量。 删除的内容: 有助于实现


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 对用户的价值在于: 删除的内容: )
z 用户可以利用 MATLAB 强大的数据分析和可视化功能,节省设计和调试程序的

时间;
z 可以编写用于调试数字信号处理程序的 m 语言批处理脚本,实现调试和分析的自

动化;
z 支持 TI 的 C5000/6000 系列 DSP。
第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 对用户
的价值在于:
z 可以实现对实时数据的自动的高级分析和可视化; 带格式的: 项目符号和编号

z 实现对复杂 DSP 程序的有效验证; 删除的内容: 可以实现对实时


z 支持 TI 的 C5000/6000 系列 DSP。
数据的自动的高级分析和可
视化;
实现对复杂 DSP 程序的有效
验证;
支持 TI 的 C5000/6000 系列
6.3 Developer’s Kit for TI DSP 的安装 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 需要:


z MATLAB 基本模块;

z Simulink 基本模块;

z DSP Blockset;

z Real-Time Workshop;

z Signal Processing Toolbox;

z Texas Instruments Code Composer Studio Integrated Development Environment 1.2 或

更高版本。
另外,
z 为了 Target for C6701 EVM 接口能够下载运行 DSP 程序,用户需要至少一个

TMS320C6701 EVM。如果只是生成面向 C6701 EVM 的工程文件,可以不要 删除的内容: ;


TMS320C6701 EVM。
z 为了使用 Link for CCS IDE 或者 Link for RTDX 接口,需要至少一个 CCS IDE 支

持的 TI DSP 开发系统。Link for CCS IDE 可以使用 CCS IDE 提供的软件仿真器,


但 Link for RTDX 需要支持 RTDX 接口的 C5000/6000 硬件平台。
z 即使是使用 Link for CCS IDE 和 Link for RTDX(这两种接口是 Matlab 和 TI DSP 之
196 从 Matlab/Simulink 模型到代码实现

间的接口),用户也需要:
¾ 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 删除的内容: 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 所示。 删除的内容: 其
删除的内容: 文中的文件名
是否要与程序中一致
带格式的
第6章 面向 TI DSP 的自动代码生成 197

图 6.3 Code Composer Setup

以下为 linkforccsidedemo.m 文件代码: 删除的内容: s


删除的内容: (linkforccsdemo.
1 % linkforccsidedemo.m 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 % ==================================================================
198 从 Matlab/Simulink 模型到代码实现

16 % Intro 删除的内容: ‘…’ ... [1]


17 disp(sprintf(['=================================================\n'…
删除的内容: ‘…‘‘…’’... [2]
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'…
删除的内容: ‘…’ ... [3]
21 ' a DSP application using the full computational power of MATLAB.\n'…
22 ' This can be used to assist DSP debugging and development.\n'… 删除的内容: ‘…’ ... [4]
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'… 删除的内容: ‘…’ ... [5]
28 ' link is created, it is specific to a particular CPU,\n'… 删除的内容: ‘…’ ... [6]
29 ' (i.e. a DSP chip) so selection is required before proceeding\n'… 删除的内容: ‘…’ ... [7]
30 ' In general, the selection processor is only necessary \n'… 删除的内容: ‘…’ ... [8]
31 ' for multiprocessor configurations of Code Composer.\n'… 删除的内容: ‘…’ ... [9]
32 '===========================================================\n\n'])); 删除的内容: ‘…’’…’... [10]
33 disp('--- Press any key to continue ---');
删除的内容: ‘…’ ... [11]
34 pause;
删除的内容: ‘…’ ... [12]
35
删除的内容: ‘…’ ... [13]
36 % =================================================================
删除的内容: ‘…’ ... [14]
37
38 % command line board/processor selection command: ccsboardinfo 删除的内容: ‘…’ ... [15]
39 disp(sprintf(['=================================================\n'… 删除的内容: ‘…‘ ... [16]
40 ' The ''Link for Code Composer(tm) Studio'' provides two tools for\n'… 删除的内容: ‘…’ ... [17]
41 ' selecting a DSP board and processor in multiprocessor\n'… 删除的内容: ‘…‘‘…’’
... [18]
42 ' configurations. First, a command line version called: ''ccsboardinfo'' \n'… 删除的内容: ... [19]
43 ' which prints a list of the available boards and processors.\n'… 删除的内容: ’
44 ' For scripting, this command can return a structure, which\n'… 删除的内容: ‘…’ ... [20]
45 ' can be applied to programmatically select a particular DSP chip.\n'…
删除的内容: ‘
46 '==========================================================\n\n']));
删除的内容: ... [21]
47 disp('--- Press any key to continue: ccsboardinfo ---');
删除的内容: ‘‘…’’…’
... [22]
48 pause;
删除的内容: ‘…’ ... [23]
49 echo on
50 ccsboardinfo 删除的内容: ‘…’ ... [24]
51 echo off; 删除的内容: ‘
52 删除的内容: ... [25]
53 % ================================================================== 删除的内容: ’
54 删除的内容: ‘…’ ... [26]
55 % GUI board/processor selection tool: boardprocsel 删除的内容: ‘…‘ ... [27]
56 disp(sprintf(['================================================\n'… 删除的内容: ‘…’ ... [28]
删除的内容: ‘
删除的内容: … ... [29]
删除的内容: ‘‘…’’…’
... [30]
删除的内容: ‘
删除的内容: ... [31]
删除的内容: ’
第6章 面向 TI DSP 的自动代码生成 199 删除的内容: ‘
删除的内容: ... [32]
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'…
删除的内容: ‘…‘‘…’…’
... [33]
59 ' for the rest of this tutorial. For single processor installations,\n'…
删除的内容: ‘…’ ... [34]
60 ' of Code Composer Studio, simply press ''OK'' to continue.\n’…
61 '=========================================================\n\n'])); 删除的内容: ‘

62 删除的内容: ... [35]


63 disp('--- Press any key to continue, then select a DSP from the GUI: boardprocsel ---'); 删除的内容: ‘
64 删除的内容: ‘
65 pause; 删除的内容: ... [36]
66 echo on 删除的内容: ’
67 [boardNum,procNum] = boardprocsel
删除的内容: ‘
68 echo off
删除的内容: ... [37]
69
删除的内容: ’
70 if isempty(boardNum) | isempty(procNum),
删除的内容: ‘…’ ... [38]
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' ); 删除的内容: ... [39]
74 else 删除的内容: ’…
75 fprintf(1,[ '\n The goal of this selection process is a board number\n' 删除的内容: ‘…’ ... [40]
76 ' and processor number that uniquely identify a particular\n'… 删除的内容: ‘
77 ' target DSP. These values are then applied during the link creation.\n\n' 删除的内容: ... [41]
78 ' You selected board number = %d, and processor number = %d\n\n'],boardNum,procNum); 删除的内容: ’…
79 end
删除的内容: ‘
80 %==================================================================
删除的内容: ... [42]
81 % Object Constructor: ccsdsp
删除的内容: ’
82 disp(sprintf(['================================================\n'…
删除的内容: ‘…’ ... [43]
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'… 删除的内容: ... [44]
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'… 删除的内容: ... [45]
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'… 删除的内容: ‘…‘‘…’’
... [46]
91 ' designated DSP chip. Therefore, it will appear in all commands that\n'…
删除的内容: ... [47]
92 ' follow the object creation. Naturally, in multiprocessor \n'…
删除的内容: ’
93 ' implementations it is possible to have more than one link object.\n'…
删除的内容: ‘…‘‘…’’
... [48]
94 ' NOTE – Before proceeding, your DSP hardware should be reset and \n'…
删除的内容: ... [49]
95 ' configured as needed for operation by Code Code Composer.\n'…
96 '==========================================================\n\n'])); 删除的内容: ’

97 删除的内容: ‘
删除的内容: ... [50]
删除的内容: ’
删除的内容: ‘
删除的内容: ... [51]
删除的内容: ’
删除的内容: ‘…‘‘…’’
... [52]
删除的内容: ... [53]
删除的内容: ’

... [54]
... [55]

... [56]
200 从 Matlab/Simulink 模型到代码实现

98 disp('--- Press any key to continue: ccsdsp ---'); 删除的内容: ‘…‘ ... [59]
99
删除的内容: ‘…’…’…’
... [60]
100 pause;
删除的内容: ’
101 echo on
删除的内容: ‘
102 cc=ccsdsp('boardnum',boardNum, 'procnum',procNum)
删除的内容:
103 echo off
104 %==================================================================
删除的内容: ‘‘…’’…’
... [61]
105 % Visibility of Code Composer
删除的内容: ‘…’ ... [62]
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']));
删除的内容: ‘‘…’’…’
... [63]
118
删除的内容: ‘
119 disp('--- Press any key to continue: visible ---');
120 删除的内容: ... [64]
121 pause; 删除的内容: ‘
122 echo on 删除的内容: ‘
123 cc.visible(1) % Force Code Composer to be visible on the desktop 删除的内容: ... [65]
124 echo off 删除的内容: ‘…’’…’... [66]
125 %================================================================== 删除的内容: ‘…‘‘…’’…’
... [67]
126 % Link Status: info, isrunning, disp 删除的内容: ‘…’ ... [68]
127 disp(sprintf(['================================================\n'…
删除的内容: ‘…‘ ... [69]
128 ' With the link in place, it is now possible from MATLAB to\n'…
删除的内容: ‘…’ ... [70]
129 ' query Code Composer for status on the specified DSP CPU\n'…
删除的内容: ‘…’ ... [71]
130 ' Three methods are available to receive status information: \n'…
删除的内容: ‘…’ ... [72]
131 ' ''info'' – returns a structure of testable Target conditions.\n'…
132 ' ''disp'' – prints a list of information about the target CPU.\n'… 删除的内容: ‘…’ ... [73]
133 ' ''isrunning'' – returns the state (running or halted) of the CPU.\n'… 删除的内容: ‘…‘‘…’’…’
... [74]
134 ' The next segment will demonstrate these methods.\n'… 删除的内容: ‘…‘‘…’’…’
... [75]
135 '===========================================================\n\n'])); 删除的内容: ‘… …‘‘…’’…’
... [76]
136 disp('--- Press any key to continue: info,disp,isrunning ---'); 删除的内容: ‘…’ ... [77]
137 pause; 删除的内容: ‘…’ ... [78]
138 echo on 删除的内容: ‘…‘ ... [79]
删除的内容: ‘…’…‘…’
... [80]
删除的内容: ‘…’…‘…’
... [81]
删除的内容: ‘
删除的内容:
删除的内容: ’
删除的内容: ‘…‘‘…’’…‘‘…’’
... [82]
第6章 面向 TI DSP 的自动代码生成 201 删除的内容: ... [83]
删除的内容: ’
139 disp(cc)
删除的内容: ‘…‘‘…’’
... [84]
140 linkinfo = info(cc)
删除的内容: ... [85]
141 cpurunstatus = isrunning(cc)
删除的内容: ’
142 echo off
143 删除的内容: ‘…’ ... [86]
144 %=================================================================== 删除的内容: ‘
145 删除的内容: ... [87]
146 % Determine family (5x or 6x) 删除的内容: ’
147 sfamily = linkinfo.subfamily; 删除的内容: ‘…’ ... [88]
148 if sfamily >= hex2dec('50') & sfamily < hex2dec('60'), 删除的内容: ‘
149 c5xfamily = (1==1);
删除的内容: ... [89]
150 elseif sfamily >= hex2dec('60') & sfamily < hex2dec('70'),
删除的内容: ’
151 c5xfamily = (1==0);
删除的内容: ‘
152 else
删除的内容: ... [90]
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'… 删除的内容: ... [91]
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'],… 删除的内容: ... [92]
160 linkinfo.family,dec2hex(linkinfo.subfamily),linkinfo.revfamily)); 删除的内容: ’
161
删除的内容: ‘
162 %==================================================================
删除的内容: ... [93]
163
删除的内容: ’
164 % The Code Composer Files: load/open
删除的内容: ‘
165
166 disp(sprintf([‘================================================\n’… 删除的内容: ... [94]
167 删除的内容: ‘‘…’’…’
... [95]
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'… 删除的内容: ... [96]
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'… 删除的内容: ... [97]
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'…
删除的内容: ... [98]
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',… 删除的内容: ... [99]
删除的内容: ’
删除的内容: ‘
删除的内容: ... [100]
删除的内容: ’
删除的内容: ‘…’ ... [101]
202 从 Matlab/Simulink 模型到代码实现
删除的内容: ‘
180 ' (TI)\\cc\\gel. Use menu option File->Load_GEL in Code Composer. \n',… 删除的内容: ... [102]
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'])); 删除的内容: ... [103]
184 disp('--- Load a GEL File(if necessary), then press any key to continue: open ---'); 删除的内容: ’
185 pause;
删除的内容: ‘…’ ... [104]
186 if c5xfamily,
删除的内容: ‘…’ ... [105]
187 echo on
删除的内容: ‘
188 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_54xx.mak')
删除的内容: ... [106]
189 projpath = fileparts(projfile)
190 open(cc,projfile) % Open project file 删除的内容: ‘

191 cd(cc,projpath) % Change working directory of Code Composer(only) 删除的内容: ’…’…’…’…’…’


... [107]
192 echo off 删除的内容: ... [108]
193 elseif cc.info.revfamily > 10, 删除的内容: ’…’…’…’
... [109]
194 echo on 删除的内容: ... [110]
195 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x11.mak') 删除的内容: ’…’…’…’…’…’
... [111]
196 projpath = fileparts(projfile) 删除的内容: ... [112]
197 open(cc,projfile) % Open project file
删除的内容: ’…’…’…’
... [113]
198 cd(cc,projpath) % Change working directory of Code Composer(only)
删除的内容: ... [114]
199 echo off
删除的内容: ’…’…’…’…’…’
... [115]
200 else
删除的内容: ... [116]
201 echo on
202 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x0x.mak') 删除的内容: ’…’…’…’
... [117]
203 projpath = fileparts(projfile) 删除的内容: ... [118]
204 open(cc,projfile) % Open project file 删除的内容: ‘…’ ... [119]
205 cd(cc,projpath) % Change working directory of Code Composer(only) 删除的内容: ‘…’’ ... [120]
206 echo off 删除的内容: ... [121]
207 end 删除的内容: ‘…’ ... [122]
208 %================================================================== 删除的内容: ‘…’ ... [123]
209 % The Code Composer Files: address
删除的内容: ‘
210
删除的内容: ‘‘…’’ ... [124]
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'… 删除的内容: ... [125]
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'… 删除的内容: ‘…’ ... [126]
220 ' The next step will load the generated program file ''a.out''\n'… 删除的内容: ‘…‘‘…’’…’
... [127]
第6章 面向 TI DSP 的自动代码生成 203

221 ' using the ''load'' method. Notice the results of checking\n'… 删除的内容: ‘…‘‘…’’…’
... [128]
222 ' the symbol table for the variable ''ddat'' before and after\n'… 删除的内容: ‘…‘‘…’’…’
... [129]
223 ' the load.\n'… 删除的内容: ‘…’ ... [130]
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 删除的内容: ‘…’ ... [131]
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 删除的内容: ’…’ ... [132]
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 删除的内容: ’…’ ... [133]
236 catch 删除的内容: ’…’ ... [134]
237 echo off 删除的内容: ... [135]
238 warnState = warning(warnState);
删除的内容: ‘… ‘‘…’’
... [136]
239 disp(lasterr);
带格式的
240 240 disp(sprintf(['!!!!! The load of ''a.out'' failed. Please attempt to rebuild it\n'…
删除的内容: ... [137]
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 删除的内容: ... [138]


245 load(cc, 'a.out',40) % Load the target execution file 删除的内容: ’
246 ddatA = address(cc, 'ddat') % Read the address of global: ddat 删除的内容: ‘…’ ... [139]
247 dec2hex(ddatA) % in hexadecimal (address and page) 删除的内容: ’…’ ... [140]
248 echo off 删除的内容: ’…’ ... [141]
249 end 删除的内容: ‘…’ ... [142]
250
删除的内容: ‘…’ ... [143]
251 %===================================================================
删除的内容: ‘…’ ... [144]
252
删除的内容: ‘…’ ... [145]
253 % Halt, run, read
删除的内容: ‘…’ ... [146]
254 disp(sprintf(['================================================\n'…
255 ' With the target code loaded, it is now possible to examine\n'… 删除的内容: ‘…‘‘…’’
... [147]
256 ' and modify data values in the DSP target from MATLAB.\n'… 删除的内容: ... [148]
257 ' If you look at the source file listing in the Code Composer \n'… 删除的内容: ’
258 ' application window, there should be a file labeled:\n'… 删除的内容: ‘…‘‘…’’…’
... [149]
259 ' ''ccstut.c'', which was shipped with this tutorial and included\n'… 删除的内容: ‘…‘‘…’’
... [150]
260 ' in the project. It has two global data arrays: ''ddat'' and \n'… 删除的内容: ... [151]
261 ' ''idat''. They are declared and initialized in lines 10 and 11.\n'… 删除的内容: ’
204 从 Matlab/Simulink 模型到代码实现

262 ' These DSP memory arrays can be accessed directly from\n'… 删除的内容: ‘…’ ... [152]
263 ' MATLAB command line using the ''read'' and ''write'' methods.\n'… 删除的内容: ‘…‘‘…’’…‘‘…’’
... [153]
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'])); ’ ... [154]
269 disp('--- Insert Breakpoint then press any key to continue: halt,restart,read ---'); 删除的内容: ‘…‘‘…’’…’
... [155]
270 pause; 删除的内容: ‘…’ ... [156]
271 try 删除的内容: ‘…‘‘…’’…’
... [157]
272 if c5xfamily, 删除的内容: ‘…’ ... [158]
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 删除的内容: ’…’ ... [159]
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) 删除的内容: ’…’…’…’
... [160]
281 删除的内容:
282 write(cc,address(cc, 'ddat'),single([pi 12.3 exp(-1) sin(pi/4)])) % Modify memory values
283 删除的内容: ’…’…’…’
... [161]
284 write(cc,address(cc, 'idat'),int16([1:4])) 删除的内容: ’…’ ... [162]
285 删除的内容:
286 run(cc, 'runtohalt',20); % Resume execution from breakpoint, then modify
287 删除的内容: ’…’ ... [163]
288 ddatV = read(cc,address(cc, 'ddat'), 'single',4) 删除的内容: ’…’ ... [164]
289 删除的内容:
290 idatV = read(cc,address(cc, 'idat'), 'int16',4)
291 删除的内容: ’…’…’…’
... [165]
292 restart(cc); 删除的内容: ’…’…’…’
... [166]

293 echo off


294 else
295 echo on
296 halt(cc) % halt the CPU (if necessary)
删除的内容: ’…’ ... [167]
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
删除的内容: ’…’…’…’
... [168]
300 ddatV = read(cc,address(cc, 'ddat'), 'double',4) % Should equal initialized value from C-Code
删除的内容:
301
删除的内容: ’…’…’…’
... [169]
第6章 面向 TI DSP 的自动代码生成 205
删除的内容: ’…’ ... [170]
302 idatV = read(cc,address(cc, 'idat'), 'int32',4) 删除的内容: ... [171]
303 删除的内容: ’…’ ... [172]
304 write(cc,address(cc, 'ddat'),double([pi 12.3 exp(-1) sin(pi/4)])) % Modify memory values 删除的内容: ’…’ ... [173]
305 删除的内容: ... [174]
306 write(cc,address(cc, 'idat'),int32([1:4])) 删除的内容: ’…’…’…’
... [175]
307
删除的内容: ’…’…’…’
... [176]
308 run(cc, 'runtohalt',20); % Resume execution from breakpoint, then modify
删除的内容: ‘
309
删除的内容: ... [177]
310 ddatV = read(cc,address(cc, 'ddat'), 'double',4)
删除的内容: ’
311
312 idatV = read(cc,address(cc, 'idat'), 'int32',4) 删除的内容: ‘

313 删除的内容: ... [178]


314 restart(cc); 删除的内容: ’
315 删除的内容: ‘…’ ... [179]
316 echo off 删除的内容: ‘
317 end 删除的内容: ... [180]
318 catch 删除的内容: ’
319 echo off
删除的内容: ‘
320 disp(lasterr);
删除的内容: ... [181]
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'… 删除的内容: ... [182]
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'… 删除的内容: ‘…’ ... [183]
327 'Composer before executing the tutorial.\n'])); 删除的内容: ‘…’ ... [184]
328 error('CCS Tutorial failure'); 删除的内容: ’
329 end 删除的内容: ‘…’ ... [185]
330 删除的内容: ‘…’ ... [186]
331 %===================================================================
删除的内容: ‘
332
删除的内容: ... [187]
333 % regread/regwrite
删除的内容: ’
334 if c5xfamily,
删除的内容: ‘…‘‘…’’
... [188]
335 disp(sprintf([‘================================================\n'…
336 ' For Assembly language programmers, there are also methods\n'… 删除的内容: ... [189]
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'… 删除的内容: ... [190]
340 ' is not memory-mapped and therefore requires a special pair of \n'… 删除的内容: ’
341 ' methods: ''regread'' and ''regwrite''.\n'… 删除的内容: ‘…‘‘…’’…‘‘…’’
... [191]
342 '==========================================================\n\n'])); 删除的内容: ‘…’ ... [192]
206 从 Matlab/Simulink 模型到代码实现

343 disp('--- Press any key to continue: regread/regwrite ---'); 删除的内容: ‘…‘ ... [193]
344 pause;
345 echo on
346 cc.regread('PC', 'binary') 删除的内容: ‘…’…’…’
... [194]
347 cc.regwrite('PC',hex2dec('100'), 'binary') 删除的内容: ‘…’…‘…’…’…’
... [195]
348 echo off
349 else
350 disp(sprintf(['=================================================\n'… 删除的内容: ‘…’ ... [196]
351 ' For Assembly language programmers, there are also methods\n'… 删除的内容: ‘…’ ... [197]
352 ' to access CPU registers: ''regread'' and ''regwrite''.\n'… 删除的内容: ‘…‘‘…’’…‘‘…’’
353 '===========================================================\n\n'])); ’ ... [198]
354 disp('--- Press any key to continue: regread/regwrite ---' ); 删除的内容: ‘…’ ... [199]
355 pause; 删除的内容: ‘…‘ ... [200]
356 echo on
357 tReg = cc.regread('A0', '2scomp') % 2's complement version of A0 删除的内容: ‘…’…’…’…’
... [201]
358 cc.regread('B2', 'binary') % Unsigned version of B2 删除的内容: ‘…’…’…’
... [202]
359 cc.regwrite('A2',tReg, '2scomp') 删除的内容: ‘…’…’…’
... [203]
360 echo off
361 end
362
363 %==================================================================
364
365 % Deleting the link: clear
366 disp(sprintf(['================================================\n'… 删除的内容: ‘…’ ... [204]
367 ' Finally, to delete the link to Code Composer, use\n'… 删除的内容: ‘…’ ... [205]
368 ' ''clear cc''. Note, if a link object exists, manually \n'… 删除的内容: ‘…‘‘…’’…’
... [206]
369 ' exiting Code Composer will not kill the application. It\n'… 删除的内容: ‘…’ ... [207]
370 ' simply moves to the background. Once all link objects\n'… 删除的内容: ‘…’ ... [208]
371 ' have been deleted (or by quiting MATLAB), then\n'…
删除的内容: ‘…’ ... [209]
372 ' the Code Composer Application will be terminated.\n'…
删除的内容: ‘…’ ... [210]
373 ' However, a ''visible'' Code Composer is assumed\n'…
删除的内容: ‘…‘‘…’’…’
... [211]
374 ' to be active and will never be halted by clearing\n'…
删除的内容: ‘…’ ... [212]
375 ' any Maltab links.\n'…
376 '==========================================================\n\n’])); 删除的内容: ‘…’ ... [213]

377 disp('--- Press any key to continue: clear ---' ); 删除的内容: ‘


378 pause; 删除的内容: ‘…‘ ... [214]
379 echo on
380 clear cc 带格式的: 项目符号和编号
381 echo off 删除的内容: echo off
带格式的: 项目符号和编号
程序说明如下: 删除的内容:
第6章 面向 TI DSP 的自动代码生成 207

z 第 13 行,关闭命令本身在 MATLAB 命令窗口的显示。


z 第 49 行,开启命令本身在 MATLAB 命令窗口的显示。
z 第 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

z 第 67 行,打开开发板和处理器选择对话框,选择目标板和目标板上的处理器,如
图 6.4 所示,返回板号和处理器号。 删除的内容: :

>> [boardNum,procNum] = boardprocsel


boardNum = 删除的内容:

procNum =

图 6.4 选择目标板和目标板
上的处理器

图 6.4 选择目标板和目标板上的处理器

z 第 70~79 行,判断返回的目标板号和目标处理器号是否有效。 删除的内容:


z 第 102 行,创建 MATLAB CCSDSP 对象 cc,用于 MATLAB 和所选目标板、目标 删除的内容: ─
处理器之间的连接,同时以后台方式运行 Code Composer Studio。Link for CCS 删除的内容: 和
IDE 接口就是通过操作 CCSDSP 对象来实现的。
208 从 Matlab/Simulink 模型到代码实现

>> 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
所示。
z 第 123 行,调用 cc 的 visible 方法,让读者可以见到 Code Composer Studio 的开发

环境。

>> cc.visible(1)

运行结果如图 6.5 所示。 删除的内容: (对不起,原稿


中该图放错了位置!!!)

图 6.5 cc.visible(1)让开发环境可见

z 第 139 行,显示目标处理器信息: 删除的内容:

>> disp(cc)
CCSDSP Object:
第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 删除的内容:

z 第 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 能否写指定的内存块 图 6.5 cc.visible(1)让开发环
load 下载一个程序文件(*.out,*.obj)到目标处理器 境可见

open 是 装载一个文件到 CCS IDE 删除的内容: linkinfo =


info(cc)运行结果
210 从 Matlab/Simulink 模型到代码实现

read 从目标处理器的指定内存提取数据
删除的内容:
第6章 面向 TI DSP 的自动代码生成 211

续表
函 数 重 载 描 述
regread 读取目标处理器指定寄存器中的数据值
regwrite 向目标处理器指定的寄存器中写入一个值
reset 复位目标处理器
restart 为目标处理器上的当前程序重置程序计数器到起始点
run 执行目标处理器上的程序
set 是 为 CCS IDE 连接设置属性
symbol 从 CCS IDE 返回最近的程序符号表
visible 设置 CCS IDE 窗口的可见性
write 向目标处理器的指定内存写入数据

z 第 141 行,返回目标处理器的运行状态,0 表示没有运行,1 表示处于运行状态。

cpurunstatus = isrunning(cc)

cpurunstatus =

z 第 146~154 行,判断目标处理器是否属于 TI C5000/6000 系列 DSP。 删除的内容: —


z 第 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.
删除的内容: (上述命令格式
z 第 186~207 行,根据目标处理器所属的系列,选择在 CCS IDE 中打开的工程文 请和原稿一致!!!)

件,并将 MATLAB 当前目录指向该工程文件所在的目录。本例中打开的工程文件 删除的内容: ─

如图 6.6 所示。 删除的内容: ,


z 第 227~249 行,向目标处理器下载可执行文件 a.out,返回全局变量 ddat 对应的内 删除的内容: ─
存地址,并将其转换成十六进制格式。
212 从 Matlab/Simulink 模型到代码实现

>> 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

z 第 269~270 行,提示插入一个断点,这时在图 6.6 中的第 3 条 printf 语句处插入一 删除的内容: ─


个断点,然后按任意键继续。 删除的内容: 请
z 第 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]);
第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

z 第 333~361 行,读写指定寄存器的内容。 删除的内容: ─


¾ tReg = cc.regread('A0','2scomp') ,以补码格式读取寄存器 A0 的内容;
214 从 Matlab/Simulink 模型到代码实现

>> tReg = cc.regread('A0','2scomp')


tReg =

¾ cc.regread('B2','binary') ,以无符号格式读取寄存器 B2 的内容; 带格式的: 项目符号和编号

>>cc.regread('B2','binary')
ans =

¾ cc.regwrite('A2',tReg,'2scomp'),向寄存器 A2 写入数据 tReg 的补码格式。 删除的内容: ,

¾ cc.regread('PC','binary'),以无符号格式读取程序计数器的内容; 删除的内容: (

¾ cc.regwrite('PC',hex2dec('100'),'binary') , 向 程 序 计 数 器 写 入 256 的 无 符 号 删除的内容:

格式。 删除的内容: )
z 第 380 行,删除 CCSDSP 对象,断开 Link for CCS IDE。 删除的内容: ,
z 程序中有许多使用 disp 和 pause 语句的地方,那是用于在 MATLAB 命令窗口产生 删除的内容: (
提示信息。 删除的内容: (linkforrtdxde
mo.m 的文本请和原稿一致
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 %
第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, '; 带格式的: 项目符号和编号
216 从 Matlab/Simulink 模型到代码实现

删除的内容:
54 'please select another board'},... 删除的内容:
55 'Selection Error','modal')); uiwait(msgbox({'RTDX is not
supported for the
56 count = count+1; selected board, ';
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
第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
218 从 Matlab/Simulink 模型到代码实现

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 中包含 10 个整数 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');
第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
220 从 Matlab/Simulink 模型到代码实现

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... 删除的内容: % Query for
remaining number of available
226 num_of_msgs = cc.rtdx.msgcount('ochan')
messages in read channel
227 queue...
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
第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

程序说明如下:
z 第 18 行,通过开发板和处理器选择对话框、选择目标板和目标处理器,返回板号

和处理器号。本例假设选择了 C6701 EVM。


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

z 第 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 所示。
z 第 23~80 行,判断所选的处理器是否兼容 RTDX。如果不兼容,清除创建的 删除的内容: ─
CCSDSP 对象,重新选择开发板和处理器,重新创建 CCSDSP 对象,再进行判断
删除的内容: (仅重复 1 次
(仅重复 1 次);如果兼容,判断所选处理器属于 C5X 还是 C6X1X 或者
删除的内容: );
C6X0X,选择对应的下载文件;如果既不是 C5X 也不是 C6X,则清除创建的
删除的内容: (
CCSDSP 对象,重新选择开发板和处理器,重新创建 CCSDSP 对象,再进行判断
删除的内容: 仅重复 1 次)
(仅重复 1 次)。
z 第 81~84 行,如果所选的下载文件不存在,提示错误信息,退出演示程序。 删除的内容: ─

z 第 90~104 行,将当前目录指向目标文件所在目录,调用 cc 的 visible 方法,让读 删除的内容: ─

者可以看到 Code Composer Studio 开发环境,同时向处理器下载目标文件(本例 删除的内容: (


下 载 的 目 标 文 件 为 %MATLABROOT%\toolbox\tiddk\tidemos\rtdxtutorial\c6x\ 删除的内容: 本例下载的目标
文件为
rtdxtutorial_6x0x.out)。
%MATLABROOT%\toolbox\t
z 第 112~123 行,配置 RTDX 通道缓存,打开读写通道(这里的读写通道是相对于 iddk\tidemos\rtdxtutorial\c6x\
rtdxtutorial_
Matlab 而言的。在 Link for RTDX 连接中,Matlab 的写通道,其实是 TI DSP 的读
删除的内容:
通道;Matlab 的写通道,其实是 TI DSP 的读通道)并且使能 RTDX 连接(对于
C54X)。 删除的内容: 6x0x.out)

z 第 131~134 行,设定 Link for RTDX 连接超时时间。 删除的内容: ─

z 第 137 行,显示有关 RTDX 连接的信息。 删除的内容: (

z 第 139~143 行,目标机复位,运行目标程序。 删除的内容: 这里的读写通道


是相对于 Matlab 而言的。在
z 第 152~154 行,使能写通道。
Link for RTDX 连接中,
z 第 156~162 行,通过 RTDX 连接向目标 DSP 写入 10 个 16 位整形数[1 2 3 4 5 6 7 8 Matlab 的写通道,其实是 TI
9 10]。 DSP 的读通道;Matlab 的写
通道,其实是 TI DSP 的读通
z 第 169~170 行,检查读通道的使能状态,返回值应为 0,因为读通道还处于禁止
道)
状态。
删除的内容: (
z 第 172~173 行,返回读通道中的有效消息数,此时的有效消息数应该为 0。
删除的内容: 对于 C54X)
z 第 175~177 行,使能读通道。
删除的内容: 此句没错!!
表 6.2 用于操作 Link for RTDX 的函数 带格式的
函 数 重 载 描 述 删除的内容: ─
address 返回一个符号对应的地址和内存页 删除的内容: ─
clear 是 删除现存的 RTDX 和 CCS IDE 连接,用析构函数终结连接对象
删除的内容: ─
close 关闭已打开的 RTDX 通道
删除的内容: ─
configure 定义 RTDX 通道缓存的大小和数目
删除的内容: ─
删除的内容: ─
删除的内容: ─
第6章 面向 TI DSP 的自动代码生成 223

续表
函 数 重 载 描 述
禁用 RTDX 接口,一个指定的 RTDX 通道或者所有的 RTDX
disable
通道
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 向目标处理器写入一个消息

z 第 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
224 从 Matlab/Simulink 模型到代码实现

puts("\n\n Read Completed ");


for (j=1; j<=20; j++) { 共写入 20 个消息
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) {} 执行完 181 行后,目标机
} 上的程序应该在此循环 删除的内容: 。

z 第 189~190 行,返回读通道中的有效消息数,此时的有效消息数应该是 20。 删除的内容: ─


z 第 192~193 行,读取一个消息,通道中的消息是读一个少一个。 删除的内容: ─

>>outdata = cc.rtdx.readmsg('ochan', 'int16')


outdata =

2 3 4 5 6 7 8 9 10 11

z 第 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

z 第 206~210 行,读取两个消息。 删除的内容: ─

>>outdata = cc.rtdx.readmsg('ochan', 'int16', [2 5],2)


outdata =

[2×5 int16] [2×5 int16]


第6章 面向 TI DSP 的自动代码生成 225

z 第 212~213 行,读取一个消息。 删除的内容: ─

>>outdata = cc.rtdx.readmsg('ochan', 'int16', [10 1])


outdata =

8
9
10
11
12
13
14
15
16
17

z 第 222~223 行,读取一个 5×2 的矩阵(相当于读取一个消息)。 删除的内容: ─


删除的内容: (
>>outdata = cc.rtdx.readmat('ochan', 'int16', [5 2]) 删除的内容: )
outdata =

9 14 删除的内容:
10 15
11 16
12 17
13 18

z 第 225~226 行,返回读通道中的有效消息数,此数应该为 12。 删除的内容: ─


z 第 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
删除的内容: ─

z 第 231~233 行,返回读通道中的有效消息数,此数应该为 10。 删除的内容: ─


z 第 241~242 行,读取一个 10×5 的矩阵(相当于读取五个消息)。 删除的内容: (
删除的内容: )
226 从 Matlab/Simulink 模型到代码实现

删除的内容:
>>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

z 第 244~246 行,返回读通道中的有效消息数,此数应该为 5。 删除的内容: ─


z 第 254~255 行,废除读通道的一个消息。 删除的内容: ─
z 第 257~259 行,返回读通道中的有效消息数,此数应该为 4。 删除的内容: ─
z 第 261~262 行,废除所有的消息。 删除的内容: ─
z 第 264~266 行,返回读通道中的有效消息数,此数应该为 0。 删除的内容: ─
z 第 274~275 行,禁止所有打开的 RTDX 通道。
删除的内容: ─
z 第 277~279 行,如果目标处理器正在运行,则挂起它。
删除的内容: ─
z 第 281~282 行,禁止 RTDX 连接。
删除的内容: ─
z 第 284~287 行,关闭 RTDX 连接读写通道。
删除的内容: ─
z 第 289~291 行,将 CCS IDE 置于后台运行
z 第 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 模型时,可以选用该模块库中的模块。
第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 所 示 : 两 个 正 弦 信 号 y1 = 0.2 sin (2π × 500t ) 和
y 2 = 0.2 sin (2π × 1000t ) 叠加后,通过一个低通滤波器,目的是要滤除 1000Hz 的高频信
删除的内容: 0.2sin(2
带格式的 ... [215]
删除的内容: *
228 从 Matlab/Simulink 模型到代码实现 删除的内容: π
删除的内容: pi
号 , 假 定 采 样 频 率 为 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 删除的内容: 500
所示。 删除的内容: *
删除的内容: *
带格式的
删除的内容: t)
带格式的 ... [216]
删除的内容: 0.2sin(2
删除的内容: *
删除的内容: π

图 6.8 用 C6701 EVM 来实现低通滤波的软硬件试验平台 删除的内容: pi


删除的内容: ×
删除的内容: *
删除的内容: 1000
删除的内容: *
带格式的
删除的内容: t)

图 6.9 低通滤波模型 lfilterwithsimulink.mdl

删除的内容:
删除的内容: 这个有什么关
... [217]
带格式的
删除的内容: ... [218]
带格式的 ... [219]
删除的内容: 0.2sin(2
删除的内容: *
删除的内容: π
删除的内容: pi
删除的内容: ×
删除的内容: *
删除的内容: 500
删除的内容: *
带格式的
图 6.10 y1=0.2sin(2*pi*500*t)参数设置
删除的内容: t)
第6章 面向 TI DSP 的自动代码生成 229

删除的内容: 分页符

删除的内容: *pi
图 6.11 y2=0.2sin(2*pi*500*t)参数设置
带格式的
删除的内容: 0.2sin(2π
删除的内容: ×
删除的内容: *
删除的内容: 1000
删除的内容: *
带格式的
删除的内容: t)

图 6.12 Digital Filter Design 参数设置


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

如图 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
复位)。 删除的内容: ;
删除的内容: (
删除的内容: )
第6章 面向 TI DSP 的自动代码生成 231

图 6.15 lfilterwithc6701.mdl

图 6.16 C6701 EVM ADC 参数设置

图 6.17 C6701 EVM DAC 参数设置


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

按如下步骤设置模型 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.29
图 6.19 选择 Target for C6701 EVM
第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 设置


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

步骤 5. 如图 6.23 所示,使用 Real-Time Workshop 选项卡类别 General code generation 带格式的

options(cont.)的默认设置。 删除的内容:
删除的内容: (
删除的内容: (
删除的内容: cont. )
删除的内容: )
删除的内容: )

图 6.23 General code generation options(cont.)设置

步骤 6. 如图 6.24 所示,使用 Real-Time Workshop 选项卡类别 MATLAB to CCS Link 带格式的

的默认设置。 删除的内容: 6.23

步骤 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 设置


第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 溢出的错误 删除的内容: ,
236 从 Matlab/Simulink 模型到代码实现

提示。这是为什么呢?这是因为模型 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 工程文件


第6章 面向 TI DSP 的自动代码生成 237

带格式的
删除的内容: *
删除的内容: *
带格式的
删除的内容: sin(2
删除的内容: π
删除的内容: ×
删除的内容: pi
删除的内容: 500
删除的内容: *
图 6.29 切贝雪夫 I 型设计
删除的内容: t)
步骤 10. 启动两个向声卡的 Line Out 端口输出波形的波形发生器。如图 6.30 所示设置 带格式的
参数。 删除的内容: 6.29
>> daqfcngen 删除的内容: (
删除的内容: )
带格式的
删除的内容: (
带格式的
删除的内容: 2
删除的内容: *
删除的内容: π
删除的内容: pi
删除的内容: ×
图 6.30 y=sin(2*pi*500*t)
删除的内容: *
波形发生器 函数 daqfcngen 由数据采集工具箱 提供,它位于%MATLABROOT%\ 删除的内容: 500
toolbox\daq\daqdemos\daqfcngen.m 中。daqfcngen 可以通过声卡的 Line Out 端口向外输出 删除的内容: *
一个波形。如图 6.31 所示设置波形发生器的参数,然后单击 Start 按钮(单击之后 Start 按 删除的内容: t)
钮变为 Stop 按钮),目的是生成信号 y1=0.2sin(2*pi*500*t)。 带格式的
删除的内容: 0.2sin(2
删除的内容: *
删除的内容: π
删除的内容: pi
删除的内容: ×
带格式的 ... [220]
238 从 Matlab/Simulink 模型到代码实现 删除的内容: *
删除的内容: 500
删除的内容: *
带格式的
删除的内容: t)
删除的内容: 6.30
删除的内容: 那样
删除的内容: (…) ... [221]
删除的内容: 0.2sin(2
删除的内容: *

图 6.31 y1=0.2sin(2*pi*500*t) 删除的内容: π


删除的内容: pi
再次使用命令 daqfcngen,启动另一个向声卡的 Line Out 端口输出波形的波形发生
删除的内容: ×
器,并且如图 6.32 所示设置参数,然后单击 Start 按钮(单击之后 Start 按钮变为 Stop 按
删除的内容: *
钮),目的是生成信号 y2=0.2sin(2*pi*1000*t)。
删除的内容: 1000
>>daqfcngen 删除的内容: *
带格式的
删除的内容: t)
带格式的 ... [222]
带格式的 ... [223]
删除的内容: 0.2sin(2×
删除的内容: *
删除的内容: π
删除的内容: pi
删除的内容: ×
图 6.32 y2=0.2sin(2*pi*1000*t)
删除的内容: *
由图 6.8 所示的硬件连接方式可知,实际上我们已经向 C6701 EVM 的 Line In 端口输 删除的内容: 1000×
入了信号 y=y1+y2=0.2[sin(2*pi*500*t) + sin(2*pi*1000*t)],当然幅度会有变化,这取决于 删除的内容: *
声卡的声量调节按钮。y 就是待处理的信号,它经过了在 C6701 EVM 上运行的图 6.15 所 删除的内容: t)
示模型的处理(先经过 AD 变换,再低通滤波,然后再 DA 输出),滤波后的信号会向 带格式的
C6701 EVM 的 Line Out 端口输出。由图 6.8 所示的硬件连接方式,滤波后的信号会通过 带格式的 ... [224]
Line In 端口向声卡输入。 删除的内容: sin(2
步骤 11. 启动一个显示声卡的 Line In 端口输入波形的示波器。 删除的内容: *

>> daqscope 删除的内容: π


删除的内容: pi
示波器函数 daqscope 由数据采集工具箱提供,它位于%MATLABROOT%\toolbox\daq\
删除的内容: ×
daqdemos\daqscope.m 中。daqscope 可以显示声卡的 Line In 端口的输入波形。单击图 6.33
删除的内容: *
所示界面中的启动按钮,并且调节声卡的声量调节按钮,我们可以看到类似于图 6.34 的
删除的内容: 500
一个正弦波形,其频率是 500Hz(f=7.3×44100/644.714=499.34),证明 1000Hz 的正弦信
删除的内容: *
号已被滤除。
带格式的
删除的内容: t)
带格式的
删除的内容: sin(2
删除的内容: *
删除的内容: π
删除的内容: pi
删除的内容: ×
删除的内容: *

带格式的

... [225]
带格式的

... [226]
第6章 面向 TI DSP 的自动代码生成 239

图 6.33 示波器

图 6.34 500Hz 正弦信号

如果此时直接将声卡的 Line Out 和 Line In 连接,可以看到类似于图 6.35 所示的信 删除的内容: 我们


号,它是 500Hz 和 1000Hz 两个正弦的叠加。

图 6.35 500Hz 和 1000Hz 两个正弦的叠加


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

>> 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
第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. 删除的内容:
242 从 Matlab/Simulink 模型到代码实现

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.


删除的内容: 研发
第7章 面向 Xilinx FPGA 的自动代码生成 删除的内容: w
删除的内容: <#>
<#>
带格式的: 项目符号和编号
为了加速在通信和多媒体领域的创新和研发,MathWorks 公司和 Xilinx 公司合作开发 删除的内容: <#>
了基于 Simulink 的 FPGA 实现工具 System Generator for Simulink。通过这一工具,结合 删除的内容: <#>。
Simulink 和 Matlab,MathWorks 公司向用户提供了一个无缝的自上而下的 FGPA 解决方 删除的内容: <#>
案。用户可以: <#>
<#>用 System Generator for
z 用 Simulink 开发 DSP 算法;
Simulink 自动将 Simulink 模
z 用 System Generator for Simulink 自动将 Simulink 模型转成面向 Xilinx FPGA 的 型转成面向 Xilinx FPGA 的
VHDL 代码; VHDL 代码;

z 使用 Xilinx 公司提供的 IP 核。 删除的内容: <#>。


删除的内容: <#>

7.1 对传统 FPGA 设计方式的挑战

传统的 FPGA 设计方式如图 7.1 所示。DSP 的设计小组如果想用 FPGA 来实现自己的


设计,只能是先用 Simulink 或其他工具搭建和仿真系统及算法,等仿真正确之后,将系统
结构的设计方案提交给 FPGA 的设计工程师。FPGA 的设计工程师再手工地将系统模型用
VHDL 语言来描述,同时创建测试平台,用来验证自己的 FPGA 实现方式和 Simulink 系统
级的仿真结果是否相符。在得到系统最优的 FPGA 实现之前可能会有很多的反复。只有当
FPGA 实现方式和 Simulink 系统级的仿真结果相符之后,FPGA 代码才可用来做综合和
实现。

删除的内容:
删除的内容:
删除的内容: 可否能把图中
“设计叠代”改为“设计迭
图 7.1 传统的 FPGA 设计方式 代”
带格式的
第7章 面向 Xilinx FPGA 的自动代码生成 243

现在,有了 System Generator for Simulink 工具,DSP 的设计小组就可以用它从 删除的内容:


Simulink 模型直接自动地生成经过优化的可综合的 FPGA 实现代码。这样的设计流程大大 删除的内容: System
Generator for Simulink
地缩短了产品的开发时间,排除了以前可能而且经常出现的与 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 代码。
244 从 Matlab/Simulink 模型到代码实现

删除的内容: (
图 7.3 Xilinx Blockset
删除的内容: )
Xilinx Blockset 提供的模块包括:
z Basic Elements(基本模块),如图 7.4 所示。

删除的内容:
删除的内容: (
删除的内容: )
删除的内容:
删除的内容: 此图在原稿的
Word 文档中就是半黑状
图 7.4 Basic Elements(基本模块) 带格式的
z DSP(滤波和 FFT 模块),如图 7.5 所示。 删除的内容: (
删除的内容: )
第7章 面向 Xilinx FPGA 的自动代码生成 245

图 7.5 DSP(滤波和 FFT 模块)

z Math(数学模块),如图 7.6 所示, 删除的内容: (


删除的内容: )

图 7.6 Math(数学模块)

z Memory(内存模块),如图 7.7 所示。 删除的内容: (

z Matlab IO(接口模块),如图 7.8 所示。 删除的内容: )


删除的内容: (
删除的内容: )
246 从 Matlab/Simulink 模型到代码实现

删除的内容:

图 7.7 Memory(内存模块)

删除的内容:
删除的内容: (…) ... [1]
图 7.8 Matlab IO(接口模块) 删除的内容: 此图在原稿的
Word 文档中就是半黑状
用于 FPGA 设计的 Simulink 模型基本框架如图 7.9 所示。 删除的内容: (…) ... [2]
第7章 面向 Xilinx FPGA 的自动代码生成 247

图 7.9 用于 FPGA 设计的 Simulink 模型

其中,
z 通常的 Simulink 模块是指除 Xilinx Blockset 模块之外的其他 Simulink 模块。
删除的内容: (
z 位于 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 代码的自动生成 图 7.10 firandmac.mdl(这个
过程。 图不宜太小,太小读者看不
清楚!!)
【例 22】图 7.10 所示是两种实现 FIR 滤波的 FPGA 设计的比较,一种实现方法是直
删除的内容: Xilinx Blockset
接利用 Xilinx Blockset 提供的 FIR 模块,另一种实现方法是用 Xilinx Blockset 提供的基本 提供的 FIR 模块,
模块来搭建 FIR 的滤波实现。仿真的结果表明两种实现方法可以达到相同的效果。 删除的内容:
图 7.10 中模块 Din 的参数设置如图 7.11 所示;模块 FIR 的参数设置如图 7.12 所示;
删除的内容: 另一种实现方法
模块 Dout 的参数设置如图 7.13 所示;模块 Dout MAC 的参数设置如图 7.14 所示;模块 是用 Xilinx Blockset 提供的
MAC Based FIR 是一个子系统,它的组成如图 7.15 所示。 基本模块来搭建 FIR 的滤波
实现,仿真的结果表明两种
实现方法可以达到相同的效
果。
删除的内容:
删除的内容: ,
删除的内容: ,
删除的内容: ,
删除的内容: ,
248 从 Matlab/Simulink 模型到代码实现

图 7.10 firandmac.mdl

删除的内容: (
图 7.11 Din 模块(Gateway In 模块)参数设置
删除的内容: )
第7章 面向 Xilinx FPGA 的自动代码生成 249

图 7.12 FIR 模块参数设置


删除的内容: 分页符

删除的内容: (
图 7.13 Dout 模块(Gateway Out 模块)参数设置
删除的内容: )

删除的内容: (
图 7.14 Dout MAC 模块(Gateway Out 模块)参数设置
删除的内容: )
250 从 Matlab/Simulink 模型到代码实现

图 7.15 MAC Based FIR 子系统

图 7.15 中的 Controller 模块和 MAC 模块都是一个子系统,它们的组成分别如图 7.16


和图 7.17 所示。

图 7.16 Controller 子系统


删除的内容: 分页符

图 7.17 MAC 子系统


第7章 面向 Xilinx FPGA 的自动代码生成 251

对图 7.10 中所示模型 firandmac.mdl 进行 Simulink 仿真,结果如图 7.18 所示,其中


coef = [3 5 7 0] ,仿真参数的设置如图 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 所示的对话框。
252 从 Matlab/Simulink 模型到代码实现

图 7.20 System Generator 参数设置

图 7.20 中各个设置项目的可选项如下:

Xilinx Product Family

System Generator for Simulink V1.0 工具支持的 Xilinx FPGA 系列包括:


z Virtex
z 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 模型。
第7章 面向 Xilinx FPGA 的自动代码生成 253

这个选项在选择定点宽度,或者用定点方式仿真 FPGA 设计没有得到期望的结果时


非常有用。如果用户使用定点仿真的结果不正确,用户可以选择以双精度浮点的方式仿
真整个系统或特定的某些模块,这将有助于用户发现 FPGA 设计的哪一部分存在量化
错误。
用户很容易区分 FPGA 设计中的哪些模块被设置为 override with doubles,因为当它被
设置时,受影响的 Xilinx 模块会显示为灰色,而不是显示为正常的蓝色或者黄色。
zAccording to Block Masks
进行 Simulink 仿真时,FPGA 设计部分根据模块的屏蔽情况,使用双精度浮点信号取
代定点信号。
zEverywhere in Subsystem
进行 Simulink 仿真时,FPGA 设计部分在子系统中使用双精度浮点信号取代定点
信号。
zNowhere in Subsystem
进行 Simulink 仿真时,FPGA 设计部分在子系统中不使用双精度浮点信号取代定点
信号。

Generate Cores

选择在生成 VHDL 代码的过程中,是否生成 Xilinx LogiCOREs。


z According to Block Masks
根据模块的屏蔽情况生成 Xilinx LogiCOREs。
z Everywhere Available
在任何可能的地方,都生成 Xilinx LogiCOREs。
z 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 所示的信 删除的内容: )
息框。 删除的内容: ,
删除的内容: 完成
254 从 Matlab/Simulink 模型到代码实现

图 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
第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 的内容类似于下文,它是综合时需要的文件的列表。 删除的内容: 图 7.17

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
256 从 Matlab/Simulink 模型到代码实现

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 所 删除的内容: 7.10

示界面中添加一个 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章 面向 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。 删除的内容: 、
第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 所示,它支持: 删除的内容: )
z 中断控制

z 速率转换

z 异步缓存读取

z 任务间同步

z 异步缓存写入
第8章 面向 VxWorks 的代码生成 259

图 8.1 VxWorks 支持库

图 8.2 Asynchronous Support 库

VxWorks 支持库的第二个子库 IO Devices 库,如图 8.3 所示,包含对如下驱动程序的


支持:
z Matrix MS-AD12
z Matrix MS-DA12
z VME Microsystems VMIVM-3115-1
z Xycom XVME-500/590
z Xycom XVME-505/595
260 从 Matlab/Simulink 模型到代码实现

图 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 板,用
以和外部的硬件通信。

删除的内容: (没办法!,
你可以用 Visio 画一个)
删除的内容: (
图 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 所示。 删除的内容: )


删除的内容:
第8章 面向 VxWorks 的代码生成 261

删除的内容: (
图 8.5 (VxWorks) Real-Time Target 的运行结构
删除的内容: )
StethoScope 是 MATLAB 的第三方厂商 Real-Time Innovations, Inc.提供的一个实时的 删除的内容: (你自己想办
数 据 采 集 、 性 能 分 析 图 形 化 工 具 , 可 用 它 来 观 测 Real-Time Workshop\Tornado 法!)
(VxWorks) Real-Time Target 目标程序变量的实时变化。StethoScope 可用于: 删除的内容:
z 数据的实时采集和显示; 删除的内容:
z 观测变量的实时变化; 删除的内容: (
z 采集、存储和归档数据供以后分析; 删除的内容: )
z 以 MATLAB 格式输出数据;

z 测量和改善实时 VxWorks 程序的性能。

主机进程

主机上也有两个进程用于和目标机上的实时程序通信(如图 8.5 所示): 删除的内容: (


z 运行于外部模式的 Simulink 删除的内容: )
当 Simulink 运行于外部模式时,用户可以修改模块参数,Simulink 会调用外部接口
MEX-文件(例如在 Windows 平台上通常是 ext_com.dll),将新参数下载到 VxWorks 目 删除的内容: (
标机中。 删除的内容: )
z StethoScope 用户接口模块

这个模块和运行在 VxWorks 目标机上的 StethoScope 实时模块通信,用以获取模型的


数据信息。

目标机上的 VxWorks 任务

对于多采样速率模型,用户可以以单任务模式或者多任务模式生成实时程序(对于单 删除的内容: (
采样率模型,则只能生成单任务模式的实时程序),这可通过仿真参数设置对话框的 删除的内容: )
262 从 Matlab/Simulink 模型到代码实现

Solver 选项卡的模式设置来选择,如图 8.6 所示。

图 8.6 模式选择

两种模式需要的主程序代码都在文件%MATLABROOT%\rtw\c\tornado\rt_main.c 中。 删除的内容:
Tornado(VxWorks)Real-Time Target 在生成代码的过程中,会编译和连接 rt_main.c 文件 删除的内容: (
代码。 删除的内容: )
z 单任务 删除的内容:
默认方式下,模型运行在单任务 tSingleRate 模式。这种方式可以提供最佳的性能。任 删除的内容: ,
务 tSingleRate 以模型的基采样速率(最高采样速率)运行,同时执行那些低采样模块需要 删除的内容: (
的代码。任务 tSingleRate 的执行通常被一个 VxWorks semTake 调用阻塞,直到时钟中断 删除的内容: )
发生,中断服务程序调用 semGive,才能导致 semTake 调用返回。一旦使能,任务
tSingleRate 执行一个时间步的模型代码,然后循环等待对 semTake 的再一次调用。默认方
删除的内容: (
式下,任务 tSingleRate 运行在一个相对较高的优先级(30),这样可以不被后台系统任务
删除的内容: )
所中断。
删除的内容: (
z 多任务
删除的内容: )
用户也可以选择让模型运行在多任务模式下,一个任务对应模型的一种采样速率(如
删除的内容: —
图 8.5 所示):
删除的内容: (
¾ tBaseRate ——这个任务运行对应基速率(最高采样速率)的模型组件代
删除的内容: )
码。默认方式下,它运行在较高的优先级(30),不被后台系统任务所
删除的内容: (
中断。
删除的内容: )
¾ tRaten ——模型中其他的(基速率除外)每一种采样速率都对应一个独立的任
删除的内容: 以
务,分别命名为 tRate1、tRate2、……、tRaten,它们对应的采样速率依次减
带格式的
慢,优先级也依次降低一级。tRate1 优先级最高,tRaten 的优先级最低(当
删除的内容: —
然 tRate1 的优先级比 tBaseRate 低)。
删除的内容: (
删除的内容: )
第8章 面向 VxWorks 的代码生成 263

z用于和主机通信的任务
如果在生成 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 模型。


删除的内容:
264 从 Matlab/Simulink 模型到代码实现

添加设备驱动模块

运行在 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 项目信息。
第8章 面向 VxWorks 的代码生成 265

图 8.8 F-14 飞控系统模型%MATLABROOT%\toolbox\simulink\simdemos\aerospace\f14.mdl

z VxWorks 配置
用户必须给定目标机和目标机 CPU 的类型,目标类型用于选择适当的交叉编译器和
连接器,CPU 类型用于定义宏 CPU,许多 VxWorks 头文件需要使用这些宏定义。关于如
何正确给定目标机和目标机 CPU 的类型,请参阅 VxWorks 相关文档。目标机和目标机
CPU 的类型信息在 tornado.tmf 中给定,由
#-------------- VxWorks Configuration --------------
标识。请按实际情况修改如下几行: 删除的内容: ,

VX_TARGET_TYPE = 68k
CPU_TYPE = MC68040

z 自动下载配置
为了在编译的过程中完成自动下载的功能,必须正确指定目标名和 Tornado Target
Server 主机名。请根据实际情况修改如下的宏定义:

#-------------- Macros for Downloading to Target--------------

TARGET = targetname
266 从 Matlab/Simulink 模型到代码实现

TGTSVR_HOST = hostname

z 工具位置
为了定位在编译过程中需要使用的 Tornado 工具程序,必须在环境变量或者模板
makefile 文件 tornado.tmf 中指定如下 3 个宏: 删除的内容: 三

#-------------- Tool Locations --------------

WIND_BASE = c:/Tornado
WIND_HOST_TYPE = x86–win32
WIND_REGISTRY = $(COMPUTERNAME)

请根据实际情况进行修改。

程序的生成、编译、连接和下载

如果用户已经搭建了 Simulink 模型,并且添加了适当的设备驱动模块,配置好了模板


makefile 文件,那么用户就可以设置编译连接选项,激活编译连接过程。
z 指定编译连接选项

使用 模型 仿 真参 数设 置 对话 框的 Solver 选 项卡 (如 图 8.9 所示 ) 和 Real-Time 删除的内容: (


Workshop 选项卡(如图 8.10 所示),指定编译连接选项。 删除的内容: )
删除的内容: (
删除的内容: )

图 8.9 仿真参数 Solver 设置

请在 Solver 选项卡中将求解器类型选择为 Fixed-step,并选择适当的积分算法。如果


模型只有离散状态,请将积分算法选择为 discrete (no continuous status),这样可以加快 删除的内容: (
程序的执行速度。 删除的内容: )
第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
z 代码生成选项
268 从 Matlab/Simulink 模型到代码实现

为了设置 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:选择该项,启动代码的自动下载。
z 激活编译连接过程

单击模型参数对话框 Real-Time Workshop 选项卡 Target Configuration 设置类别中的


第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 工具手工完成下载和运行的过程。这需要做如下工作: 删除的内容: )
z 建立主机和 VxWorks 目标机之间的通信连接 删除的内容:
在完成对模型的编译连接过程之后,用户可以启动主机和 VxWorks 目标机之间的连 删除的内容: (
接,即启动主机上 Target Server 和 VxWorks 目标机上的 Target Agent 之间的通信连接。这 删除的内容: )
可在 Tornado 集成开发环境中实现,也可在 DOS 命令窗口实现。如在 DOS 命令窗口实 删除的内容: (
现,请使用如下命令行: 删除的内容: )
删除的内容: (
tgtsvr target_network_name
删除的内容: )
删除的内容: /* Function:
z 将目标文件从主机下载到 VxWorks 目标机 rt_main
在 Tornado 集成开发环境或者 DOS 命令窗口中启动 Tornado 工具 WindSh,再在 ======================
======================
WindSh 窗口执行如下命令: =======
* Abstract:
ld <model.lo * Initialize the Simulink
model pointed to by
"model_name" and start
当然,如果在编译连接的过程中选择了支持 StethoScope ,用户还需要下载支持 * model execution.
*
StethoScope 需要的目标文件 libxdr.so、libutilstssip.so 和 libscope.so。 * This routine spawns a task
z 运行程序 to execute the passed model. It
will
VxWorks 实时程序定义了一个函数 rt_main(),用来创建执行模型代码、完成与 * optionally initialize
Simulink 的通信(如果选择了外部模式方式)及初始化 StethoScope(如果选择了支持 StethoScope (via
ScopeInitServer), if it
StethoScope ) 的 任 务 。 rt_main 函 数 在 文 件 rt_main.c 中 定 义 , 这 个 文 件 位 于 目 录 * hasn't already been done. It
%MATLABROOT%\rtw\c\tornado 中。 also optionally sets up external
mode
* communications channels
/* Function: rt_main =========================================================== to Simulink.
* Abstract: *
* Parameters: ... [1]
270 从 Matlab/Simulink 模型到代码实现

* 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)
*
第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.
*/
272 从 Matlab/Simulink 模型到代码实现

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;
第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");
274 从 Matlab/Simulink 模型到代码实现

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 *
************************/
第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
276 从 Matlab/Simulink 模型到代码实现

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
第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*/
}
278 从 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);
第8章 面向 VxWorks 的代码生成 279

return(EXIT_SUCCESS);
} /* end rt_main */
删除的内容: in */
(程序文本要与原稿一
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
z

指向模型产生代码入口点函数的指针,这个函数和 Simulink 模型同名,它的指针保存


在模型的 SimStruct 结构中。
z optStr
选 项 字 符 串 用 于 指 定 终 止 时 间 ( -tf ) 和 在 外 部 模 式 时 , 运 行 前 是 否 等 待 来 自 删除的内容: (
Simulink 的消息的触发(-w)。例如,“-tf 20 -w”表示程序运行 20 秒,运行之前等待 删除的内容: )
来自 Simulink 外部模式控制面板的消息的触发。 删除的内容: (

zscopeInstallString 删除的内容: )
用于指定将哪些信号安装到 StethoScope 的字符串,可能的值包括: 删除的内容: (这句没问
题!!)
¾ NULL——不安装任何信号,这是默认设置;
¾ “*”——安装所有信号; 删除的内容: ─

¾ “[A-Z]*”——安装名称以大写字母开头的模块输出的信号; 删除的内容: ─
¾ 指定其他任何字符串,将安装名称为该字符串的模块输出的信号。 删除的内容: ─
scopeFullName
z

这个参数决定 StethoScope 是用完整的层次模块名,还是仅用模块名标记信号。可能


的值为:
¾ 1——使用完整的模块名; 删除的内容: ─
¾ 0——仅用模块名,这是默认设置值。 删除的内容: ─
如果程序中有一个模块或者 S-函数的多个实例,请使用完整的模块名标记信号。
zpriority
指定程序最高优先级任务(tBaseRate)的优先级。 删除的内容: (

port
z 删除的内容: )
外部模式连接使用的 TCP 端口号,有效值为 256~65535,默认值为 17725。 删除的内容: ─
用户也可以在 tornado.tmf 中定义宏 PROGRAM_OPTS,传递-w 和-tf 选项给 rt_main
函数。例如: 删除的内容: ,
280 从 Matlab/Simulink 模型到代码实现

ROGRAM_OPTS = "-tf inf -w” 删除的内容:

在WindSh窗口中调用rt_main函数,开始运行程序。例如: 删除的内容: ,

sp(rt_main, model, "-tf 20 -w", "*", 0, 30, 17725)

z 开始运行 model 模型
z 指定终止时间为 20 秒
z 提供 StethoScope 对所有模块输出信号的访问
z 仅用模块名标记信号
z 使用默认优先级(30)作为 tBaseRate 任务的优先级 删除的内容: (
z 使用 TCP 端口号的默认值,17725 删除的内容: )
页 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.
*/
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]);
}

/*
* 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) !=


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]);
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
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
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*/
}

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
第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。 删除的内容: X
MATLAB R12.1 总共包含大概 60 个模块,面向各个行业的应用。在 MATLAB 的命 删除的内容: X
令窗口输入 ver,可查看各个模块的版本信息。例如在 MATLAB R12.1 的命令窗口输入 删除的内容: 其它
ver 命令,可以看到如下的信息(取决于安装了多少个模块): 删除的内容: 键入
删除的内容: 键入
>> ver
删除的内容: (
-------------------------------------------------- MATLAB 整个产品 删除的内容: 您
MATLAB Version 6.1.0.450 (R12.1) on PCWIN 的发布版本是 12.1
MATLAB License Number: DEMO 删除的内容: )
--------------------------------------------------
MATLAB Toolbox Version 6.1 (R12.1) 18-May-2001
Simulink MATLAB 基本 Version 4.1 (R12.1) 06-Apr-2001
模块的版本是 6.1
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
282 从 Matlab/Simulink 模型到代码实现

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 删除的内容:
1
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
第9章 面向 DSP 和通信行业的应用 283

删除的内容:
9.2 MATLAB R12.1 中适用于 删除的内容:

DSP 和通信行业的模块

DSP/通信产品的开发通常包含三个重要的阶段:算法的设计和分析、系统级设计与仿 删除的内容: /
真、实现。在 MATLAB 产品家族中,有不同的模块对这三个阶段进行支持:
z 算法设计与分析

¾ MATLAB 基本模块
¾ Communications Toolbox
¾ Filter Design Toolbox
¾ Image Processing Toolbox
¾ MATLAB C/C++ Math Library
¾ MATLAB C/C++ Graphics Library
¾ Signal Processing Toolbox
¾ Wavelet Toolbox
z 系统级设计与仿真 删除的内容: 与
¾ Simulink
¾ Stateflow
¾ CDMA Reference Blockset
¾ Communications Blockset
¾ DSP Blockset
¾ Motorola DSP Developer’s Kit
¾ Xilinx Blockset
¾ Altera DSP Builder
z 实现
¾ 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
284 从 Matlab/Simulink 模型到代码实现

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
第9章 面向 DSP 和通信行业的应用 285

0 0 -4.8990 删除的内容: %
删除的内容: (程序文本请与
>> rankofA=rank(A) 原稿一致!!!)
删除的内容: function
rankofA = varargout =
pwelch(x,win,noverlap,varargi
n)
3 %PWELCH Power Spectral
Density estimate via Welch's
算法开发 method.
% Pxx = PWELCH(X)
returns the Power Spectral
以下所列是用 m 语言实现的功率谱估计的 Welch 方法(%MATLABROOT%\toolbox\ Density (PSD) estimate,
% Pxx, of a discrete-time
signal\signal\pwelch.m)。 signal vector X using Welch's
averaged,
% modified periodogram
function varargout = pwelch(x,win,noverlap,varargin)
method. By default, X is
%PWELCH Power Spectral Density estimate via Welch's method. divided into eight
% Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate, % sections with 50% overlap,
each section is windowed with
% Pxx, of a discrete-time signal vector X using Welch's averaged,
a Hamming
% modified periodogram method. By default, X is divided into eight % window and eight modified
% sections with 50% overlap, each section is windowed with a Hamming periodograms are computed
and averaged.
% window and eight modified periodograms are computed and averaged.
%
% % If the length of X is such
% If the length of X is such that it cannot be divided exactly into that it cannot be divided
exactly into
% eight sections with 50% overlap, X will be truncated accordingly. % eight sections with 50%
% overlap, X will be truncated
% Pxx is the distribution of power per unit frequency. For real signals, accordingly.
%
% PWELCH returns the one-sided PSD by default; for complex signals, it % Pxx is the distribution of
% returns the two-sided PSD. Note that a one-sided PSD contains the power per unit frequency. For
% total power of the input signal. real
% signals,PWELCH returns
% the one-sided PSD by default;
% Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into for complex
% signals, it returns the two-
% overlapping sections of length equal to the length of WINDOW, and then
sided PSD. Note that a one-
% windows each section with the vector specified in WINDOW. If WINDOW is sided PSD
% an integer, X is divided into sections of length equal to that integer % contains the total power of
the input signal.
% 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 % Pxx =
% sections with 50% overlap, X will be truncated accordingly. If WINDOW PWELCH(X,WINDOW),
when WINDOW is a vector,
% is omitted or specified as empty, a default window is used to obtain
divides X into
% eight sections of X. % overlapping sections of
% length equal to the length of
WINDOW, and
% Pxx = PWELCH(X,WINDOW,NOVERLAP) uses NOVERLAP samples of overlap from % then windows each section
% section to section. NOVERLAP must be an integer smaller than the WINDOW with the vector specified in
% if WINDOW is an integer. NOVERLAP must be an integer smaller than the WINDOW. If
% WINDOW is an integer, X
... [1]
286 从 Matlab/Simulink 模型到代码实现

% 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.
第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);
288 从 Matlab/Simulink 模型到代码实现

% 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)
%
第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
290 从 Matlab/Simulink 模型到代码实现

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
第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
292 从 Matlab/Simulink 模型到代码实现

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
第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 函数的集合。它可以


实现的功能包括:
294 从 Matlab/Simulink 模型到代码实现

z 随机信号产生,用以产生随机的噪声和信号源

>> 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

z 误码分析,画眼图和星座图,如图 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.');
第9章 面向 DSP 和通信行业的应用 295

图 9.4 星座图(1)

>>hold on
>>blue = find(y==2);
>>scatterplot(x(blue,:),1,0,'b.',h);

删除的内容: ScaTTER Plot


图 9.5 星座图(2) 运行结果

z 信源编码,包括标量量化、差分脉冲编码调制、压缩扩展器等许多功能,如图 9.6
所示 删除的内容: 。

predictor = [0 1]; % y(k)=x(k-1)


partition = [-1:.1:.9];
296 从 Matlab/Simulink 模型到代码实现

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 调制

z 差错控制编码,包括卷积编码和线性块编码

>> 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
第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

z 模拟和数字调制/解调 删除的内容: 与

>> modmap('qam',16)

运行结果如图 9.7 所示。

删除的内容: 模拟和数字调制
图 9.7 16QAM 星座图 与解调
z 特殊滤波
¾ 希尔伯特变换滤波
¾ 滚降余弦滤波
z 伽罗华域的计算
298 从 Matlab/Simulink 模型到代码实现

删除的内容: 分页符

9.5 Filter Design Toolbox

滤波器设计工具箱提供了建立在 MATLAB 基本模块和信号处理工具箱之上的高级滤


波器设计方法,可用来设计、仿真和分析定点/浮点滤波器。Filter Design Toolbox 可以实 删除的内容: 。它
现的滤波器结构如表 9.1 和 9.2 所示。 删除的内容: (表 9.1 和表
9.2 请替换成我发给你的中文
表 9.1 Filter Design Toolbox 可实现的 FIR 滤波器结构 形式,文件名为修正
表.doc,本目录下也有!)
滤波器结构 描 述
反对称有限冲激响应结构 带格式的
‘antisymmetricfir’
直接型有限冲激响应结构 带格式的
‘fir’
直接型有限冲激响应结构的转置形式 带格式的
‘firt’
‘latticema’ Lattice MA 滤波器结构
‘symmetricfir’ 对称的有限冲激响应结构
带格式的
表 9.2 Filter Design Toolbox 可实现的 IIR 滤波器结构 删除的内容: 表 9.1 Filter
滤波器结构 描 述 Design Toolbox 可实现的
FIR 滤波器结构
‘df1’ 直接 I 型结构
带格式的
‘df1t’ 直接 I 型结构的转置形式
带格式的
‘df2’ 直接 II 型结构
‘df2t’ 直接 II 型结构的转置形式
‘latticeca’ Lattice 耦合全通滤波器结构
‘latticecapc’ Lattice 耦合全通功率补偿滤波器结构
‘latticear’ Lattice AR 滤波器结构
‘latticearma’ Lattice ARMA 滤波器结构 删除的内容: 表 9.2 Filter
‘statespace’ 单输入/单输出状态空间滤波器结构 Design Toolbox 可实现的 IIR
滤波器结构
删除的内容:

9.6 Image Processing Toolbox

图像处理工具箱提供一系列的函数来支持各种各样的图像处理算法,包括:
z 几何操作
z 邻域/块操作

z 线性滤波/滤波器的设计

z 各种变换

z 图像分析和增强
第9章 面向 DSP 和通信行业的应用 299

z 二进制图像操作
z 区域操作

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 数值计算环境之上的、支持各种各样的信号处理


方法的函数的集合。它支持的信号处理操作包括:
z 波形产生 删除的内容: ,结果如图 9.8
所示。

>> xn=sin(pi/16*(0:31));
>> stem(xn)

结果如图 9.8 所示。

删除的内容: 波形产生
图 9.8 数字序列波形
300 从 Matlab/Simulink 模型到代码实现

z 滤波器设计/实现,如图 9.9 所示 删除的内容: 结果


¾ 滤波器类型 删除的内容: 。
¾ 滤波器设计和分析工具 fdatool
>>fdatool

图 9.9 滤波器设计与实现

¾ 用 sptool 分析滤波器,如图 9.10 所示 带格式的: 项目符号和编号


>>sptool

图 9.10 用 sptool 分析滤波器


第9章 面向 DSP 和通信行业的应用 301

¾ IIR 滤波器的设计
¾ FIR 滤波器的设计
z 参数化建模
z 谱分析
¾ 统计信号处理
¾ 谱分析理论
¾ 谱分析方法
¾ 谱分析函数
¾ 时变谱

>> which specgramdemo


D:\MATLAB6p1\toolbox\signal\sigdemos\specgramdemo.m
>> specgramdemo
Loading demo file (mtlb.mat).

结果如图 9.11 所示。

删除的内容: 结果如图 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, 删除的内容: n
302 从 Matlab/Simulink 模型到代码实现

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 所示。


它可用来仿真:
z 线性/非线性系统

z 连续/离散系统

z 混合系统

同时,它还可以仿真多速率的系统,也就是允许系统的不同部分有不同的采样更新 删除的内容: 并且它


速率。
Simulink 是进行系统级仿真的强大工具。Simulink 提供了一个简单易用的图形化界面
和各种各样的模块来搭建系统模型。在 Simulink 中,用户可以实现自顶而下或是自底而上
的设计,可以非常方便地引入自己开发的算法。同时,由于 Simulink 和 Matlab 是高度集
成的,用户可以选择用 Matlab/Simulink 来分析系统模型中任何一点的信号。
第9章 面向 DSP 和通信行业的应用 303

图 9.12 Simulink 建模仿真环境

9.11 Stateflow

Stateflow 是解决复杂的逻辑控制问题的强大的图形化界面设计和开发工具。它和
Matlab/Simulink 高度集成。Stateflow 创建的框图可以看作是 Simulink 中的一个模块,它可
用于:
z 基于有限状态机理论,可视化地建模和仿真复杂的事件驱动的系统;

z 设计和开发确定性的管理控制系统;

z 可以非常容易地修改用户的设计,评估结果和验证系统的行为; 删除的内容: 你
z 从 Stateflow 模型自动生成定点/浮点 C 代码。

图 9.13 所示是用 Stateflow 搭建的开关切换控制逻辑系统,每一个上升沿的到来都会


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

触发开关状态的切换,并且使计数器加 1。
删除的内容: 分页符

图 9.13 开关切换控制逻辑

9.12 CDMA Reference Blockset

CDMA Reference Blockset 是包含 IS-95A CDMA 无线通信系统物理层基本模块的 Simulink


模块的集合,如图 9.14 和图 9.15 所示。图 9.16 所示是 IS-95A 前向业务信道的模型。 删除的内容: 15

图 9.14 CDMA Reference Blockset(a)


第9章 面向 DSP 和通信行业的应用 305

删除的内容: 图 9.14(续)
CDMA Reference Blockset(a)
续在上面还是
删除的内容: 图 9.14(续)
CDMA Reference Blockset(a)
带格式的
删除的内容: !!也可
删除的内容:

删除的内容: 14
图 9.15 CDMA Reference Blockset(b)
306 从 Matlab/Simulink 模型到代码实现

删除的内容: 15
图 9.16 %MATLABROOT%\toolbox\cdma\cdmademos\is95fwdchendtoend2.mdl

9.13 Communications Blockset

Communications Blockset 是用于研究、设计、仿真、分析和开发通信系统的 Simulink


模块的集合,如图 9.17 所示。用户可以直接使用这些模块或是修改它们来实现自己的通 删除的内容: 16
信算法和系统。Communications Blockset 可以用于实现整个通信链路,包括: 删除的内容: 你
z 信号产生/信源编码 删除的内容: 用
z 差错控制编码 删除的内容: 你
z 交织

z 调制/解调

z 搭建信道模型

z 同步
第9章 面向 DSP 和通信行业的应用 307

删除的内容: 16
图 9.17 Communications Blockset

9.14 DSP Blockset

DSP Blockset 是专门为数字信号处理应用设计的 Simulink 模块的集合,如图 9.18 所 删除的内容: 17


示。它可用于实现各种各样的 DSP 算法,例如多速率/自适应滤波、矩阵运算、统计、时 删除的内容: ,
频转换等。

删除的内容: 17
图 9.18 DSP Blockset
308 从 Matlab/Simulink 模型到代码实现

为了查看 DSP Blockset 相关的演示程序,可以使用如下命令:

>> demo blocksets dsp

运行结果如图 9.19 所示。 删除的内容: 18


删除的内容: :

删除的内容: 18
图 9.19 MATLAB 演示程序
删除的内容: Demos

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,能够开发基 删除的内容: Developer's
于 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。 删除的内容: 19
第9章 面向 DSP 和通信行业的应用 309

删除的内容: 19
图 9.20 Motorola DSP Blockset

>> mot_dsp563_filterdemo

运行和仿真结果分别如图 9.21 和图 9.22 所示。 删除的内容: 20


删除的内容: 21
删除的内容: :
310 从 Matlab/Simulink 模型到代码实现

删除的内容: 20
图 9.21 mot_dsp563_filterdemo.mdl

删除的内容: 1
图 9.22 仿真结果
删除的内容: Scope
第9章 面向 DSP 和通信行业的应用 311

9.16 Xilinx Blockset

Xilinx Blockset 是 Xilinx 公司提供的用于创建可以生成 FPGA 代码的 Simulink 模型的


模块的集合。使用它搭建的 Simulink 组件可直接转化为可综合的 Xilinx FPGA 的 VHDL
代码。图 9.23 所示是使用 Xilinx Blockset 中的模块搭建的 Costas 锁相环模型。 删除的内容: 22

删除的内容: 22
图 9.23 %MATLABROOT%\toolbox\xilinx\sysgen\examples\costas_loop\costas_tb.mdl 中的 Costas 锁相环

9.17 Real-Time Workshop

Real-Time Workshop 用于将 Simulink 搭建的系统模型自动转化为实现代码(C/Ada 代 删除的内容: (

码)。它提供五种不同的代码格式,各种代码格式确定了生成适用于某种特定应用的代码 删除的内容: )
的框架。这五种代码格式如下: 删除的内容: ,
z 适用于快速原型的实时代码; 删除的内容: 。
z 适用于快速原型的实时且动态分配内存的代码;

z 适用于代码重用和加速仿真过程的 S-函数代码格式;

z 适用于嵌入式系统的嵌入式 C 代码;

z Ada。

Real-Time Workshop 的各种目标代码支持的功能如表 9.3 所示。


删除的内容:
312 从 Matlab/Simulink 模型到代码实现

删除的内容: 9.18
表 9.3 Real-Time Workshop 目标代码的支持的功能 Developer’s Kit for TI DSP
Developer’s Kit for TI DSP
目标 Real- RTW 是 MathWorks 公司和 TI 公
TI
GRT time Embedded DOS Ada Tomado S-func RSIM RTWin xPC
DSP
司联合开发的一个工具包,
支持的功能
malloc Coder 它将 Simulink/Matlab 和 TI
TM
Static memory allocation × × × × × × × × × eXpressDSP 开发工具连
Dynamic memory 接起来,使用户能够很容易
× × × ×
allocation 地实现数字信号处理应用从
Continuous time × × × × × × × × 概念到代码的开发和验证过
CMES S-function 程。这个开发工具包主要由
× × × × × × × × × ×
(noninline) 三个接口组件组成:
Any S-functions Target for C6701 EVM
× × × Link for Real-Time Data
(inlined)
Exchange (RTDX)
Optimized for min Link for Code Composer
× ×
RAM/ROM usage Studio IDE
Supports external mode × × × × × × 有了这个开发工具,用户可
Intended for rapid 以直接将 Simulink 模型自动
× × × × × × ×
prototyping 转化为 TI DSP
Intended for production 删除的内容: s
× × × ×
code
删除的内容: 可以实现的 C
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 开发工具连接起来,使用户能够很容易地实现数字信
号处理应用从概念到代码的开发和验证过程。这个开发工具包主要由三个接口组件组成:
z Target for C6701 EVM 带格式的: 项目符号和编号

z Link for Real-Time Data Exchange(RTDX)


Link for Code Composer Studio IDE
z

有了这个开发工具,用户可以直接将 Simulink 模型自动转化为 TI DSP 可以实现的 C


代码,加速快速原型的开发进程。
第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 格式。它
支持:
z 定点代码生成;

z 浮点代码生成;

z 单一速率或者多速率的异步中断驱动执行模式;

z 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 语
言代码实现文件。
314 从 Matlab/Simulink 模型到代码实现

删除的内容: 23
删除的内容: 单击图 9.24 中
的 Build 按钮,将在当前目
录中创建目录
sfprj\build\sf_car\shiftlogic\src

sfprj\build\sf_car\shiftlogic\inf
o。目录
sfprj\build\sf_car\shiftlogic\inf
o 中生成了相关信息文件
binfo.mat,目录
图 9.24 将 sf_car.mdl 中的 Stateflow 框图生成 C 代码
sfprj\build\sf_car\shiftlogic\src
sf_car_shiftlogic.h 生成了 Stateflow 框图
shift_logic 的 C 语言代码实现
sf_car_shiftlogic.c
文件。

文件代码如下所列: 删除的内容: :
删除的内容:
第9章 面向 DSP 和通信行业的应用 315

/* 删除的内容: shift_logic.h
shift_logic.c
*
* 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 删除的内容:
*
316 从 Matlab/Simulink 模型到代码实现

*/

#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;
第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 */
318 从 Matlab/Simulink 模型到代码实现

/* 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 */
第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) {
320 从 Matlab/Simulink 模型到代码实现

/* 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(可选)创建系统模型和生成执行代码。生成可执
删除的内容: )
第9章 面向 DSP 和通信行业的应用 321

行的代码之后,可以在另一台 PC 机上实时地运行目标应用。主、目标机的两种连接方式
如图 9.25 和图 9.26 所示。 删除的内容: 5

删除的内容: 24
图 9.25 xPC Target 主-目标机串口连接方式

删除的内容: 25
图 9.26 xPC Target 主-目标机 Ethernet 连接方式

带格式的
页 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.
%
% 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
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,
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
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:
%
% 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
删除的内容: A

删除的内容: 代码

附录 带命令行参数的独立应用程序 删除的内容: 如下:


删除的内容: function
commsmtr(varargin)

% COMMSMTR - simulator
本附录是为了说明怎样编写带多个输入参数的独立应用程序。将下面三个文件 console application for a
certain communications
commsmtr.m(主程序)、disphelp.m 和 prcsofcmdline.m 放在当前目录下,再 system
% Please compile it into
windows console application
>mcc –B sgl commsmtr.m
commsmtr.exe
% as the following MATLAB
即可生成可执行文件 commsmtr.exe。三个代码文件见本书附带光盘。 commands:
% >>mex -setup
% >>mbuild -setup
>> !commsmtr sui4bpsk.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p 0.25 % >>mcc -B sgl commsmtr.m
**********system parameter for current simulation********** % then run it as a executable
program in Windows console,
the sampling frequency: Fs=5 (MHz) just like
the ratio of energy of each bit to noise power spectral density: Eb/N0= 0 5 10 15 20 25 30 35 40 % >commsmtr /?
% >commsmtr sui416qam.mat
the channel mode:
/s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t
SUI-4 + AWGN 10000 /p
the mapping method: 0.25
% and so on.
BPSK
%
the size of IFFT: 256 % Note!!!
the total bits of transmitted data: 10240 % This example is just for
explaining how to input
the size of cyclic prefix: 64 multiple command line
the simulation results will be saved in file sui4bpsk.mat parameters
>> !commsmtr /? % not for simulation.
%
A certain communications system simulator console application % author: YongchunChen
% date: 2002/02/08
commsmtr [filename] [/S Fs] [/R Eb_N0] [/C channel_model] % version: 1.0
[/M mapping_mode] [/F points_in_a_IFFT] [/T total_transmitted_data_bits] %% defining default system
[/P cyclic_prefix_length] parameters
commSys.Fs=5000000; %
sampling frquency=5MHz
filename the Matlab MAT-file name in which the simulation results commSys.Eb_N0=0:5:40; %
will be saved. the ratio of Energy of each bit
to noise
Fs the Sampling frequency of transmitted data(MHz).
power spectral density
Eb_N0 the ratio of energy of each bit to noise power spectral commSys.channelType=4; %
density. SUI-channel type
commSys.channelMode=strvca
channel_model the channel mode
t('AWGN',... % channel type
0 - AWGN 'SUI-1 + [1]
...
1 - SUI-1 + AWGN 删除的内容:
2 - SUI-2 + AWGN
删除的内容:
附录 带命令行参数的独立应用程序 删除的内容: A
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.
删除的内容: A.
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 图 A.1 在 DOS 命令窗口执
commsmtr data.mat /s 5 /r 0:5:20 /c 4 /m 2 /F 256 /t 65536 /p [0.2,0.25] 行 commsmtr.exe
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 中
带格式的
324 从 Matlab/Simulink 模型到代码实现

(如果计算机 A 上已安装了 MATLAB 操作系统,请将 C:\matlablib\bin\win32 添加在 删除的内容: 。(


%MATLABROOT%\bin\win32 之前)。 删除的内容:
步骤 4. 在计算机 A 的 DOS 命令窗口即可执行 commsmtr.exe 程序。 删除的内容: %
删除的内容: 。)
带格式的

附图 1 在 DOS 命令窗口执行 commsmtr.exe


页 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',...
' ',...
'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


% ......
%
%%% 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,',...
'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'
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
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.');
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));
end

commSysNew.totalBits=max(ceil(commSysNew.totalBits/LstComMult),1)*LstCom
Mult;
commSysNew.cpLen=ceil(max(commSysNew.ifftSize)*commSysNew.cpLenRatio);
读者意见反馈卡
请您认真填写本卡并寄给我们。对于发现本书中技术问题的读者,我们另有答谢。

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:thjd@thjd.com.cn)
《从 Matlab/Simulink 模型到代码实现》编辑部收
邮编:100084
联系电话:(010)62791976 传真:(010)62788903
公司网址:www.thjd.com.cn

如需本书可与本编辑部联系邮购,汇款请按以上地址填写,另加邮费 15%(挂号)

You might also like