Professional Documents
Culture Documents
到代码实现
陈永春 编著
清 华 大 学 出 版 社
(京)新登字 158 号
内 容 简 介
本书是一本易学易用、编排科学、理论与实际密切结合的 MATLAB 学习用书,它可以使读者全面了
解 MATLAB 技术,并帮助解决应用中的难题。
本书分为 9 个章节。先是介绍了 MATLAB 产品的体系结构、产品开发的流程及 MATLAB 的算法开
发功能,然后阐述了如何利用 MATLAB Complier 把 m 程序转成独立的应用以及系统级的设计工具
Simulink,紧接着介绍了从 Simulink 模型生成面向目标代码的工具 Real-Time Workshop 以及面向 DSP 和
通信行业应用的一些模块的基本特征。本书附光盘一张,以方便读者学习 MATLAB 的大量实例、程序代
码及图形。
本书特别适用于那些以 MATLAB 作为开发/仿真/实现工具的科技人员以及广大 MATLAB 爱好者。本
书文字简洁,附有大量直观图形,能有效地节省读者的时间。
版权所有,翻印必究。
本书封面贴有清华大学出版社激光防伪标签,无标签者不得销售。
Administering Apache
或抄袭
本
前 言
z 本书中某些命令的输出结果篇幅较长,为了说明问题,书中原样给出。如果不关
心命令的输出,读者可以跳过这些内容。
本书的出版首先要感谢我的导师北京航空航天大学电子工程系的万国龙教授对我的帮
助和教诲;感谢北京九州恒润科技有限公司的总经理吉英存博士在工作中给我的教益和启
发;感谢所有帮助支持过我的同事、朋友以及清华大学出版社的编辑们!
最后还要对我的父亲母亲致以深深谢意!
如果本书的出版,能给使用 MATLAB 的读者带来一些帮助和启发,我将深感荣幸!欢
迎读者朋友通过 E-mail yongchunchen@hotmail.com 和我交流 MATLAB 使用经验或者讨论
相关问题。读者也可登录北京九州恒润科技有限公司的网址 http://www.hirain.com 或者
MathWorks 公司的网址 http://www.mathworks.com 查询有关 MATLAB 的最新信息。有关
MATLAB 的购买事宜,请与北京九州恒润科技有限公司联系。
陈永春
2002 年 7 月 30 日
目 录
第 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
附录 带命令行参数的独立应用程序 ............................................................................322
第1章 MATLAB 产品的体系结构
1.1 科研及设计人员的最爱
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 模型到代码实现
For example,
ver control
returns the version info for the Control System Toolbox.
删除的内容: (图题应该和图
图 1.2 输入 helpwin ver 运行结果 在同一页)
第 1 章 MATLAB 产品的体系结构 5
删除的内容: (图题应该和图
图 1.4 MATLAB 产品的体系结构 在同一页)
6 从 Matlab/Simulink 模型到代码实现
MATLAB Toolbox
图 1.5 MATLAB 界面
Toolboxes
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.
Filter discretization.
bilinear - Bilinear transformation with optional prewarping.
impinvar - Impulse invariance analog to digital conversion.
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.
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 模型到代码实现
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
See also SIGDEMOS, AUDIO, and, in the Filter Design Toolbox, FILTERDESIGN.
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 arithmetic.
imabsdiff - Compute absolute difference of two images.
14 从 Matlab/Simulink 模型到代码实现
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.
Image analysis.
edge - Find edges in intensity image.
qtdecomp - Perform quadtree decomposition.
第 1 章 MATLAB 产品的体系结构 15
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.
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 模型到代码实现
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).
Array operations.
circshift - Shift array circularly.
18 从 Matlab/Simulink 模型到代码实现
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 模型到代码实现
mtlb vcosig
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
dicom-dict
strel
工具箱可以帮助用户加速特定应用领域的研发过程,让用户把主要精力放在构思自己
的想法,而不是编程上面。用户可以根据自己的应用领域有选择地购买工具箱模块。 删除的内容: (为何空一
片??)
Compiler 分页符
Simulink
Blocksets
图 1.8 电力系统模块库
图 1.9 通信模块库
26 从 Matlab/Simulink 模型到代码实现
删除的内容: .
图 1.10 已安装的所有 Simulink 模块库
删除的内容: (
删除的内容: )
Real-Time Workshop(RTW)
Stateflow
图 1.12 有限状态机:上海地铁出入口处的转门
Stateflow Coder
z 获得清晰的系统设计规范;
z 仿真系统组件间的行为;
z 设计和测试整个系统;
z 尽早发现设计中的瑕疵;
z 降低设计风险缩短产品上市时间。
图 1.16 退出安装对话框
第 1 章 MATLAB 产品的体系结构 31
步骤 7. 在图 1.21 所示的界面中,用户需要:
z 指 定 安 装 目 录 , 目 录 名 不 能 含 有 空 格 字 符 , 所 以 不 能 将 MATLAB 安 装 到 带格式的: 项目符号和编号
全部安装;
z 选择帮助文档的不同的语言版本;
第 1 章 MATLAB 产品的体系结构 33
删除的内容: 22
图 1.21 Product List
中。用户也可通过单击鼠标来选中或不选某个模块。值得注意的是某些模块之间 删除的内容: )
有一定的依赖关系,例如:MATLAB 模块是其他 MATLAB 产品的基础,要安装
其他模块,必须要选中或目标目录中已安装了 MATLAB 模块。MATLAB 各个模
块之间的相互关系,相信 MATLAB 代理商会代为处理,所以对用户来讲,默认选
择或是全选即可(如果磁盘空间足够的话)。在图 1.21 的右侧显示的是有效磁盘 删除的内容: (
空间、MATLAB 产品需要的磁盘空间、MATLAB 帮助文档需要的磁盘空间和总 删除的内容: )
共需要的磁盘空间信息。
单击 Next 按钮开始安装,如图 1.22 所示。当然,如果在图 1.21 中指定的安装目录不
存在,会提示创建此目录。
安装完成之后,MATLAB 安装目录中将包含如下文件和目录:
z 文本文件 license.txt,它是 MATLAB 软件的许可证协议;
z MATLAB 执行文件的快捷方式;
z 如下的子目录:
¾ \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
当然,在各位的安装目录中不一定包含上述所有目录。
>> matlabroot
ans =
D:\MATLAB6p1
图 1.30 %MATLABROOT%\toolbox\local\matlabrc.m
图 1.31 修改%MATLABROOT%\toolbox\local\matlabrc.m
%
% 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.
% 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
set_param(0,'PaperType',defaultpaper);
set_param(0,'PaperUnits',defaultunits);
end
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.
% 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
%% 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
MathWorks 公司一直致力于提高工程师与科研人员的研发效率,加速产品的开发过
程。为了达到这个目标,MathWorks 公司的 MATLAB 产品向用户提供了:
z Matlab:具有世界领先水准的工程计算、算法开发和数据可视化的软件;
z Simulink:交互式的用于系统级设计和仿真的模块框图环境。
2.1 数学方式的程序开发
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]);
2.2 脚本 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
>> solver
X=
0.7500
-0.6250
2.1250
>> whos
50 从 Matlab/Simulink 模型到代码实现
2.3 函数 m 文件
删除的内容:
图 2.1 MATLAB 函数文件格式
删除的内容:
关键字
>> function=100
??? function=100
|
Error: Illegal use of reserved keyword "function".
函数名
函数 m 文件的文件名一般应与函数名相同,如果不相同,则以文件名标识该函数。
也就是说,如果 m 函数的函数名和文件名不相同,MATLAB 命令窗口或者其他函数要通
过文件名来调用该函数,而不是用函数名。函数 m 文件的文件名要以字母开头,由字
母、数字、下划线组成,中间不能有空格,且长度不超过 31 个字符。函数名是以字母开
头,由字母、数字、下划线组成的字符串,中间不能有空格,长度不宜超过 31 个字符。
请用户尽量让 m 函数的函数名和它的文件名一致,以免混乱。
输入变量
在线帮助
删除的内容:
图 2.2 输入 helpwin mymean 的运行结果
删除的内容:
删除的内容:
删除的内容: 将 mymean.m 改
写成如图 2.3 所示,再使用
help 和 helpwin 命令,得到的
是不一样的结果:
删除的内容:
图 2.3 在线帮助各行之间不应有空格
删除的内容:
函数代码体
函数代码是实现函数功能的 m 语言代码,代码体的任何地方都可添加注释。带有多
个输入输出变量的 m 函数的格式如图 2.5 所示。
图 2.4 修改 mymean.m 后输
入 helpwin mymean 的运行结
果
删除的内容: ,
删除的内容:
图 2.5 带有多个输入输出变量的函数
删除的内容:
【例 2】输入参数可变的 m 函数。如图 2.6 所示是一个输入参数可变的 m 函数。编写 删除的内容: (应该和图在同
输入参数可变的函数,要注意的几点是: 一页)
z 输入参数可变的函数的最后一个输入参数一定要是 varargin;
function myvarin(p1,p2,…,pN,varargin)
删除的内容:
图 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])的运行结果
删除的内容:
删除的内容:
删除的内容:
删除的内容:
删除的内容: >> 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 输出参数可变的 m 函数
删除的内容:
z 第 13~17 行是产生坐标在[0 9]间均匀分布的随机整型数据点,返回(x,y)坐标。 删除的内容: ─
删除的内容: (
>> p1=myvarout
删除的内容: )
p1 =
6 2
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
z Wavelet Toolbox
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
删除的内容:
图 2.10 输入 helpwin daq 的运行结果
删除的内容:
>> doc daq
删除的内容:
运行结果如图 2.11 所示。 删除的内容:
删除的内容:
删除的内容:
删除的内容:
图 2.11 输入 doc daq 的运行结果
删除的内容:
删除的内容:
第2章 算法开发 61
2.5 调用 C/Fortran 程序
删除的内容:
⎨ 删除的内容: (
⎪µ = 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
删除的内容: (
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=
们想作出微分方程组的解(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=
ans =
2.0000
8.9685
4.0000
-1.0947
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
Compiler: 3
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;
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=
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=
ans =
2.0000
8.9685
4.0000
-1.0947 删除的内容:
删除的内容: 分页符
2.6 建立自己的函数库
删除的内容:
图 2.14 MATLAB 搜索路径设置对话框
删除的内容:
84 从 Matlab/Simulink 模型到代码实现 删除的内容:
删除的内容:
删除的内容:
删除的内容:
2.7 算法开发示例 删除的内容:
删除的内容:
%
% 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.
% --- randsrc
case ''
% --- randsrc(m)
case 'n'
m = varargin{1};
% --- randsrc(m, n)
case 'n/n'
m = varargin{1};
n = varargin{2};
% --- 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
ar = size(alpha,1);
ac = size(alpha,2);
if ar > 2
error('The ALPHABET parameter cannot contain more than two rows.');
aprob = alpha(2,:);
% '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
rand('state', state);
end
% 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,:);
% [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。
b=[1 2 0];
a=[1 2 3];
[z,p,k]=tf2zp(b,a);
zplane(z,p);
>> plotpz
删除的内容:
图 2.15 输入 plotpz 的运行结果
删除的内容:
【例 6】边缘检测算法。用 Sobel 和 Canny 方法来检测灰度图像的边缘,相应的函数
m 文件 edge_detect.m 如下所示: 删除的内容: :
I = imread(filename);
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']);
删除的内容: 分页符
删除的内容:
图 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
#if !defined
m程序
(可以包含图形功能)
MATLAB Compiler
m程序生成的C/C++源代码
C/C++编译器
独立应用
图 3.1 m 程序转成独立应用的过程
原则上是可以被其他的 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
译器。
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
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;
该插件的用途在后面会讲到。 删除的内容:
删除的内容: ,
>> mbuild -setup 删除的内容: 我们
Please choose your compiler for building standalone MATLAB applications:
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
3.2 从 m 程序自动生成独立的应用
和 C/C++源代码
Columns 1 through 6
Columns 7 through 12
Columns 13 through 17
a=
Columns 1 through 6
Columns 7 through 12
Columns 13 through 17
图 3.3 滤波器幅频响应和相频响应
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
>> !designbutworth
b=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
-0.0320 0 0.0040
a=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
图 3.4 菜单和工具条可以正确显示
b=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
-0.0320 0 0.0040
a=
Columns 1 through 7
Columns 8 through 14
102 从 Matlab/Simulink 模型到代码实现
Columns 15 through 17
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 菜单和工具条无法显示
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
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. 删除的内容:
OPTIONS:
If you wish to have some optimizations on, you may specify them
after the debug switch.
l Line. Generates code that reports file name and line numbers on
run-time errors. (Equivalent to -A debugline:on)
T <option> Specify target phase and type. The following table shows
valid <option> strings and their effects:
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.
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.
EXAMPLES:
Note: on PCs, filenames ending with .o above would actually end with .obj. 删除的内容:
删除的内容: 分页符
b=
112 从 Matlab/Simulink 模型到代码实现
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
-0.0320 0 0.0040
a=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
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
EXITING
删除的内容:
图 3.6 滤波器的频率响应
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)
b=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
-0.0320 0 0.0040
a=
Columns 1 through 7
Columns 8 through 14
Columns 15 through 17
图 3.7 修改后得到的滤波器频率响应
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)
编译它,结果如下: 删除的内容:
错误
>> !designbutworthand2df2
ERROR: Undefined function or variable 'df2'.
EXITING
function testinputandeval
R = input('Input MATLAB expression: ','s');
R
eval(R);
a=
sin(10)
>> !testinputandeval
Input MATLAB expression: a
R=
EXITING
>> !testinputandeval
Input MATLAB expression: sin(10)
R=
sin(10)
第3章 将 m 程序转换成独立的应用 117
ans =
-0.5440
function testls
%testls.m
y= 'a';
load('testls.mat',y);
EXITING
但是
function testls
%testls.m
load('testls.mat','a');
a
可以正确地编译和执行。
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 函数
话框。
步骤 4. 在图 3.11 所示对话框中选择需要调用的 m 函数(该函数最好不带参数,或者 带格式的
删除的内容: 分页符
图 3.11 选择 m 文件
120 从 Matlab/Simulink 模型到代码实现
图 3.12 mcc-log.txt
图 3.13 plotfreq.m
本节以 Microsoft Visual C++ 6.0 为例,讲解从 VC++中调用 MATLAB C Math Library
的步骤(Microsoft Visual C++ 5.0 的情况与此类同)。 删除的内容: (
删除的内容: )
从 Win32 控制台程序调用 MATLAB C Math Library
入图 3.20 所示界面。
步骤 3. 在图 3.20 所示界面中单击 OK 按钮,生成如图 3.21 所示的工程文件。 带格式的
图 3.23 mysvd.cpp
图 3.24 consoleprj.cpp
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.30 选择 Single document
删除的内容: 步骤 3. 修改
mfcprjView.h,在视类定义中
添加一行 int mysvd
删除的内容: (
删除的内容: (CDC *pDC
删除的内容: )
删除的内容: );,如下所
示。
删除的内容: 分页符
下所示。
第3章 将 m 程序转换成独立的应用 131
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()
};
/////////////////////////////////////////////////////////////////////////////
//{{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 "mfcprjDoc.h"
#include "mfcprjView.h"
#include "matlab.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
////////////////////////////////////////////////////////////////////////
// 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()
{
}
return CView::PreCreateWindow(cs);
}
////////////////////////////////////////////////////////////////////////
// CMfcprjView drawing
////////////////////////////////////////////////////////////////////////
// CMfcprjView printing
mlfEnterNewContext(0, 0);
mlfAssign(&X, mlfDoubleMatrix(4, 2, data, NULL));
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
////////////////////////////////////////////////////////////////////////
// CMfcprjView message handlers
图 3.35 所示。
的安装目录选择对话框。注意目录名中不能包含空格,一般用默认目录即可。然后,单击
Next 按钮,开始安装,如图 3.37 所示。
图 3.36 选择安装目录
图 3.37 Installing
删除的内容: r
图 3.39 MatrixVB 程序项
第3章 将 m 程序转换成独立的应用 141
删除的内容: L
图 3.41 VB 中调用 MATLAB 的 invhilb 和 plot 函数功能的运行结果
>> plot(invhilb(5))
图 3.42 输入 plot(invhilb(5))的运行结果
// 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:
////////////////////////////////////////////////////////////////////////
//{{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
4.1 图形化建模
Simulink 是一个图形化的建模工具。从某种意义上讲,凡是能够用数学方式描述的系
统,都可用 Simulink 建模。当然,针对自己特定的系统,用户应该权衡 Simulink 的易用
性和方便性,以选择是否用 Simulink 建模。例如通信系统网络层的仿真,用 Simulink 加
上 Stateflow 是可以实现的,但不会太方便,所以笔者主张类似的仿真现在还不宜用
Simulink。用 Simulink 可以很容易就搭建的系统主要包括:
z 通信系统物理层和数据链路层
z 动力学系统
z 控制系统
z 数字信号处理系统
z 电力系统
z 生物系统
z 金融系统
z Communications Blockset
4.2 基本模块库
包括:
z 用于连续系统的基本模块(Simulink/Continuous),如图 4.2 所示。 删除的内容: (
删除的内容: )
图 4.2 用于连续系统的基本模块
图 4.3 用于离散系统的基本模块
图 4.5 数学运算基本模块
图 4.6 非线性模块
第4章 系统级设计工具 Simulink 147
图 4.7 信号与系统基本模块
图 4.8 信宿模块
148 从 Matlab/Simulink 模型到代码实现
图 4.9 信源模块
图 4.10 子系统基本模块
第4章 系统级设计工具 Simulink 149
4.3 Blocksets
图 4.12 扩展模块库
对 Simulink 系统模型的仿真主要包含两个阶段:
z 初始化阶段
初始化阶段主要完成以下工作:
¾ 每个模块的所有参数都传递给 MATLAB 进行求值,得到的数值作为实际的 删除的内容:
参数使用。 删除的内容:
¾ 展开模型的层次结构,每个子系统被它们所包含的模块替代,带有触发和使 带格式的: 项目符号和编号
能模块的子系统被视为原子单元进行处理。
¾ 检查信号的宽度和模块的连接情况,提取状态和输入/输出依赖关系方面的
信息,确定模块的更新顺序。
第4章 系统级设计工具 Simulink 151
¾ 确定状态的初值和采样时间。
z 运行阶段
初始化之后,仿真进入运行阶段。仿真是由求解器控制的,它计算模块的输出,更新
离散状态,计算连续状态。在采用变步长求解器时,求解器还会确定时间步长。计算连续
状态包含下面两个步骤:
¾ 首先,求解器为待更新的系统提供当前状态、时间和输入值,反过来,求解 删除的内容: 展开模型的层次
结构,每个子系统被它们所
器需要状态导数的值;
包含的模块替代,带有触发
¾ 然后,求解器对状态的导数进行积分,计算新的状态的值。 和使能模块的子系统被视为
状态计算完成后,再进行一次模块的输出更新。这时,一些模块可能会发出过零的警 原子单元进行处理。
告,促使求解器探测出发生过零的准确时间。 <#>检查信号的宽度和模块
Simulink 的仿真过程是在 Simulink 求解器和系统相互作用之下完成的,系统和求解器 的连接情况,提取状态和输
在仿真过程中的对话作用如图 4.13 所示。 入/输出依赖关系方面的信
息,确定模块的更新顺序。
<#>确定状态的初值和采样
时间。
时间、输入、状态 运行阶段初始化之后,仿真
进入运行阶段。仿真是由求
解器控制的,它计算模块的
SIMULINK
输出,更新离散状态,计算
连续状态。在采用变步长求
系统 解器时,求解器还会确定时
计算
求解器 间步长。计算连续状态包含
模块输出
传递模块输出 下面两个步骤:
状态的导数
对状态导数积分
状态的更新
确定采样时间 带格式的
生成
过零事件 带格式的
带格式的: 项目符号和编号
带格式的
删除的内容: 然后,求解器对
输出、导数、事件通知 状态的导数进行积分,计算
新的状态的值。
状态计算完成后,再进行一
图 4.13 系统和求解器之间的对话
次模块的输出更新。这时,
一些模块可能会发出过零的
在图 4.13 中,求解器的作用是传递模块的输出,对状态导数进行积分,并确定采样
警告,促使求解器探测出发
时间。系统的作用是计算模块的输出,对状态进行更新,计算状态的导数,生成过零 生过零的准确时间。
事件。从求解器传递给系统的信息包括时间、输入和当前状态;反过来,系统为求解器提
供模块的输出、状态的更新和状态的导数。整个仿真过程如图 4.14 所示。
152 从 Matlab/Simulink 模型到代码实现
设置初始条件
计算下一个采样所在时刻
(仅对变步长仿真)
计算输出
更新离散状态
(如果系统存在离散状态)
计算输出
计算导数
结束
4.5 重 要 概 念
系统模型搭建完成之后,可以对其进行各种各样的仿真,以测试系统的性能。仿真过
程涉及到一些重要的概念。
过零检测
z 模块在上一个时间步改变了模式(例如积分器进入了饱和区段) 。
过零是一个重要的事件,表征系统中的不连续性,例如响应中的跳变。如果仿真中不
对过零进行检测,可能会导致不准确的仿真结果。 当采用变步长求解器时,Simulink 能
够检测到过零(使用固定步长的求解器,Simulink 不检测过零)。当一个模块通知系统前 删除的内容: (
一时间步发生了过零,变步长求解器就会缩小步长,即便绝对误差和相对误差是可接受 删除的内容: )
第4章 系统级设计工具 Simulink 153
的。缩小步长的目的是判定事件发生的准确时间。当然,这样会降低仿真的速度,但这样
做对有些模块来讲是至关重要和必要的,因为这些模块的输出可能表示了一个物理值,它
的零值有着重要的意义。事实上,只有少量的模块能够发出过零事件通知。每个模块发出
专属于自己的事件通知,而且可能与不止一个类型的事件发生关联。
能够产生过零通知的 Simulink 模块如图 4.15 所示。
各个模块的过零的类型是有差异的。例如,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.18 关闭过零检测
第4章 系统级设计工具 Simulink 155
代数环
直接馈通(Direct feedthrough)定义为系统的输出直接依赖于输入,换句话说,如果
模块的输出方程中包含输入,则它具备直接馈通特性。Gain 模块有直接馈通特性,而
Unit Delay 模块则不具备。在 Simulink 模型中,将带有直接馈通特性的各模块串成一个回
路会导致一个代数环。在一个代数环中,由于模块之间是相互依赖的,所有的模块都要求
在同一个时刻计算输出,这与通常的仿真顺序概念相抵触。具有代数环的模型,仿真得到
的结果可能不正确。所以在用 Simulink 搭建系统模型之前,应尽量通过手工的方法对方程
求解,以去掉代数环。
如图 4.20 所示的模型是一个含有代数环的模型例子。为了计算求和模块的输出,
Simulink 需要知道它的输入,但是输入恰恰是输出自己!这个代数环可以很方便地手工 删除的内容:
解出:
1-x-x=x,x=0.3333 带格式的
带格式的
删除的内容:
带格式的
带格式的
删除的内容:
图 4.20 algebra_loop.mdl
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
'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 模型到代码实现
不能满足要求,或者用户确实关注仿真速度,才宜编写 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
*/
#include "simstruc.h"
/*================*
* Build checking *
*================*/
第4章 系统级设计工具 Simulink 159
if (!ssSetNumOutputPorts(S,1)) return;
ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetNumSampleTimes(S, 1);
TIMES10_C.DLL
第4章 系统级设计工具 Simulink 161
图 4.24 S-Function 模块
图 4.25 sintx10.mdl
%%%%%%%%%%%
% 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
(这个文件不是必要的,但如不涉及知识产权保护,一般还是将它包括在内,以供用户参 删除的内容: (
考)和 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.32 m S-函数
图 4.33 C S-函数
图 4.34 创建子系统
图 4.35 创建的子系统
所示。
图 4.36 删除子系统输入输出端口
所示。
步骤 7. 如图 4.39 所示设置 Mask Editor 对话框,其他参数为默认值,结果如图 4.40 带格式的
所示。
168 从 Matlab/Simulink 模型到代码实现
删除的内容: 分页符
图 4.37 删除输入输出端口后的子系统
图 4.38 封装子系统
图 4.40 封装之后的子系统
图 4.41 times10.mdl
文件 slblocks.m。其内容如下:
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 带格式的
所示。
Times10 Blockset 已经加在 Simulink Library Browser 中了,如图 4.44 和图 4.45 所示。现在
就可以像使用标准模块库中的模块一样使用 Times10 Blockset 中的模块了。
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
图 4.48 bluetooth_voice.mdl
174 从 Matlab/Simulink 模型到代码实现
图 4.49 tpc95.mdl
图 4.51 gsm_edge.mdl
删除的内容: 分页符
删除的内容:
图 4.57 softdec.mdl
第5章 Real-Time Workshop
算法的开发、系统级设计和仿真只是产品开发的两个环节,产品开发还有最为关键的
一环,那就是实现。前面已经介绍过,m 语言开发的算法通过 MATLAB Compiler 可以转
成独立的应用和 C/C++源代码。有必要强调一下,MATLAB Compiler 生成的 C/C++源代
码不是面向目标的,而是针对 PC 和 UNIX 平台的,它连接了很多动态链接库,无法应用 删除的内容:
5.1 减轻程序员负担
图 5.1 传统的产品开发流程
5.2 自动代码生成过程
文件;
z RTW Embedded Coder 可以在代码生成的过程中产生一个 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
z 可生成浮点代码;
z 对单速率或者多速率系统,都支持异步中断方式;
生成的代码(软件在回路仿真); 删除的内容:
z 自动生成 HTML 格式的代码生成报告。 删除的内容: (
注意,RTW Embedded Coder 只支持内嵌的(inlined)S-函数。 删除的内容: )
RTW Embedded Coder 生成的代码的效率非常高,早期版本的测试结果如图 5.6 所 删除的内容: (
示,MATLAB R12.1 中 RTW Embedded Coder 的版本是 2.0,效率应当更高。 删除的内容: )
删除的内容:
Visual C/C++ Project Makefile only for the RTW Embedded Coder
Ada 是美国军方使用的编程语言的一个标准,在中国使用得较少。
z 实时的硬件在回路仿真
z 教学为学生树立建模、仿真和测试实时系统及进行迭代设计的整个流程和概念 删除的内容: ─
S-function Target
z 将一个子系统转换成一个模块;
z 加速仿真;
z 代码重用。
z 快速原型;
z 实时实现;
6.2 三 种 接 口
图 6.1 三种接口
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
z Simulink 基本模块;
z DSP Blockset;
z Real-Time Workshop;
更高版本。
另外,
z 为了 Target for C6701 EVM 接口能够下载运行 DSP 程序,用户需要至少一个
间的接口),用户也需要:
¾ MATLAB 基本模块;
¾ Simulink 基本模块。
安装完 Developer’s Kit for TI DSP 后,在%MATLABROOT%\toolbox 目录下会包含一
个如图 6.2 所示的目录结构,它是 Developer’s Kit for TI DSP 安装后生成的目录结构。
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 模型到代码实现
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'])); 删除的内容: ‘
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'… 删除的内容:
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 删除的内容: ‘
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; 删除的内容: ‘
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]
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]
>> 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 所示,返回板号和处理器号。 删除的内容: :
procNum =
图 6.4 选择目标板和目标板
上的处理器
图 6.4 选择目标板和目标板上的处理器
>> 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 cc.visible(1)让开发环境可见
>> disp(cc)
CCSDSP Object:
第6章 面向 TI DSP 的自动代码生成 209
z 第 140 行,返回包含目标处理器信息的一个结构。
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)到目标处理器 境可见
read 从目标处理器的指定内存提取数据
删除的内容:
第6章 面向 TI DSP 的自动代码生成 211
续表
函 数 重 载 描 述
regread 读取目标处理器指定寄存器中的数据值
regwrite 向目标处理器指定的寄存器中写入一个值
reset 复位目标处理器
restart 为目标处理器上的当前程序重置程序计数器到起始点
run 执行目标处理器上的程序
set 是 为 CCS IDE 连接设置属性
symbol 从 CCS IDE 返回最近的程序符号表
visible 设置 CCS IDE 窗口的可见性
write 向目标处理器的指定内存写入数据
cpurunstatus = isrunning(cc)
cpurunstatus =
>> 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 中打开的工程文 请和原稿一致!!!)
ans =
[]
>>ddatA = address(cc,'ddat')
ddatA =
1.0e+009 *
2.1475 0
>>dec2hex(ddatA)
ans =
80000010
00000000
图 6.6 ccstut_6x11.mak
>> halt(cc)
restart(cc)
run(cc,'runtohalt',20);
ddatV = read(cc,address(cc,'ddat'),'double',4)
idatV = read(cc,address(cc,'idat'),'int32',4)
run(cc,'runtohalt',20);
ddatV = read(cc,address(cc,'ddat'),'double',4)
idatV = read(cc,address(cc,'idat'),'int32',4)
restart(cc);
ddatV =
idatV =
ddatV =
idatV =
1 2 3 4
>>cc.regread('B2','binary')
ans =
¾ cc.regread('PC','binary'),以无符号格式读取程序计数器的内容; 删除的内容: (
格式。 删除的内容: )
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 删除的内容:
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 模型到代码实现
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
程序说明如下:
z 第 18 行,通过开发板和处理器选择对话框、选择目标板和目标处理器,返回板号
续表
函 数 重 载 描 述
禁用 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 向目标处理器写入一个消息
/* RTDX tutorial target application: read from host and echo back */
#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 模型到代码实现
2 3 4 5 6 7 8 9 10 11
4 5 6 7 8 9 10 11 12 13
8
9
10
11
12
13
14
15
16
17
9 14 删除的内容:
10 15
11 16
12 17
13 18
10 14 18 13 17
11 15 19 14 18
12 16 11 15 19
13 17 12 16 20
删除的内容: ─
删除的内容:
>>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
安装了 Developer’s Kit for TI DSP 模块之后,在 Simulink Library Browser 中会出现一
个支持 C6701 EVM 的模块库,如图 6.7 所示。在搭建需要生成面向 C6701 EVM 的工程文
件的 Simulink 模型时,可以选用该模块库中的模块。
第6章 面向 TI DSP 的自动代码生成 227
删除的内容:
删除的内容: 这个有什么关
... [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.13 仿真参数设置
图 6.15 lfilterwithc6701.mdl
图 6.18 选择固定步长
删除的内容: 6.29
图 6.19 选择 Target for C6701 EVM
第6章 面向 TI DSP 的自动代码生成 233
options 的默认设置。
options(cont.)的默认设置。 删除的内容:
删除的内容: (
删除的内容: (
删除的内容: cont. )
删除的内容: )
删除的内容: )
带格式的
删除的内容: *
删除的内容: *
带格式的
删除的内容: 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
删除的内容: *
带格式的
... [225]
带格式的
... [226]
第6章 面向 TI DSP 的自动代码生成 239
图 6.33 示波器
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 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.
删除的内容:
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.
删除的内容:
删除的内容:
删除的内容: 可否能把图中
“设计叠代”改为“设计迭
图 7.1 传统的 FPGA 设计方式 代”
带格式的
第7章 面向 Xilinx FPGA 的自动代码生成 243
删除的内容: (
图 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.6 Math(数学模块)
删除的内容:
图 7.7 Memory(内存模块)
删除的内容:
删除的内容: (…) ... [1]
图 7.8 Matlab IO(接口模块) 删除的内容: 此图在原稿的
Word 文档中就是半黑状
用于 FPGA 设计的 Simulink 模型基本框架如图 7.9 所示。 删除的内容: (…) ... [2]
第7章 面向 Xilinx FPGA 的自动代码生成 247
其中,
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 代码的行为仿真。
删除的内容:
现举一例说明用于 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.13 Dout 模块(Gateway Out 模块)参数设置
删除的内容: )
删除的内容: (
图 7.14 Dout MAC 模块(Gateway Out 模块)参数设置
删除的内容: )
250 从 Matlab/Simulink 模型到代码实现
图 7.20 中各个设置项目的可选项如下:
Target Directory
生成代码所在的目标目录,任何有效的目录名称都可,如果目录不存在,生成代码的
过程中会提示用户创建该目录。
Create Testbench
通 常 的 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
Generate Cores
图 7.21 代码生成完成
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
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
7.4 浮点仿真与定点仿真
7.5 未 来 之 路
8.1 VxWorks/Tornado
z 速率转换
z 异步缓存读取
z 任务间同步
z 异步缓存写入
第8章 面向 VxWorks 的代码生成 259
图 8.3 IO Devices 库
删除的内容: (没办法!,
你可以用 Visio 画一个)
删除的内容: (
图 8.4 VxWorks 实时应用开发的典型配置 删除的内容: )
删除的内容:
实时代码在 UNIX/PC 主机上,用 Torando 提供的交叉编译器编译。通过 Real-Time
删除的内容: (
Workshop\Tornado(VxWorks)Real-Time Target 生成的目标文件(model.lo),可通过
删除的内容: )
Tornado 集成开发环境的命令 shell Windsh 下载到 VxWorks 目标机。实时程序在 VxWorks
目标机上执行,通过 IO 设备和外部硬件交换数据,并且保持和主机之间的相互通信。 删除的内容: 的
删除的内容: (
图 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 格式输出数据;
主机进程
目标机上的 VxWorks 任务
对于多采样速率模型,用户可以以单任务模式或者多任务模式生成实时程序(对于单 删除的内容: (
采样率模型,则只能生成单任务模式的实时程序),这可通过仿真参数设置对话框的 删除的内容: )
262 从 Matlab/Simulink 模型到代码实现
图 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 任务才将数据发送到主机上进
行显示。
删除的内容: (
删除的内容: )
针对特定应用设计 Simulink 模型
添加设备驱动模块
z VxWorks 配置
用户必须给定目标机和目标机 CPU 的类型,目标类型用于选择适当的交叉编译器和
连接器,CPU 类型用于定义宏 CPU,许多 VxWorks 头文件需要使用这些宏定义。关于如
何正确给定目标机和目标机 CPU 的类型,请参阅 VxWorks 相关文档。目标机和目标机
CPU 的类型信息在 tornado.tmf 中给定,由
#-------------- VxWorks Configuration --------------
标识。请按实际情况修改如下几行: 删除的内容: ,
VX_TARGET_TYPE = 68k
CPU_TYPE = MC68040
z 自动下载配置
为了在编译的过程中完成自动下载的功能,必须正确指定目标名和 Tornado Target
Server 主机名。请根据实际情况修改如下的宏定义:
TARGET = targetname
266 从 Matlab/Simulink 模型到代码实现
TGTSVR_HOST = hostname
z 工具位置
为了定位在编译过程中需要使用的 Tornado 工具程序,必须在环境变量或者模板
makefile 文件 tornado.tmf 中指定如下 3 个宏: 删除的内容: 三
WIND_BASE = c:/Tornado
WIND_HOST_TYPE = x86–win32
WIND_REGISTRY = $(COMPUTERNAME)
请根据实际情况进行修改。
程序的生成、编译、连接和下载
Build 按钮(不要选择 Generate code only,否则 Build 按钮会变为 Generate code 按钮,单 删除的内容: (
击后只生成代码和对应的 makefile 文件), 启动编译连接过程。生成的代码被交叉编译 删除的内容: )
连接,生成相应的目标文件 model.lo(lo:loadable object)。 删除的内容: (
¾ 如果选择了自动下载功能(Download to VxWorks target),Target Server 将 带格式的
被启动,目标文件被自动下载到目标机中并开始运行(为了成功地自动下载 删除的内容: )
tornado\downld.pl)。 删除的内容: (
* 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 模型到代码实现
/*
* Convert to lower case.
*/
for (i=0; i<optStrLen; i++) {
optStr[i] = tolower(optStr[i]);
}
/*
* Convert error string to standard argc and argv format.
*/
/*
* 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
/* 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++];
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);
}
}
/************************
* 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 模型到代码实现
#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
sysAuxClkDisable();
rtSetSampleRate(1.0 / ssGetStepSize(S));
#ifdef MULTITASKING
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
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
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
zscopeInstallString 删除的内容: )
用于指定将哪些信号安装到 StethoScope 的字符串,可能的值包括: 删除的内容: (这句没问
题!!)
¾ NULL——不安装任何信号,这是默认设置;
¾ “*”——安装所有信号; 删除的内容: ─
¾ “[A-Z]*”——安装名称以大写字母开头的模块输出的信号; 删除的内容: ─
¾ 指定其他任何字符串,将安装名称为该字符串的模块输出的信号。 删除的内容: ─
scopeFullName
z
port
z 删除的内容: )
外部模式连接使用的 TCP 端口号,有效值为 256~65535,默认值为 17725。 删除的内容: ─
用户也可以在 tornado.tmf 中定义宏 PROGRAM_OPTS,传递-w 和-tf 选项给 rt_main
函数。例如: 删除的内容: ,
280 从 Matlab/Simulink 模型到代码实现
在WindSh窗口中调用rt_main函数,开始运行程序。例如: 删除的内容: ,
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.
*/
/*
* 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++];
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);
}
}
/************************
* 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
#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
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
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
return(EXIT_SUCCESS);
} /* end rt_ma
第9章 面向 DSP 和通信行业的应用
删除的内容:
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 模型到代码实现
数学计算
>> A=magic(3)
A=
8 1 6
3 5 7
4 9 2
>> invA=inv(A)
invA =
>> [v,d]=eig(A)
v=
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 模型到代码实现
% 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
% 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 模型到代码实现
%--------------------------------------------------------------------------------------
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 = '';
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
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
数据分析和可视化
>> Lorenz
>> wrldtrv
删除的内容: 分页符
z 随机信号产生,用以产生随机的噪声和信号源
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
Columns 4 through 6
Columns 7 through 9
Column 10
6.0579 - 1.6622i
>>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);
z 信源编码,包括标量量化、差分脉冲编码调制、压缩扩展器等许多功能,如图 9.6
所示 删除的内容: 。
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 差错控制编码,包括卷积编码和线性块编码
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 16QAM 星座图 与解调
z 特殊滤波
¾ 希尔伯特变换滤波
¾ 滚降余弦滤波
z 伽罗华域的计算
298 从 Matlab/Simulink 模型到代码实现
删除的内容: 分页符
图像处理工具箱提供一系列的函数来支持各种各样的图像处理算法,包括:
z 几何操作
z 邻域/块操作
z 线性滤波/滤波器的设计
z 各种变换
z 图像分析和增强
第9章 面向 DSP 和通信行业的应用 299
z 二进制图像操作
z 区域操作
>> xn=sin(pi/16*(0:31));
>> stem(xn)
删除的内容: 波形产生
图 9.8 数字序列波形
300 从 Matlab/Simulink 模型到代码实现
图 9.9 滤波器设计与实现
¾ IIR 滤波器的设计
¾ FIR 滤波器的设计
z 参数化建模
z 谱分析
¾ 统计信号处理
¾ 谱分析理论
¾ 谱分析方法
¾ 谱分析函数
¾ 时变谱
9.10 Simulink 概述
z 连续/离散系统
z 混合系统
9.11 Stateflow
Stateflow 是解决复杂的逻辑控制问题的强大的图形化界面设计和开发工具。它和
Matlab/Simulink 高度集成。Stateflow 创建的框图可以看作是 Simulink 中的一个模块,它可
用于:
z 基于有限状态机理论,可视化地建模和仿真复杂的事件驱动的系统;
z 设计和开发确定性的管理控制系统;
z 可以非常容易地修改用户的设计,评估结果和验证系统的行为; 删除的内容: 你
z 从 Stateflow 模型自动生成定点/浮点 C 代码。
触发开关状态的切换,并且使计数器加 1。
删除的内容: 分页符
图 9.13 开关切换控制逻辑
删除的内容: 图 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
z 调制/解调
z 搭建信道模型
z 同步
第9章 面向 DSP 和通信行业的应用 307
删除的内容: 16
图 9.17 Communications Blockset
删除的内容: 17
图 9.18 DSP Blockset
308 从 Matlab/Simulink 模型到代码实现
删除的内容: 18
图 9.19 MATLAB 演示程序
删除的内容: Demos
删除的内容: 19
图 9.20 Motorola DSP Blockset
>> mot_dsp563_filterdemo
删除的内容: 20
图 9.21 mot_dsp563_filterdemo.mdl
删除的内容: 1
图 9.22 仿真结果
删除的内容: Scope
第9章 面向 DSP 和通信行业的应用 311
删除的内容: 22
图 9.23 %MATLABROOT%\toolbox\xilinx\sysgen\examples\costas_loop\costas_tb.mdl 中的 Costas 锁相环
码)。它提供五种不同的代码格式,各种代码格式确定了生成适用于某种特定应用的代码 删除的内容: )
的框架。这五种代码格式如下: 删除的内容: ,
z 适用于快速原型的实时代码; 删除的内容: 。
z 适用于快速原型的实时且动态分配内存的代码;
z 适用于代码重用和加速仿真过程的 S-函数代码格式;
z 适用于嵌入式系统的嵌入式 C 代码;
z Ada。
删除的内容: 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) 删除的内容: (
删除的内容: )
删除的内容: (
z 浮点代码生成;
z 单一速率或者多速率的异步中断驱动执行模式;
>> sf_car
删除的内容: 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"
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;
}
}
}
}
}
}
{
/* 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));
}
删除的内容: 你
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
% 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);
%----------------------------------------------------------------------
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 = '';
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
删除的内容: 代码
% 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 模型到代码实现
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.' ...
));
commSysNew=commSysDefault;
cmdLineErr=0;
cmdLine=lower(varargin);
k=1;
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:
□有 □无
如需本书可与本编辑部联系邮购,汇款请按以上地址填写,另加邮费 15%(挂号)