You are on page 1of 363

Matlab/Simulink

() 158

MATLAB
MATLAB
9 MATLAB MATLAB
MATLAB Complier m
Simulink Simulink Real-Time Workshop DSP
MATLAB

MATLAB // MATLAB

Administering Apache

Matlab/Simulink

100084
http://www.tup.tsinghua.edu.cn

7871092 1/16

21

479

2002 10 1 2002 10 1

ISBN 7-900643-63-X

00015000

34.00

2001 , MATLAB MATLAB DSP


4G
MATLAB m C/C++
C/C++ MATLAB MATLAB C/C++ Math

: l

Library VB MATLAB
Simulink TI DSPs/Xilinx
FPGA/WindRiver VxWorks
MATLAB
MATLAB
MATLAB
MATLAB MATLAB
MATLAB MATLAB
MATLAB MATLAB MATLAB

1 MATLAB MATLAB

2 MATLAB m
C/Fortran m

3 MATLAB Compiler m
VC++ m VC++/VB MATLAB

4 MATLAB Simulink Simulink


Simulink C m

5 Simulink Real-Time Workshop


Real-Time Workshop

6 TI DSP Development Kit for TI DSP


Matlab TI DSP Simulink
TI DSP Code Composer Studio

7 Xilinx FPGA Simulink


Xilinx FPGA VHDL

Matlab/Simulink

II
z

8 WindRiver VxWorks
Simulink VxWorks/Tornado

9 MATLAB DSP

>>command_name/command_name(arg1,,argN) MATLAB

command_name command_name(arg1,,argN) command_name

m >> MATLAB
z

MATLAB MATLAB MATLAB


MATLAB ToolboxMatlab MATLAB MATLAB

Image Processing Toolbox MATLAB

: (

Compiler m MATLAB Toolbox MATLAB

: )

: (

%MATLABROOT% MATLAB

: )

MATLAB
E-mail yongchunchen@hotmail.com MATLAB
http://www.hirain.com
MathWorks http://www.mathworks.com MATLAB
MATLAB

2002 7 30

1
1.1
1.2
1.3
1.4
1.5

MATLAB ...................................................................................1
............................................................................................... 1
MATLAB .......................................................................................... 5
MATLAB ............................................................... 28
MATLAB ....................................................................................................... 29
MATLAB ................................................................................................ 37

2 ..........................................................................................................47
2.1 ................................................................................................. 47
2.2 m ................................................................................................................ 49
2.3 m ................................................................................................................ 50
2.4 Toolboxes .................................................................................................................... 57
2.5 C/Fortran .................................................................................................... 61
2.6 ..................................................................................................... 83
2.7 ............................................................................................................. 84
3
3.1
3.2
3.3
3.4
3.5
3.6

m .............................................................................93
C/C++ compiler .................................................................................................. 94
m C/C++..................................................... 97
m C/C++........................................................... 111
VC++ m ........................................................................................... 118
VC++ MATLAB C Math Library............................................................. 122
VB MATLAB ................................................................................. 138

4 Simulink ...............................................................................143
4.1 ............................................................................................................... 143
4.2 ............................................................................................................... 144
4.3 Blocksets.................................................................................................................... 149
4.4 Simulink .................................................................................................... 150
4.5 ................................................................................................................... 152
4.6 C m .......................................................................... 158

Matlab/Simulink

IV

4.7 Blockset ................................................................................................ 165


4.8 ................................................................................................... 172
5
5.1
5.2
5.3
5.4

Real-Time Workshop .....................................................................................180


....................................................................................................... 180
................................................................................................... 181
RTW ..................................................................................................... 182
RTW ............................................................................................................. 192

6
6.1
6.2
6.3
6.4
6.5

TI DSP .........................................................................193
Developers Kit for TI DSP ............................................................................. 193
................................................................................................................... 193
Developers Kit for TI DSP .......................................................................... 195
Matlab TI DSP ............................................................................................. 196
Simulink C6701 EVM ........................................... 225

7 Xilinx FPGA .................................................................242


7.1 FPGA ............................................................................... 242
7.2 Xilinx Blockset .......................................................................................................... 243
7.3 VHDL ....................................................................................................... 247
7.4 ............................................................................................... 256
7.5 ................................................................................................................... 256
8
8.1
8.2
8.3
8.4
9

VxWorks ..............................................................................258
VxWorks/Tornado ..................................................................................................... 258
Simulink VxWorks ....................................................................................... 258
Tornado (VxWorks) Real-Time Target .................................................... 260
Tornado (VxWorks) Real-Time Target ................................................ 263
DSP ..........................................................................281

9.1 MATLAB R12.1 vs MATLAB 6.1 ........................................................................... 281


9.2 MATLAB R12.1 DSP .............................................. 283
9.3 MATLAB ................................................................................................. 284
9.4 Communications Toolbox.......................................................................................... 293
9.5 Filter Design Toolbox................................................................................................ 298
9.6 Image Processing Toolbox......................................................................................... 298
9.7 Matlab C/C++ Math/Graphics Library ...................................................................... 299
9.8 Signal Processing Toolbox ........................................................................................ 299
9.9 Wavelet Toolbox ....................................................................................................... 302

9.10

Simulink .......................................................................................................... 302

9.11
9.12
9.13
9.14
9.15
9.16
9.17
9.18
9.19
9.20
9.21
9.22
9.23
9.24

Stateflow .................................................................................................................. 303


CDMA Reference Blockset ..................................................................................... 304
Communications Blockset ....................................................................................... 306
DSP Blockset ........................................................................................................... 307
Motorola DSP Developers Kit................................................................................ 308
Xilinx Blockset ........................................................................................................ 311
Real-Time Workshop............................................................................................... 311
Developers Kit for TI DSP ..................................................................................... 312
Real-Time Windows Target..................................................................................... 313
RTW Embedded Coder............................................................................................ 313
Stateflow Coder ....................................................................................................... 313
Tornado (VxWorks) Real-Time Target ................................................................... 320
Xilinxs System Generator for Simulink ................................................................. 320
xPC Target ............................................................................................................... 320

............................................................................322

1
1.1

MATLAB

MATLAB MathWorks
MATLAB
MATLAB
MATLAB
z
z
z
z
z
z
z
z
z
MATLAB
MATLAB MATLAB
MATLAB
MATLAB http://www.mathworks.com/partners
MATLAB
MATLAB

MATLAB C/C++ MATLAB


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

Matlab/Simulink

2
MATLAB Toolbox

Version 6.1 (R12.1) 18-May-2001

Simulink

Version 4.1 (R12.1) 06-Apr-2001

Stateflow

Version 4.1 (R12.1) 21-May-2001

Stateflow Coder

Version 4.1 (R12.1) 21-May-2001

Real-Time Windows Target

Version 2.1 (R12.1) 02-Feb-2001

Real-Time Workshop

Version 4.1 (R12.1) 18-May-2001

CDMA Reference Blockset

Version 1.1 (R12.1) 18-May-2001

Communications Blockset

Version 2.0.1 (R12.1) 18-May-2001

Communications Toolbox

Version 2.0.1 (R12.1) 18-May-2001

Control System Toolbox

Version 5.1 (R12.1) 18-May-2001

DSP Blockset

Version 4.1 (R12.1) 18-May-2001

Data Acquisition Toolbox

Version 2.1 (R12.1) 06-Apr-2001

Database Toolbox

Version 2.2 (R12.1) 04-Jan-2001

Datafeed Toolbox

Version 1.3 (R12.1) 03-Jan-2001

Developer's Kit for TI(tm) DSP

Version 1.1 (R12.1) 08-Jun-2001

Dials & Gauges Blockset

Version 1.1.1 (R12.1) 02-Feb-2001

Symbolic Math Toolbox

Version 2.1.2 (R12.1) 11-Sep-2000

Filter Design Toolbox

Version 2.1 (R12.1) 01-Feb-2001

Financial Derivatives Toolbox

Version 1.0 (R12.1) 14-Aug-2000

Financial Time Series Toolbox

Version 1.1 (R12.1) 01-Dec-2000

Financial Toolbox

Version 2.1.3 (R12.1) 12-Mar-2001

Fixed-Point Blockset

Version 3.1 (R12.1) 18-May-2001

Fuzzy Logic Toolbox

Version 2.1.1 (R12.1) 18-May-2001

GARCH Toolbox

Version 1.0 (R12.1) 01-Jun-1999

Image Processing Toolbox

Version 3.1 (R12.1) 18-May-2001

Instrument Control Toolbox

Version 1.1 (R12.1) 18-May-2001

LMI Control Toolbox

Version 1.0.7 (R12.1) 18-May-2001

MATLAB Compiler

Version 2.2 (R12.1) 30-Mar-2001

MATLAB Report Generator

Version 1.2 (R12.1) 01-Apr-2001

MATLAB Web Server

Version 1.2.1 (R12.1) 23-Apr-2001

Mapping Toolbox

Version 1.2 (R12.1) 22-May-2000

Model Predictive Control Toolbox

Version 1.0.6 (R12.1) 18-May-2001

Motorola DSP Developer's Kit

Version 1.1 (R12.1) 01-Sep-2000

Mu-Analysis and Synthesis Toolbox

Version 3.0.6 (R12.1) 18-May-2001

Neural Network Toolbox

Version 4.0.1 (R12.1) 02-Feb-2001

Nonlinear Control Design Blockset

Version 1.1.5 (R12.1) 18-May-2001

Optimization Toolbox

Version 2.1.1 (R12.1) 18-May-2001

Partial Differential Equation Toolbox

Version 1.0.4(R12.1) 06-Apr-2001

Power System Blockset

Version 2.2 (R12.1) 06-Apr-2001

Real-Time Workshop Ada Coder

Version 4.1 (R12.1) 18-May-2001

Real-Time Workshop Embedded Coder

Version 2.0 (R12.1) 01-Mar-2001

Requirements Management Interface

Version 1.0.2 (R12.1) 30-Nov-2000

1 MATLAB
Robust Control Toolbox

Version 2.0.8 (R12.1) 18-May-2001

SB2SL (converts SystemBuild to Simu...

Version 2.2 (R12.1) 10-Apr-2001

Signal Processing Toolbox

Version 5.1 (R12.1) 06-Apr-2001

Simulink Performance Tools

Version 1.1 (R12.1) 18-May-2001

Simulink Report Generator

Version 1.2 (R12.1) 01-Apr-2001

Spline Toolbox

Version 3.0 (R12.1) 13-Mar-2000

Statistics Toolbox

Version 3.0 (R12.1) 01-Sep-2000

System Identification Toolbox

Version 5.0.1 (R12.1) 18-May-2001

Wavelet Toolbox

Version 2.1 (R12.1) 06-Apr-2001

xPC Target

Version 1.2 (R12.1) 09-Apr-2001

xPC Target Embedded Option

Version 1.2 (R12.1) 09-Apr-2001

MATLAB Toolbox Simulink

>> ver matlab


MATLAB Version 6.1.0.450 (R12.1) on PCWIN
MATLAB License Number: DEMO
MATLAB Toolbox

Version 6.1 (R12.1) 18-May-2001

>> ver Simulink


Simulink

Version 4.1 (R12.1) 06-Apr-2001

ver
>> which ver
D:\MATLAB6p1\toolbox\matlab\general\ver.m

ver
>> edit ver

ver MATLAB 1.1


ver
>> help ver
VER MATLAB, Simulink, and toolbox version information.
VER displays the current MATLAB and toolbox version numbers.
VER(TOOLBOX_DIR) displays the current version information for the
toolbox specified by the string TOOLBOX_DIR.

Matlab/Simulink

4
For example,
ver control

returns the version info for the Control System Toolbox.


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

1.2

1.1 ver

1.2

helpwin ver

: (
)

1 MATLAB

>> doc ver

1.3

1.3 doc ver

MATLAB

1.2

MATLAB

MATLAB 1.4

1.4 MATLAB

Matlab/Simulink

MATLAB Toolbox
1.4 MATLAB MATLAB MATLAB ToolboxMATLAB
Toolbox m MATLAB MATLAB
MATLAB Toolbox MATLAB
1.5 MATLAB

1.5 MATLAB

Toolboxes
Toolboxes ver MATLAB

Communications Toolbox

Version 2.0.1 (R12.1) 18-May-2001(comm)

Control System Toolbox

Version 5.1 (R12.1) 18-May-2001(control)

Data Acquisition Toolbox

Version 2.1 (R12.1) 06-Apr-2001(daq)

Database Toolbox

Version 2.2 (R12.1) 04-Jan-2001(database)

Datafeed Toolbox

Version 1.3 (R12.1) 03-Jan-2001(datafeed)

Symbolic Math Toolbox

Version 2.1.2 (R12.1) 11-Sep-2000(symbolic)

Filter Design Toolbox

Version 2.1 (R12.1) 01-Feb-2001(filterdesign)

Financial Derivatives Toolbox

Version 1.0 (R12.1) 14-Aug-2000(finderiv)

Financial Time Series Toolbox

Version 1.1 (R12.1) 01-Dec-2000(ftseries)

Financial Toolbox

Version 2.1.3 (R12.1) 12-Mar-2001(finance)

Fuzzy Logic Toolbox

Version 2.1.1 (R12.1) 18-May-2001(fuzzy)

GARCH Toolbox

Version 1.0 (R12.1) 01-Jun-1999(garch)

Image Processing Toolbox

Version 3.1 (R12.1) 18-May-2001(images)

Instrument Control Toolbox

Version 1.1 (R12.1) 18-May-2001(instrument)

1 MATLAB
LMI Control Toolbox

Version 1.0.7 (R12.1) 18-May-2001(lmi)

Mapping Toolbox

Version 1.2 (R12.1) 22-May-2000(map)

Model Predictive Control Toolbox

Version 1.0.6 (R12.1) 18-May-2001(mpc)

Mu-Analysis and Synthesis Toolbox Version 3.0.6 (R12.1) 18-May-2001(mutools)


Neural Network Toolbox

Version 4.0.1 (R12.1)

02-Feb-2001(nnet)

Optimization Toolbox

Version 2.1.1 (R12.1)

18-May-2001(opt)

:
:

Partial Differential Equation Toolbox Version 1.0.4 (R12.1) 06-Apr-2001(pde)

: Toolbox

Robust Control Toolbox

Signal Processing Toolbox

Version 2.0.8 (R12.1)

18-May-2001(robust)

Version 5.1 (R12.1) 06-Apr-2001(signal)

Spline Toolbox

Version 3.0 (R12.1)

13-Mar-2000(splines)

Statistics Toolbox

Version 3.0 (R12.1)

01-Sep-2000(stats)

System Identification Toolbox

Version 5.0.1 (R12.1)

18-May-2001(ident)

Wavelet Toolbox

Version 2.1 (R12.1)

06-Apr-2001(wavelet)

Signal Processing Toolbox


/Image Processing Toolbox
help/what

:
:

>> help signal

: (

Signal Processing Toolbox.


Version 5.1 (R12.1) 06-Apr-2001

:
: )

Filter analysis.
abs

- Magnitude.

angle

- Phase angle.

filternorm

- Compute the 2-norm or inf-norm of a digital filter.

freqs

- Laplace transform frequency response.

freqspace

- Frequency spacing for frequency response.

freqz

- Z-transform frequency response.

freqzplot

- Plot frequency response data.

fvtool

- Filter Visualization Tool (FVTool).

grpdelay

- Group delay.

impz

- Discrete impulse response.

unwrap

- Unwrap phase.

zplane

- Discrete pole-zero plot.

Filter implementation.
conv

- Convolution.

conv2

- 2-D convolution.

: angle

Matlab/Simulink

8
deconv

- Deconvolution.

fftfilt

- Overlap-add filter implementation.

filter

- Filter implementation.

filter2

- Two-dimensional digital filtering.

filtfilt

- Zero-phase version of filter.

filtic

- Determine filter initial conditions.

latcfilt

- Lattice filter implementation.

medfilt1

- 1-Dimensional median filtering.

sgolayfilt

- Savitzky-Golay filter implementation.

sosfilt

- Second-order sections (biquad) filter implementation.

upfirdn

- Up sample, FIR filter, down sample.

FIR filter design.


convmtx

- Convolution matrix.

cremez

- Complex and nonlinear phase equiripple FIR filter design.

fir1

- Window based FIR filter design - low, high, band, stop, multi.

fir2

- FIR arbitrary shape filter design using the frequency sampling method.

fircls

- Constrained Least Squares filter design arbitrary response.

fircls1

- Constrained Least Squares FIR filter design - low and highpass.

firls

- Optimal least-squares FIR filter design.

firrcos

- Raised cosine FIR filter design.

intfilt

- Interpolation FIR filter design.

kaiserord

- Kaiser window design based filter order estimation.

remez

- Optimal Chebyshev-norm FIR filter design.

remezord

- Remez design based filter order estimation.

sgolay

- Savitzky-Golay FIR smoothing filter design.

IIR digital filter design.


butter

- Butterworth filter design.

cheby1

- Chebyshev Type I filter design (passband ripple).

cheby2

- Chebyshev Type II filter design (stopband ripple).

ellip

- Elliptic filter design.

maxflat

- Generalized Butterworth lowpass filter design.

yulewalk

- Yule-Walker filter design.

IIR filter order estimation.


buttord

- Butterworth filter order estimation.

cheb1ord

- Chebyshev Type I filter order estimation.

cheb2ord

- Chebyshev Type II filter order estimation.

ellipord

- Elliptic filter order estimation.

Analog lowpass filter prototypes.

1 MATLAB
besselap

- Bessel filter prototype.

buttap

- Butterworth filter prototype.

cheb1ap

- Chebyshev Type I filter prototype (passband ripple).

cheb2ap

- Chebyshev Type II filter prototype (stopband ripple).

ellipap

- Elliptic filter prototype.

Analog filter design.


besself

- Bessel analog filter design.

butter

- Butterworth filter design.

cheby1

- Chebyshev Type I filter design.

cheby2

- Chebyshev Type II filter design.

ellip

- Elliptic filter design.

Analog filter transformation.


lp2bp

- Lowpass to bandpass analog filter transformation.

lp2bs

- Lowpass to bandstop analog filter transformation.

lp2hp

- Lowpass to highpass analog filter transformation.

lp2lp

- Lowpass to lowpass analog filter transformation.

Filter discretization.
bilinear

- Bilinear transformation with optional prewarping.

impinvar

- Impulse invariance analog to digital conversion.

Linear system transformations.


latc2tf

- Lattice or lattice ladder to transfer function conversion.

polystab

- Polynomial stabilization.

polyscale

- Scale roots of polynomial.

residuez

- Z-transform partial fraction expansion.

sos2ss

- Second-order sections to state-space conversion.

sos2tf

- Second-order sections to transfer function conversion.

sos2zp

- Second-order sections to zero-pole conversion.

ss2sos

- State-space to second-order sections conversion.

ss2tf

- State-space to transfer function conversion.

ss2zp

- State-space to zero-pole conversion.

tf2latc

- Transfer function to lattice or lattice ladder conversion.

tf2sos

- Transfer Function to second-order sections conversion.

tf2ss

- Transfer function to state-space conversion.

tf2zp

- Transfer function to zero-pole conversion.

zp2sos

- Zero-pole to second-order sections conversion.

zp2ss

- Zero-pole to state-space conversion.

zp2tf

- Zero-pole to transfer function conversion.

Matlab/Simulink

10
Windows.
bartlett

- Bartlett window.

barthannwin

- Modified Bartlett-Hanning window.

blackman

- Blackman window.

blackmanharris

- Minimum 4-term Blackman-Harris window.

bohmanwin

- Bohman window.

chebwin

- Chebyshev window.

gausswin

- Gaussian window.

hamming

- Hamming window.

hann

- Hann window.

kaiser

- Kaiser window.

nuttallwin

- Nuttall defined minimum 4-term Blackman-Harris window.

rectwin

- Rectangular window.

triang

- Triangular window.

tukeywin

- Tukey window.

window

- Window function gateway.

Transforms.
bitrevorder

- Permute input into bit-reversed order.

czt

- Chirp-z transform.

dct

- Discrete cosine transform.

dftmtx

- Discrete Fourier transform matrix.

fft

- Fast Fourier transform.

fft2

- 2-D fast Fourier transform.

fftshift

- Swap vector halves.

goertzel

- Second-order Goertzel algorithm.

hilbert

- Discrete-time analytic signal via Hilbert transform.

idct

- Inverse discrete cosine transform.

ifft

- Inverse fast Fourier transform.

ifft2

- Inverse 2-D fast Fourier transform.

Cepstral analysis.
cceps

- Complex cepstrum.

icceps

- Inverse Complex cepstrum.

rceps

- Real cepstrum and minimum phase reconstruction.

Statistical signal processing and spectral analysis.


cohere

- Coherence function estimate.

corrcoef

- Correlation coefficients.

corrmtx

- Autocorrelation matrix.

cov

- Covariance matrix.

csd

- Cross Spectral Density.

1 MATLAB
pburg

- Power Spectral Density estimate via Burg's method.

pcov

- Power Spectral Density estimate via the Covariance method.

peig

- Power Spectral Density estimate via the Eigenvector method.

periodogram

- Power Spectral Density estimate via the periodogram method.

pmcov

- Power Spectral Density estimate via the Modified Covariance method.

pmtm

- Power Spectral Density estimate via the Thomson multitaper method.

pmusic

- Power Spectral Density estimate via the MUSIC method.

psdplot

- Plot Power Spectral Density data.

pwelch

- Power Spectral Density estimate via Welch's method.

pyulear

- Power Spectral Density estimate via the Yule-Walker AR Method.

rooteig

- Sinusoid frequency and power estimation via the eigenvector algorithm.

rootmusic

- Sinusoid frequency and power estimation via the MUSIC algorithm.

tfe

- Transfer function estimate.

xcorr

- Cross-correlation function.

xcorr2

- 2-D cross-correlation.

xcov

- Covariance function.

Parametric modeling.
arburg

- AR parametric modeling via Burg's method.

arcov

- AR parametric modeling via covariance method.

armcov

- AR parametric modeling via modified covariance method.

aryule

- AR parametric modeling via the Yule-Walker method.

ident

- See the System Identification Toolbox.

invfreqs

- Analog filter fit to frequency response.

invfreqz

- Discrete filter fit to frequency response.

prony

- Prony's discrete filter fit to time response.

stmcb

- Steiglitz-McBride iteration for ARMA modeling.

Linear Prediction.
ac2rc

- Autocorrelation sequence to reflection coefficients conversion.

ac2poly

- Autocorrelation sequence to prediction polynomial conversion.

is2rc

- Inverse sine parameters to reflection coefficients conversion.

lar2rc

- Log area ratios to reflection coefficients conversion.

levinson

- Levinson-Durbin recursion.

lpc

- Linear Predictive Coefficients using autocorrelation method.

lsf2poly

- Line spectral frequencies to prediction polynomial conversion.

poly2ac

- Prediction polynomial to autocorrelation sequence conversion.

poly2lsf

- Prediction polynomial to line spectral frequencies conversion.

poly2rc

- Prediction polynomial to reflection coefficients conversion.

rc2ac

- Reflection coefficients to autocorrelation sequence conversion.

rc2is

- Reflection coefficients to inverse sine parameters conversion.

rc2lar

- Reflection coefficients to log area ratios conversion.

11

Matlab/Simulink

12
rc2poly

- Reflection coefficients to prediction polynomial conversion.

rlevinson

- Reverse Levinson-Durbin recursion.

schurrc

- Schur algorithm.

Multirate signal processing.


decimate

- Resample data at a lower sample rate.

downsample

- Downsample input signal.

interp

- Resample data at a higher sample rate.

interp1

- General 1-D interpolation. (MATLAB Toolbox)

resample

- Resample sequence with new sampling rate.

spline

- Cubic spline interpolation.

upfirdn

- Up sample, FIR filter, down sample.

upsample

- Upsample input signal.

Waveform generation.
chirp

- Swept-frequency cosine generator.

diric

- Dirichlet (periodic sinc) function.

gauspuls

- Gaussian RF pulse generator.

gmonopuls

- Gaussian monopulse generator.

pulstran

- Pulse train generator.

rectpuls

- Sampled aperiodic rectangle generator.

sawtooth

- Sawtooth function.

sinc

- Sinc or sin(pi*x)/(pi*x) function

square

- Square wave function.

tripuls

- Sampled aperiodic triangle generator.

vco

- Voltage controlled oscillator.

Specialized operations.
buffer

- Buffer a signal vector into a matrix of data frames.

cell2sos

- Convert cell array to second-order-section matrix.

cplxpair

- Order vector into complex conjugate pairs.

demod

- Demodulation for communications simulation.

dpss

- Discrete prolate spheroidal sequences (Slepian sequences).

dpssclear

- Remove discrete prolate spheroidal sequences from database.

dpssdir

- Discrete prolate spheroidal sequence database directory.

dpssload

- Load discrete prolate spheroidal sequences from database.

dpsssave

- Save discrete prolate spheroidal sequences in database.

eqtflength

- Equalize the length of a discrete-time transfer function.

modulate

- Modulation for communications simulation.

seqperiod

- Find minimum-length repeating sequence in a vector.

sos2cell

- Convert second-order-section matrix to cell array.

specgram

- Spectrogram, for speech signals.

1 MATLAB
stem

- Plot discrete data sequence.

strips

- Strip plot.

udecode

- Uniform decoding of the input.

uencode

- Uniform quantization and encoding of the input into N-bits.

Graphical User Interfaces


fdatool

- Filter Design and Analysis Tool.

sptool

- Signal Processing Tool.

See also SIGDEMOS, AUDIO, and, in the Filter Design Toolbox, FILTERDESIGN.
>> help images
Image Processing Toolbox.
Version 3.1 (R12.1) 18-May-2001
Release information.
images/Readme - Display information about current and previous versions.
Image display.
colorbar

- Display colorbar (MATLAB Toolbox).

getimage

- Get image data from axes.

image

- Create and display image object (MATLAB Toolbox).

imagesc

- Scale data and display as image (MATLAB Toolbox).

immovie

- Make movie from multiframe image.

imshow

- Display image.

montage

- Display multiple image frames as rectangular montage.

movie

- Play recorded movie frames.

subimage

- Display multiple images in single figure.

truesize

- Adjust display size of image.

warp

- Display image as texture-mapped surface.

Image file I/O.


dicominfo

- Read metadata from a DICOM message.

dicomread

- Read a DICOM image.

dicom-dict.txt

- Text file containing DICOM data dictionary.

imfinfo

- Return information about image file (MATLAB Toolbox).

imread

- Read image file (MATLAB Toolbox).

imwrite

- Write image file (MATLAB Toolbox).

Image arithmetic.
imabsdiff

- Compute absolute difference of two images.

13

Matlab/Simulink

14
imadd

- Add two images, or add constant to image.

imcomplement

- Complement image.

imdivide

- Divide two images, or divide image by constant.

imlincomb

- Compute linear combination of images.

immultiply

- Multiply two images, or multiply image by constant.

imsubtract

- Subtract two images, or subtract constant from image.

Geometric transformations.
checkerboard

- Create checkerboard image.

findbounds

- Find output bounds for geometric transformation.

fliptform

- Flip the input and output roles of a TFORM struct.

imcrop

- Crop image.

imresize

- Resize image.

imrotate

- Rotate image.

imtransform

- Apply geometric transformation to image.

makeresampler

- Create resampler structure.

maketform

- Create geometric transformation structure (TFORM).

tformarray

- Apply geometric transformation to N-D array.

tformfwd

- Apply forward geometric transformation.

tforminv

- Apply inverse geometric transformation.

Image registration.
cpstruct2pairs

- Convert CPSTRUCT to valid pairs of control points.

cp2tform

- Infer geometric transformation from control point pairs.

cpcorr

- Tune control point locations using cross-correlation.

cpselect

- Control point selection tool.

normxcorr2

- Normalized two-dimensional cross-correlation.

Pixel values and statistics.


corr2

- Compute 2-D correlation coefficient.

imcontour

- Create contour plot of image data.

imhist

- Display histogram of image data.

impixel

- Determine pixel color values.

improfile

- Compute pixel-value cross-sections along line segments.

mean2

- Compute mean of matrix elements.

pixval

- Display information about image pixels.

regionprops

- Measure properties of image regions.

std2

- Compute standard deviation of matrix elements.

Image analysis.
edge

- Find edges in intensity image.

qtdecomp

- Perform quadtree decomposition.

1 MATLAB
qtgetblk

- Get block values in quadtree decomposition.

qtsetblk

- Set block values in quadtree decomposition.

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.

Linear 2-D filter design.


freqspace

- Determine 2-D frequency response spacing (MATLAB Toolbox).

freqz2

- Compute 2-D frequency response.

fsamp2

- Design 2-D FIR filter using frequency sampling.

ftrans2

- Design 2-D FIR filter using frequency transformation.

fwind1

- Design 2-D FIR filter using 1-D window method.

fwind2

- Design 2-D FIR filter using 2-D window method.

Image deblurring.
deconvblind

- Deblur image using blind deconvolution.

deconvlucy

- Deblur image using Lucy-Richardson method.

deconvreg

- Deblur image using regularized filter.

deconvwnr

- Deblur image using Wiener filter.

edgetaper

- Taper edges using point-spread function.

otf2psf

- Optical transfer function to point-spread function.

psf2otf

- Point-spread function to optical transfer function.

Image transforms.
dct2

- 2-D discrete cosine transform.

dctmtx

- Discrete cosine transform matrix.

fft2

- 2-D fast Fourier transform (MATLAB Toolbox).

fftn

- N-D fast Fourier transform (MATLAB Toolbox).

fftshift

- Reverse quadrants of output of FFT (MATLAB Toolbox).

idct2

- 2-D inverse discrete cosine transform.

ifft2

- 2-D inverse fast Fourier transform (MATLAB Toolbox).

: -

Matlab/Simulink

16
ifftn

N-D inverse fast Fourier transform (MATLAB Toolbox).

iradon

- Compute inverse Radon transform.

phantom

- Generate a head phantom image.

radon

- Compute Radon transform.

: -

Neighborhood and block processing.


bestblk

- Choose block size for block processing.

blkproc

- Implement distinct block processing for image.

col2im

- Rearrange matrix columns into blocks.

colfilt

- Columnwise neighborhood operations.

im2col

- Rearrange image blocks into columns.

nlfilter

- Perform general sliding-neighborhood operations.

Morphological operations (intensity and binary images).


conndef

- Default connectivity.

imbothat

- Perform bottom-hat filtering.

imclearborder

- Suppress light structures connected to image border.

imclose

- Close image.

imdilate

- Dilate image.

imerode

- Erode image.

imextendedmax

- Extended-maxima transform.

imextendedmin

- Extended-minima transform.

imfill

- Fill image regions and holes.

imhmax

- H-maxima transform.

imhmin

- H-minima transform.

imimposemin

- Impose minima.

imopen

- Open image.

imreconstruct

- Morphological reconstruction.

imregionalmax

- Regional maxima.

imregionalmin

- Regional minima.

imtophat

- Perform tophat filtering.

watershed

- Watershed transform.

Morphological operations (binary images)


applylut

- Perform neighborhood operations using lookup tables.

bwarea

- Compute area of objects in binary image.

bwareaopen

- Binary area open (remove small objects).

bwdist

- Compute distance transform of binary image.

bweuler

- Compute Euler number of binary image.

bwhitmiss

- Binary hit-miss operation.

bwlabel

- Label connected components in 2-D binary image.

bwlabeln

- Label connected components in N-D binary image.

1 MATLAB
bwmorph

- Perform morphological operations on binary image.

bwpack

- Pack binary image.

bwperim

- Determine perimeter of objects in binary image.

bwselect

- Select objects in binary image.

bwulterode

- Ultimate erosion.

bwunpack

- Unpack binary image.

makelut

- Construct lookup table for use with applylut.

Structuring element (STREL) creation and manipulation.


getheight

- Get strel height.

getneighbors

- Get offset location and height of strel neighbors

getnhood

- Get strel neighborhood.

getsequence

- Get sequence of decomposed strels.

isflat

- Return true for flat strels.

reflect

- Reflect strel about its center.

strel

- Create morphological structuring element.

translate

- Translate strel.

Region-based processing.
roicolor

- Select region of interest, based on color.

roifill

- Smoothly interpolate within arbitrary region.

roifilt2

- Filter a region of interest.

roipoly

- Select polygonal region of interest.

Colormap manipulation.
brighten

- Brighten or darken colormap (MATLAB Toolbox).

cmpermute

- Rearrange colors in colormap.

cmunique

- Find unique colormap colors and corresponding image.

colormap

- Set or get color lookup table (MATLAB Toolbox).

imapprox

- Approximate indexed image by one with fewer colors.

rgbplot

- Plot RGB colormap components (MATLAB Toolbox).

Color space conversions.


hsv2rgb

- Convert HSV values to RGB color space (MATLAB Toolbox).

ntsc2rgb

- Convert NTSC values to RGB color space.

rgb2hsv

- Convert RGB values to HSV color space (MATLAB Toolbox).

rgb2ntsc

- Convert RGB values to NTSC color space.

rgb2ycbcr

- Convert RGB values to YCBCR color space.

ycbcr2rgb

- Convert YCBCR values to RGB color space.

Array operations.
circshift

- Shift array circularly.

17

Matlab/Simulink

18
padarray

- Pad array.

Image types and type conversions.


dither

- Convert image using dithering.

gray2ind

- Convert intensity image to indexed image.

grayslice

- Create indexed image from intensity image by thresholding.

graythresh

- Compute global image threshold using Otsu's method.

im2bw

- Convert image to binary image by thresholding.

im2double

- Convert image array to double precision.

im2uint8

- Convert image array to 8-bit unsigned integers.

im2uint16

- Convert image array to 16-bit unsigned integers.

ind2gray

- Convert indexed image to intensity image.

im2mis

- Convert image to Java MemoryImageSource.

ind2rgb

- Convert indexed image to RGB image (MATLAB Toolbox).

isbw

- Return true for binary image.

isgray

- Return true for intensity image.

isind

- Return true for indexed image.

isrgb

- Return true for RGB image.

label2rgb

- Convert label matrix to RGB image.

mat2gray

- Convert matrix to intensity image.

rgb2gray

- Convert RGB image or colormap to grayscale.

rgb2ind

- Convert RGB image to indexed image.

Toolbox preferences.
iptgetpref

- Get value of Image Processing Toolbox preference.

iptsetpref

- Set value of Image Processing Toolbox preference.

Demos.
dctdemo

- 2-D DCT image compression demo.

edgedemo

- Edge detection demo.

firdemo

- 2-D FIR filtering and filter design demo.

imadjdemo

- Intensity adjustment and histogram equalization demo.

landsatdemo

- Landsat color composite demo.

nrfiltdemo

- Noise reduction filtering demo.

qtdemo

- Quadtree decomposition demo.

roidemo

- Region-of-interest processing demo.

Slide shows.
ipss001

- Region labeling of steel grains.

ipss002

- Feature-based logic.

ipss003

- Correction of nonuniform illumination.

: -

1 MATLAB

19

Extended-examples.
ipexindex

- Index of extended examples.

ipexsegmicro

- Segmentation to detect microstructures.

ipexsegcell

- Segmentation to detect cells.

ipexsegwatershed

- Watershed segmentation.

ipexgranulometry

- Granulometry of stars.

ipexdeconvwnr

- Wiener deblurring.

ipexdeconvreg

- Regularized deblurring.

ipexdeconvlucy

- Lucy-Richardson deblurring.

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

ipexnormxcorr2

- Normalized cross-correlation.

: firls

ipexrotate

- Rotation and scale recovery.

ipexregaerial

- Aerial photo registration.

: Contents
: fir2

: arburg
: firrcos
: arcov
: freqs

>> what signal

: armcov
M-files in directory D:\MATLAB6p1\toolbox\signal\signal

: freqz
: aryule

Contents

fir2

psdplot

aboutsignaltbx

fircls

pulstran

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

besselap

gmonopuls

rectwin

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

bscost

idct

sawtooth

buffer

impinvar

schurrc

: freqzplot
: barthannwin

: goertzel
: bilinear

: blackmanharris
: hanning
: bohmanwin

Matlab/Simulink

20
buttap

impz

seqperiod

butter

impzlength

sgolay

buttord

interp

sgolayfilt

cceps

intfilt

signalpolyutils

cell2sos

invfreqs

sigprivate

cheb1ap

invfreqz

sinc

cheb1ord

is2rc

sos2cell

cheb2ap

kaiser

sos2ss

cheb2ord

kaiserord

sos2tf

chebwin

kratio

sos2zp

cheby1

lar2rc

sosfilt

cheby2

latc2tf

specgram

chirp

latcfilt

specplot

cohere

levinson

spectrum

convmtx

lp2bp

square

corrmtx

lp2bs

ss2sos

cremez

lp2hp

stmcb

csd

lp2lp

strips

czt

lpc

tf2latc

datawrap

lsf2poly

tf2sos

dct

maxflat

tfe

decimate

medfilt1

triang

demod

modulate

tripuls

dftmtx

nuttallwin

tukeywin

diric

pburg

udecode

downsample

pcov

uencode

dpss

peig

upfirdn

dpssclear

periodogram

upsample

dpssdir

pmcov

vco

dpssload

pmem

vratio

dpsssave

pmtm

window

ellip

pmusic

xcorr

ellipap

poly2ac

xcorr2

ellipord

poly2lsf

xcov

eqtflength

poly2rc

yulewalk

fftfilt

polyscale

zp2sos

filternorm

polystab

zplane

filtfilt

prony

filtic

psd

fir1

psdoptions

MAT-files in directory D:\MATLAB6p1\toolbox\signal\signal

1 MATLAB

mtlb

21

vcosig

MEX-files in directory D:\MATLAB6p1\toolbox\signal\signal


buffer

levinson

latcfilt

seqperiod

upfirdn

>> what images


M-files in directory D:\MATLAB6p1\toolbox\images\images
Contents

imdilate

: Contents

Readme

imdivide

applylut

imerode

bestblk

imextendedmax

blkproc

imextendedmin

bmpread

imfeature

bmpwrite

imfill

bwarea

imfilter

bwareaopen

imhist

bwdist

imhmax

bweuler

imhmin

bwfill

imimposemin

bwhitmiss

imlincomb

bwlabel

immovie

bwlabeln

immultiply

bwmorph

imnoise

bwpack

imopen

bwperim

impixel

bwselect

improfile

bwulterode

imreconstruct

bwunpack

imregionalmax

checkerboard

imregionalmin

circshift

imresize

cmgamdef

imrotate

cmgamma

imshow

cmpermute

imslice

cmunique

imsubtract

col2im

imtophat

colfilt

imtransform

conndef

imzoom

Matlab/Simulink

22
convmtx2

ind2gray

corr2

iptgetpref

cp2tform

iptsetpref

cpcorr

iradon

cpselect

isbw

cpselectswitchyard

isgray

cpstruct2pairs

isind

dct2

isrgb

dctmtx

label2rgb

dctmtx2

makelut

deconvblind

makeresampler

deconvlucy

maketform

deconvreg

mat2gray

deconvwnr

mean2

dicominfo

medfilt2

dicomread

mfilter2

dilate

montage

dither

nlfilter

edge

normxcorr2

edgetaper

ntsc2rgb

erode

ordfilt2

findbounds

otf2psf

fliptform

padarray

freqz2

pcxread

fsamp2

pcxwrite

fspecial

phantom

ftrans2

pixval

fwind1

psf2otf

fwind2

qtdecomp

getimage

qtgetblk

getline

qtsetblk

getpts

radon

getrect

regionprops

gifread

rgb2gray

gifwrite

rgb2ind

gray2ind

rgb2ntsc

grayslice

rgb2ycbcr

graythresh

roicolor

hdfpeek

roifill

hdfwrite

roifilt2

histeq

roipoly

idct2

std2

: convmtx2

: fliptform

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

23

imcontour
imcrop
MAT-files in directory D:\MATLAB6p1\toolbox\images\images
dicom-dict
MEX-files in directory D:\MATLAB6p1\toolbox\images\images
applylut

imabsdiff

bwpack

imlincomb

bwunpack

imreconstruct

imregionalmax

Classes in directory D:\MATLAB6p1\toolbox\images\images


strel

Compiler
MATLAB Compiler MATLAB m C/C++
Borland C/C++VC++ MathWorks
C/C++ MathWorks C/C++
Matlab m
C/C++ MATCOM

Matlab/Simulink

24

http://www.google.com MATCOM

Simulink
1.4 Simulink Matlab
1.6 Simulink

1.6 Simulink

Simulink
Simulink m C
Simulink Matlab
Simulink Matlab Matlab

Blocksets
Blocksets Simulink
MathWorks
DSP Blockset
FFT/FCT 1.7 1.8
1.9 MathWorks Power System Blockset Communications

1 MATLAB

25

BlocksetBlocksets Simulink Simulink Library Browser


MATLAB
1.10

1.7 DSP

1.8

1.9

26

Matlab/Simulink

1.10

Simulink

Real-Time WorkshopRTW
Real-Time WorkshopRTW Simulink RTW
Simulink RTW 1.11

1.11 Real-Time Workshop

: .
: (
: )
: (
: )

1 MATLAB

27

Real-Time Workshop

Stateflow
Stateflow Simulink

1.12

1.12

Locked Unlocked

1.12

Locked
Unlocked
Unlocked
Locked 1.12 Locked

Stateflow Simulink
Simulink

Stateflow Coder
Stateflow Coder Stateflow C
C
MATLAB Toolbox Simulink

: (
: )
: (
: )

Matlab/Simulink

28

Blocksets Stateflow Matlab Simulink


Matlab Simulink Simulink
Matlab

1.3

MATLAB

MATLAB 1.13

1.13

MATLAB

Matlab C

Matlab
Simulink
/DSP

Simulink

Simulink Real-Time Workshop


TI DSP/CCS IDE C WindRiver VxWorks/Tornado C RealTime Workshop 1.11 Xilinx MathWorks
Matlab/Simulink System Generator for Simulink Simulink
Xilinx FPGA VHDL Altera MathWorks

:
:

1 MATLAB

29

Matlab/Simulink DSPBuilder Simulink Altera FPGA


VHDL
1.13 MATLAB MathWorks
MATLAB
z
z
z
z
z
z

1.4

MATLAB

MATLAB R12.1 Product MATLAB


Document MATLAB MATLAB
Windows
1. F: MATLAB R12.1 Product
MATLAB R12.1 Product \\YoungSun\matlabr12p1
2. 1.14
F:\setup.exe \\YoungSun\matlabr12p1\setup.exe 1.14
MATLAB
3. Help 1.15
Cancel 1.16
1.16 Yes No
Next 1.17
4. 1.17 MATLAB MathWorks Personal License
PasswordPLP PLP MATLAB
Get my PLP Internet PLP MathWorks
Last Name Access Number
MATLAB PLP Next 1.18

:
: (
: )
: (
: )
:
:
:
:
:
: (
: )
:
:
:

30

Matlab/Simulink

1.14

Welcome to The MathWorks Installer

1.15 MATLAB

1.16

1 MATLAB

31

1.17 Personal License Password

1.18

License Agreement

5. 1.18 MathWorks Yes


1.19
6. 1.19 Next
1.20 Yes Internet
MATLAB No 1.21

:
: 8
: 19
:

Matlab/Simulink

32

1.19 Customer Information

1.20 Check for Updates and New Releases

7. 1.21
MATLAB
Windows Program Files
z

z
z

1 MATLAB

33

1.21 Product List

MATLAB /
PLP MATLAB

MATLAB MATLAB
MATLAB MATLAB
MATLAB
1.21
MATLAB MATLAB

Next 1.22 1.21

1.22

Installation Status

: 22
:
: (
: )

: (
: )

34

Matlab/Simulink

8. 1.23 MATLAB
MATLAB 1.24
1.21 Real-Time Windows Target 1.25
Real-Time Windows Target Next 1.25

: (
: )
:

1.23

File Extension Warning

1.24 Product Configuration Notes

1 MATLAB

35

9. 1.25 MATLAB
Internet MATLAB

1.25

Installation Complete

MATLAB
license.txt MATLAB
z MATLAB
z
\BIN\WIN32 MATLAB
LICENSE.DAT
License
MATLAB.EXE
MATLAB
*.DLL*.EXE*.BAT

\DEMOS MATLAB
\EXTERN MATLAB
\EXAMPLES MATLAB CFortran
\INCLUDE MATLAB
\LIB

\SRC
MEX C
\FLEXLM FLEXlm
\HELP MATLAB HTML PDF
\JA MATLAB
\JAVA MATLAB Java
\NOTEBOOK MATLAB Notebook
z

Matlab/Simulink

36

\SYS MATLAB
\GHOSTSCRIPT\BIN
GhostScript
PostScript GhostScript
\GHOSTSCRIPT\FONTS
\GHOSTSCRIPT\PS_FILES
PostScript
\PERL\WIN32 ActiveState Perl
\RTW Real-Time Workshop
\Simulink Simulink S-
\STATEFLOW Stateflow
\TOOLBOX MATLAB
\LOCAL Matlab

: Matalb

\MATLAB
\AUDIO
I/O
\DATAFUN
Fourier
\DATATYPES

\DEMOS

\ELFUN

\ELMAT

\FUNFUN

\GENERAL

\GRAPH2D

\GRAPH3D

\GRAPHICS

\IOFUN
I/O
\LANG
m
\MATFUN

\OPS

\POLYFUN

\SPARFUN

\SPECFUN

\SPECGRAPH

\STRFUN

\TIMEFUN

\UITOOLS

\VERCTRL

\WINFUN
Window

\UNINSTALL MATLAB Uninstaller
\WORK

:
:

:
:

1 MATLAB

37

1.5

MATLAB

MATLAB MATLAB Product


PDF install_guide.pdf MATLAB
http://www.mathworks.com
MATLAB Windows MATLAB
MATLAB 1.26
MATLAB R12.1 %MATLABROOT% d:\MATLAB6p1 MATLAB6p1
MATLAB R12.1 MATLAB 6 plus 1 MATLAB 6.1
MATLAB matlabroot MATLAB
>> matlabroot
ans =
D:\MATLAB6p1

1.26 MATLAB

: (
: )

Matlab/Simulink

38

MATLAB
z Command Window MATLAB
MATLAB MATLAB m
m
Launch Pad
Launch Pad MATLAB

z Workspace MATLAB
MATLAB MATLAB

z Command History MATLAB


MATLAB m
z Current Diretory MATLAB
MATLAB MATLAB

1.26 MATLAB d:\MATLAB6p1\work


MATLAB e:\material\study
MATLAB 1.27
e:\material\study MATLAB MATLAB
MATLAB 5.3 MATLAB
D:\MATLAB6p1\bin\win32\matlab.exe /nodesktop 1.28
MATLAB 1.29 MATLAB

1.27 MATLAB

1 MATLAB

39

1.28 MATLAB

1.29

MATLAB 5.3

MATLAB %MATLABROOT%\toolbox\local\
matlabrc.m MATLAB
matlabrc.m
%MATLABROOT%\toolbox\local startup.m matlabrc
startup.m 1.30 1.31
matlabrc.m MATLAB 1.32

Matlab/Simulink

40

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

1.31

%MATLABROOT%\toolbox\local\matlabrc.m

MATLAB MATLAB exit quit


%MATLABROOT%\toolbox\local finish.m
finish.m %MATLABROOT%\
toolbox\local m finishsav.m finishdlg.m finish.m
exit quit MATLAB
save MATLAB MATLAB

: (

: )

1 MATLAB

1.32

41

MATLAB

%MATLABROOT%\toolbox\local matlabrc.m
startup.m finish.m MATLAB 1.33

1.33

%MATLABROOT%\toolbox\local

PIII600+Windows 2000+1024X768
+32 matlabrc.m
MATLAB
%MATLABRC Master startup M-file.
% MATLABRC is automatically executed by MATLAB during startup.
% It establishes the MATLAB path, sets the default figure size,
% and sets a few uicontrol defaults.

Matlab/Simulink

42
%
%

On multi-user or networked systems, the system manager can put

any messages, definitions, etc. that apply to all users here.

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

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

43

Matlab/Simulink

44

else % for screens that aren't so high


mwwidth = 512; mwheight = 384;
left = (width-mwwidth)/2;
bottom = height-mwheight-76;
end
end
rect = [ left bottom mwwidth mwheight ];
set(0, 'defaultfigureposition',rect);

end

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

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

45

Matlab/Simulink

46
if usejava('mwt')
initprefs
end
%% Text-based preferences

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

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

%MATLABRC Master startup M-file.


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

On multi-user or networked systems, the system manager can put

any messages, definitions, etc. that apply to all users here.

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

2002-9-16 17:38:00

% Set default warning level to WARNING BACKTRACE. See help warning.


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

rect = [ left bottom mwwidth mwheight ];


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

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

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

MathWorks
MathWorks MATLAB
z Matlab
z Simulink
Matlab 4 Simulink

2.1

Matlab MATLAB
MATLAB Compiler
MATLAB C/C++ Math Library MATCOM
Matlab CC++
MATLAB

MATLAB m
Matlab
C

1
1.5 x1 + x 2 + 2 x3 = 2.5

3x1 x 2 + x3 = 5
x1 + 3x 2 + 5 x3 = 8

Matlab MATLAB :
>> A=[-1.5 1 2;3 -1 1;-1 3 5];
>> b=[2.5;5;8];
>> x=A\b
x=

:
:

M atlab/Sim ulink
0.7500
-0.6250
2.1250

C Microsoft Visual C/C++ version 6.0

: (
: )
:

//solver.c
//used to solve A*X=b,
//where A=[-1.5 1 2;3 -1 1;-1 3 5], b=[2.5;5;8].
#include "stdio.h"
void main()
{
double A[3][3]={{-1.5,1,2},{3,-1,1},{-1,3,5}};
double b[3]={2.5,5,8};
double invA[3][3],X[3];
int i;
// the determinant of A
double deltaA=A[0][0]*A[1][1]*A[2][2]+A[1][0]*A[2][1]*A[0][2]+
A[2][0]*A[1][2]*A[0][1]-(A[0][2]*A[1][1]*A[2][0]+
A[0][0]*A[2][1]*A[1][2]+A[0][1]*A[1][0]*A[2][2]);
//the inversion of A
invA[0][0]=1/deltaA*(A[1][1]*A[2][2]-A[1][2]*A[2][1]);
invA[1][0]=-1/deltaA*(A[1][0]*A[2][2]-A[1][2]*A[2][0]);
invA[2][0]=1/deltaA*(A[1][0]*A[2][1]-A[1][1]*A[2][0]);
invA[0][1]=-1/deltaA*(A[0][1]*A[2][2]-A[2][1]*A[0][2]);
invA[1][1]=1/deltaA*(A[0][0]*A[2][2]-A[2][0]*A[0][2]);
invA[2][1]=-1/deltaA*(A[0][0]*A[2][1]-A[0][1]*A[2][0]);
invA[0][2]=1/deltaA*(A[0][1]*A[1][2]-A[0][2]*A[1][1]);
invA[1][2]=-1/deltaA*(A[0][0]*A[1][2]-A[0][2]*A[1][0]);
invA[2][2]=1/deltaA*(A[0][0]*A[1][1]-A[0][1]*A[1][0]);
printf("The solution X is\n");
for(i=0;i<3;i++)
{
X[i]=invA[i][0]*b[0]+invA[i][1]*b[1]+invA[i][2]*b[2];
printf("%f\n",X[i]);
}

49

Matlab C Matlab
A mn b mp X
n p C
m m m
m

2.2

m m MATLAB
m MATLAB 1 m

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

% m m solver.m
MATLAB solver
>> solver
X=
0.7500
-0.6250
2.1250

m MATLAB solver
MATLAB whos MATLAB
Ab X
>> whos

:
:
:

Matlab/Simulink

50
Name

Size

Bytes Class

33

72 double array

31

24 double array

31

24 double array

Grand total is 15 elements using 120 bytes

2.3

m function MATLAB 2.1

2.1 MATLAB

MATLAB function MATLAB


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

:
:

51

m
m MATLAB
m
31
31
m

m m

: (
: )
:

[] m m

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

2.2
mymean.m 2.3 help helpwin

>> help mymean

: []

Matlab/Simulink

52

MYMEAN Average or mean value.


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

2.4

2.2 helpwin mymean

:
:
:
: mymean.m
2.3
help helpwin

2.3

2.4

mymean.m helpwin mymean

:
:

53
: >> help mymean

H1 help line
H1 help line lookfor
Lookfor H1 help line
>> lookfor 'average or mean'

MYMEAN Average or mean


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

MYMEAN Average or mean value.


MEAN Average or mean value.
MOT563_MEAN Average or mean value.
MOT566_MEAN Average or mean value.
NANMEAN Average or mean ignoring NaNs.

m
m 2.5
2.4 mymean.m
helpwin mymean

: ,

2.5

2 m 2.6 m

z varargin
z nargin length(varargin
z {}
2.6 x,y
z 1 N

:
:
:

: )
: (
: )
:
: (
: )

Matlab/Simulink

54

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

2~4
6~11 1 1

13~17 x y

:
:

:
:

2.6 m
z
z
z

19~20 x 0 y 0
22
23

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

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

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

:
:
:

55

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

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

:
:
:
:

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

3 m 2.9

z varargout
z nargout length(varargout
z {}

: >> myvarin([0 1])


Usage:myvarin([x1,y1],[x2,y2]
,...,[xN,yN]),where N>=2
Input more than one
points,Please!
>> myvarin
Usage:myvarin([x1,y1],[x2,y2]
,...,[xN,yN]),where N>=2
Input more than one
points,Please!
: )

Matlab/Simulink

56

2.9 x,y
z 1 N

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

2~4
6~11 0 0

: (
: )
: (
: )
:
:

2.9 m
z

13~17 [0 9]x,y

>> p1=myvarout
p1 =
6

>> [p1 p2 p3]=myvarout


p1 =
4

p2 =
9

:
:
:
: (
: )

57
:

p3 =
4

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

2.4

Toolboxes

MATLAB Toolboxes
MATLAB
MATLAB Toolbox
MATLAB
MATLAB MATLAB
z MATLAB

: (
: )

Signal Processing Toolbox


z Image Processing Toolbox
z Wavelet Toolbox
Matlab C/C++

MATLAB Compiler
MATLAB C/C++ Math Library
z MATLAB C/C++ Graphics Library
MATLAB 1
help
helpwin doc Data Acquisition Toolbox
z
z

:
: 1.6
: (
: )

>> help daq


Data Acquisition Toolbox.
Version 2.1

(R12.1) 06-April-2001

Data acquisition object construction.


daq/analoginput

- Construct analog input object.

daq/analogoutput

- Construct analog output object.

daq/digitalio

- Construct digital input/output object.

Matlab/Simulink

58

Getting and setting parameters.


daqdevice/get

- Get value of data acquisition object property.

daqdevice/set

- Set value of data acquisition object property.

setverify

- Set and return value of data acquisition object property.


:
property.

Execution.
daqdevice/start

- Start object running.

stop

- Stop object running and logging/sending.

trigger

- Manually initiate logging/sending for running object.

waittilstop

- Wait for the object to stop running.

Analog input functions.


addchannel

- Add channels to analog input object.

addmuxchannel

- Add mux'd channels to analog input object.

flushdata

- Remove data from engine.

getdata

- Return acquired data samples.

getsample

- Immediately acquire a single sample.

muxchanidx

- Return scan channel index associated with mux board.

peekdata

- Preview most recent acquired data.

Analog output functions.


addchannel

- Add channels to analog output object.

putdata

- Queue data samples for output.

putsample

- Immediately output single sample to object.

Digital input/output functions.


addline

- Add lines to digital input/output object.

getvalue

- Read line values.

putvalue

- Write line values.

General.
binvec2dec

Convert binary vector to decimal number.

daq/private/clear

- Clear data acquisition object from the workspace.

daqcallback

- Display event information for specified event.

daqfind

- Find specified data acquisition objects.

daqmem

- Allocate or display memory for one or more device objects.

daqread

- Read Data Acquisition Toolbox (.daq) data file.

daqregister

- Register or unregister adaptor DLLs.

daqreset

- Delete and unload all data acquisition objects and DLLs.

daqdevice/delete

- Remove data acquisition objects from workspace and engine.

dec2binvec

- Convert decimal number to binary vector.

:
:

ischannel

- Determine if object is a channel.

isdioline

- Determine if object is a line.

isvalid

- Determine if object is associated with hardware.

59

length

- Determine length of data acquisition object.

daq/private/load

- Load data acquisition objects from disk into MATLAB workspace.

:
:

makenames

- Generate cell array of names for naming channels/lines.

obj2mfile

- Convert data acquisition object to MATLAB code.

daq/private/save

- Save data acquisition objects to disk.

showdaqevents

- Display summary of event log.

size

- Determine size of data acquisition object.

Information and help.


daqhelp

- Data acquisition property and function help.

daqhwinfo

- Information on available hardware.

daqpropedit

- Data acquisition property editor.

daqsupport

- Data acquisition technical support tool.

propinfo

- Property information for data acquisition objects.

Data acquisition demos.


daqschool

- Launch command line Data Acquisition Toolbox tutorials.

demodaq_callback

- Introduction to data acquisition callback functions.

demodaq_intro

- Introduction to Data Acquisition Toolbox.

demodaq_save

- Methods for saving and loading data acquisition objects.

daqtimerplot

- Example callback function which plots the data acquired.

Analog input demos.


daqrecord

- Record data from the specified adaptor.

demoai_channel

- Introduction to analog input channels.

demoai_fft

- FFT display of an incoming analog input signal.

demoai_intro

- Introduction to analog input objects.

demoai_logging

- Demonstrate data logging.

demoai_trig

- Demonstrate the use of immediate, manual and software triggers.

daqscope

- Example oscilloscope for the Data Acquisition Toolbox.

:
: -

Analog output demos.

daqplay

- Output data to the specified adaptor.

daqsong

- Output data from HANDEL.MAT to a sound card.

demoao_channel

- Introduction to analog output channels.

demoao_intro

- Introduction to analog output objects.

demoao_trig

- Demonstrate the use of immediate and manual triggers.

daqfcngen

- Example function generator for the Data Acquisition Toolbox.

Matlab/Simulink

60
Digital I/O demos.
demodio_intro

- Introduction to digital I/O objects.

demodio_line

- Introduction to digital I/O lines.

diopanel

- Display digital I/O panel.

See also ANALOGINPUT, ANALOGOUTPUT, DIGITALIO, DAQHELP.


>> helpwin daq

2.10

2.10 helpwin daq

:
:

>> doc daq

2.11

:
:
:
2.11 doc daq

:
:

2.5

61

C/Fortran

MATLAB MATLAB MexFunction


C Fortran

:
:

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

2.12
y = 2 * y + y s * ( y + ) ( y + )2 + ( y )2 3 * ( y s ) ( y s )2 + ( y )2 3

3
3
y ( 4 ) = 2 * y + y s * y ( y + )2 + ( y )2 * y ( y s )2 + ( y )2

= 1 82.54

s = 1
m t [t 0 ,t1 ] [t 0 t1 L t N ]

y t 0 [ y, y , y , y ] [y , y , y , y ( ) ]
4

m yp 1= y yp2

= y yp 3 = y yp 4 = y

(4 )

: (
: )
: (
: )
: (
: )
: (
: )

y 1 = y y 2 = y y 3 = y y 4

: (

= y 2.12 m MATLAB ODE

: )

Ordinary Differential Equation


MATLAB HTML MATLAB\Using MATLAB\Mathematics\Differential Equations
doc
MATLAB MATLAB ODE
ode45ode23 2.12 yprime
>> [t y]=ode45(@yprime,[0 10],[1 2 3 4])

: (
: )
: (
: )
: (
: )
: (
: )

t=

: (
: )

Matlab/Simulink

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

2
6.2378
6.4391
6.6403
6.8428
7.0452
7.2477
7.4501
7.6605
7.8710
8.0814
8.2918
8.4960
8.7001
8.9043
9.1085
9.3314
9.5543
9.7771
10.0000

y=
1.0000 2.0000 3.0000 4.0000
1.0230 2.1005 3.0447 3.9869
1.0471 2.2009 3.0893 3.9720
1.0723 2.3012 3.1337 3.9555
1.0986 2.4015 3.1779 3.9372
1.2471 2.9005 3.3954 3.8200
1.4234 3.3931 3.6051 3.6597
1.6271 3.8761 3.8046 3.4568
1.8575 4.3463 3.9916 3.2117
2.5633 5.4706 4.3978 2.3975
3.4198 6.4371 4.6686 1.3328
4.4011 7.1970 4.7696 0.0468
5.4744 7.7088 4.6725 -1.4214
6.6545 7.9415 4.3348 -3.1032
7.8440 7.8325 3.7366 -4.8735
8.9900 7.3614 2.8689 -6.6666
10.0378

6.5223 1.7343 -8.4134

10.9650

5.2663 0.2850 -10.1060

11.6660

3.6395 -1.4137 -11.5930

63

Matlab/Simulink

64
12.0850

1.6771 -3.3247 -12.7992

12.1744 -0.5697 -5.3983 -13.6582


11.8233 -3.4110 -7.8972 -14.1436
10.9449 -6.4287 -10.4293 -14.0270
9.5167 -9.4963 -12.8832 -13.2615
7.5446 -12.4765 -15.1414 -11.8321
5.0571 -15.2306 -17.0877 -9.7509
2.1070 -17.6139 -18.6040 -7.0565
-1.2294 -19.4934 -19.5850 -3.8166
-4.8498 -20.7537 -19.9439 -0.1309
-8.9108 -21.3100 -19.5624

4.1771

-12.9906 -20.9498 -18.3293

8.6785

-16.9088 -19.6186 -16.2225 13.1777


-20.4782 -17.3129 -13.2666 17.4659
-23.5026 -14.0922 -9.5463 21.3159
-25.8258 -10.0245 -5.1455 24.5444
-27.2947 -5.2305 -0.1973 26.9653
-27.7897 0.1229 5.1260 28.4244
-27.1825 6.0641 10.8429 28.7947
-25.3735 12.1409 16.5067 27.8990
-22.3572 18.0824 21.8622 25.6956
-18.1940 23.6084 26.6527 22.2135
-12.9390 28.4927 30.6718 17.4864
-6.7958 32.4000 33.6260 11.6873
0.0200 35.0924 35.3159 5.0173
7.2418 36.3862 35.5982 -2.2623
14.6129 36.1492 34.3756 -9.8934
21.7698 34.2898 31.6032 -17.5030
28.3836 30.8027 27.3137 -24.7444
34.1356 25.7723 21.6234 -31.2728
38.8860 19.0811 14.4251 -36.9532
42.0882 11.1392 6.1816 -41.1706
43.5058

2.2633 -2.7758 -43.6436

42.9919 -7.1578 -12.0561 -44.1792


40.5900 -16.4111 -20.9672 -42.7464
36.3221 -25.3578 -29.3822 -39.3578
30.2849 -33.5815 -36.9065 -34.0730
22.6743 -40.6868 -43.1742 -27.0574
12.8965 -46.7482 -48.2049 -17.7219
2.0066 -50.6367 -50.9909 -7.0354
-9.4849 -52.0404 -51.2747

4.5031

-21.0015 -50.7935 -48.9455 16.3134

65

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


[1 2 3 4] t y t [ y, y , y , y ]
t,y

2.13 plot(t,y(:,1))
>> t=0:0.1:10;
>> [t y]=ode45(@yprime,t,[1 2 3 4])

0
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

: (

2.13

0.1000

: (

: )

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

t=

: )

:
:

Matlab/Simulink

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

2
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

67

Matlab/Simulink

68

y=
1.0000 2.0000 3.0000 4.0000
1.2447 2.8931 3.3922 3.8220
1.5780 3.7662 3.7598 3.5071
1.9967 4.6008 4.0892 3.0576
2.4961 5.3790 4.3675 2.4781
3.0696 6.0825 4.5815 1.7759
3.7092 6.6944 4.7191 0.9599
4.4050 7.1994 4.7696 0.0417
5.1455 7.5837 4.7238 -0.9652
5.9177 7.8354 4.5740 -2.0450
6.7081 7.9441 4.3136 -3.1812
7.5016 7.9006 3.9374 -4.3554
8.2827 7.6985 3.4422 -5.5484
9.0356 7.3340 2.8272 -6.7402
9.7440 6.8062 2.0939 -7.9103
10.3917

6.1170 1.2461 -9.0377

10.9629

5.2698 0.2889 -10.1021

11.4415

4.2706 -0.7707 -11.0822

11.8124

3.1278 -1.9235 -11.9581

12.0620

1.8524 -3.1583 -12.7110

12.1781

0.4584 -4.4619 -13.3238

12.1499 -1.0380 -5.8187 -13.7809


11.9688 -2.6192 -7.2128 -14.0688
11.6264 -4.2657 -8.6264 -14.1744
11.1162 -5.9564 -10.0407 -14.0866
10.4346 -7.6691 -11.4362 -13.7976
9.5809 -9.3807 -12.7930 -13.3026
8.5570 -11.0670 -14.0903 -12.6003
7.3675 -12.7026 -15.3069 -11.6920
6.0191 -14.2638 -16.4232 -10.5818
4.5197 -15.7257 -17.4186 -9.2751
2.8799 -17.0636 -18.2733 -7.7805
1.1129 -18.2543 -18.9687 -6.1094
-0.7658 -19.2763 -19.4885 -4.2767
-2.7379 -20.1100 -19.8177 -2.3000
-4.7829 -20.7371 -19.9434 -0.2004
-6.8790 -21.1426 -19.8553

2.0000

-9.0039 -21.3122 -19.5440

4.2779

-11.1329 -21.2330 -19.0017

6.6070

2
-13.2408 -20.8957 -18.2238

8.9603

-15.3021 -20.2947 -17.2091 11.3099


-17.2906 -19.4284 -15.9601 13.6267
-19.1798 -18.2987 -14.4822 15.8808
-20.9429 -16.9112 -12.7847 18.0415
-22.5557 -15.2740 -10.8783 20.0810
-23.9928 -13.3968 -8.7759 21.9695
-25.2298 -11.2931 -6.4932 23.6779
-26.2446 -8.9797 -4.0489 25.1795
-27.0176 -6.4768 -1.4648 26.4500
-27.5318 -3.8083 1.2350 27.4674
-27.7726 -1.0013 4.0229 28.2120
-27.7283 1.9147 6.8697 28.6672
-27.3901 4.9107 9.7473 28.8193
-26.7498 7.9539 12.6238 28.6549
-25.8029 11.0104 15.4668 28.1648
-24.5495 14.0458 18.2441 27.3442
-22.9933 17.0251 20.9233 26.1930
-21.1428 19.9127 23.4716 24.7153
-19.0103 22.6725 25.8567 22.9200
-16.6118 25.2692 28.0471 20.8199
-13.9644 27.6709 30.0146 18.4290
-11.0885 29.8426 31.7288 15.7652
-8.0081 31.7523 33.1623 12.8498
-4.7499 33.3713 34.2910

9.7081

-1.3439 34.6742 35.0943

6.3687

2.1768 35.6386 35.5551 2.8643


5.7763 36.2460 35.6594 -0.7690
9.4165 36.4811 35.3975 -4.4928
13.0617 36.3326 34.7626 -8.2708
16.6719 35.7900 33.7493 -12.0614
20.2066 34.8476 32.3566 -15.8228
23.6264 33.5050 30.5890 -19.5131
26.8922 31.7673 28.4555 -23.0907
29.9657 29.6449 25.9705 -26.5141
32.8090 27.1533 23.1530 -29.7419
35.3860 24.3133 20.0267 -32.7337
37.6653 21.1463 16.6160 -35.4544
39.6129 17.6782 12.9494 -37.8654
41.1980 13.9388 9.0588 -39.9312
42.3944

9.9615 4.9794 -41.6210

43.1806

5.7833 0.7492 -42.9083

69

Matlab/Simulink

70
43.5397

1.4451 -3.5905 -43.7713

43.4593 -3.0087 -7.9955 -44.1926


42.9317 -7.5301 -12.4186 -44.1591
41.9536 -12.0737 -16.8152 -43.6632
40.5237 -16.5921 -21.1394 -42.6985
38.6449 -21.0345 -25.3421 -41.2630
36.3258 -25.3515 -29.3764 -39.3609
33.5808 -29.4949 -33.1966 -37.0024
30.4300 -33.4175 -36.7590 -34.2036
26.8989 -37.0735 -40.0212 -30.9870
23.0191 -40.4182 -42.9428 -27.3808
18.8247 -43.4120 -45.4885 -23.4169
14.3513 -46.0173 -47.6247 -19.1284
9.6396 -48.1944 -49.3167 -14.5539
4.7334 -49.9096 -50.5358 -9.7355
-0.3210 -51.1351 -51.2590 -4.7186
-5.4748 -51.8493 -51.4696

0.4483

-10.6761 -52.0360 -51.1565

5.7133

-15.8707 -51.6854 -50.3148 11.0211


-21.0015 -50.7935 -48.9455 16.3134
>> yprime([0 10],[1 2 3 4])
ans =
2.0000
8.9685
4.0000
-1.0947

2.12 m yprime C Fortran


C Fortran %MATLABROOT%\extern\
examples\mex\yprimef.f yprimefg.f C mex setup
Fortran
1

: (
: )

/*=================================================================

* YPRIME.C

: (

The calling syntax is:

: (t, y

: )

: [yp] = yprime
Sample .MEX file corresponding to YPRIME.M

: )

: *
:
: <#>

... [1]

: (
: (MAX
: )
2

71

: )
: #define MAX

[ yp] = yprime(t, y)

: (A

: )

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]

24

: (A
: )

25

#if !defined(MAX)

: ) :

26

#define

: (

27

#endif

MAX(A, B) ((A) > (B) ? (A) : (B))

: (B

28

: )

29

#if !defined(MIN)

: )

30

#define

: )

31

#endif

MIN(A, B) ((A) < (B) ? (A) : (B))

: )

... [2]
: #if !defined

32
33

#define PI 3.14159265

34

: (
: (MIN

35

static double

mu = 1/82.45;

36

static double

mus = 1 - 1/82.45;

37

: )
: )
: (

38

: (A, B

39

static void yprime(

40

double

yp[],

41

double

*t,

42

double

y[]

43

44

: )
: )
: (
: (
: (
: (A
: )
: ) <
: (
: (B
: )
: ) ?
: (

... [3]

: r1 = sqrt
: (
: (
: (
:
: (y[0]+mu
Matlab/Simulink

72

: )
: )*

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. */

: );

51

if (r1 == 0.0 || r2 == 0.0 ){

: (

52

mexWarnMsgTxt("Division by zero!\n");

: (y[0]-mus

53

: (

54

... [5]

: (

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[],

63

int nrhs, const mxArray*prhs[] )

64

: );

... [6]
:
: if

65

: (

66

double *yp;

67

double *t,*y;

: (r1 == 0.0
|| r2[7]
...

68

unsigned int m,n;

69
70

/* Check for proper number of arguments */

71

: )
: ){
: mexWarnMsgTx
... [8]
:
: (

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

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

: yp[1] =... [10]


:

77
78
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]

73

83

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

84

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

: YP_OUT =
mxCreateDoubleMatrix

85

: (
: (4, 1, mxREAL

86
87

/* Create a matrix for the return argument */

: )

88

YP_OUT = mxCreateDoubleMatrix(4, 1, mxREAL);

:
: );

89
90

/* Assign pointers to the various parameters */

91

yp = mxGetPr(YP_OUT);

92
93

t = mxGetPr(T_IN);

94

y = mxGetPr(Y_IN);

95
96

/* Do the actual computations in a subroutine */

97

yprime(yp,t,y);

98

return;

:
: yp = mxGetPr
:
: (
: (YP_OUT
: )
: );
:

99

: t = mxGetPr

100 }

:
: (

z 12~36
z 39~60 C yprime
z 62~100 Matlab C mexFunction
MATLAB HTML MATLAB\Using MATLAB\External Interfaces/
API\Calling C and Fortran Programs from MATLAB
MATLAB mex

: (T_IN
: )
: );
y = mxGetPr
: (
: (Y_IN
: )
: );
:

>> mex -setup

: yprime

Please choose your compiler for building external interface (MEX) files:

: (
: (yp,t,y

Would you like mex to locate installed compilers [y]/n? y


Select a compiler:
[1] Digital Visual Fortran version 6.0 in C:\Program Files\Microsoft Visual Studio

: )
: );
:

[2] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc

[3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio

:
:

[0] None

Matlab/Simulink

74

Compiler: 3
Please verify your choices:
Compiler: Microsoft Visual C/C++ 6.0
Location: C:\Program Files\Microsoft Visual Studio
Are these correct?([y]/n): y
The default options file:
"C:\Documents and Settings\Michael\Application Data\MathWorks\MATLAB\R12\mexopts.bat"

is being updated from D:\MATLAB6P1\BIN\WIN32\mexopts\msvc60opts.bat...


Installing the MATLAB Visual Studio add-in ...
Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\ template\MATLABWizard.awx

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

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

from D:\MATLAB6P1\BIN\WIN32\MATLABAddin.dll
Merged D:\MATLAB6P1\BIN\WIN32\usertype.dat
with C:\Program Files\Microsoft Visual Studio\common\msdev98\bin\usertype.dat
Note: If you want to use the MATLAB Visual Studio add-in with the MATLAB C/C++

:
:

Compiler, you must start MATLAB and run the following commands:
:
cd(prefdir);
mccsavepath;
(You only have to do this configuration step once.)
>> mex yprime.c

dir yprime.dll
>> dir yprime.dll
yprime.dll

yprime.c 2.12 m
C yprime

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

75
:

Matlab/Simulink

76
5.4371
5.6362
5.8353
6.0365
6.2378
6.4391
6.6403
6.8428
7.0452
7.2477
7.4501
7.6605
7.8710
8.0814
8.2918
8.4960
8.7001
8.9043
9.1085
9.3314
9.5543
9.7771
10.0000

y=
1.0000 2.0000 3.0000 4.0000
1.0230 2.1005 3.0447 3.9869
1.0471 2.2009 3.0893 3.9720
1.0723 2.3012 3.1337 3.9555
1.0986 2.4015 3.1779 3.9372
1.2471 2.9005 3.3954 3.8200
1.4234 3.3931 3.6051 3.6597
1.6271 3.8761 3.8046 3.4568
1.8575 4.3463 3.9916 3.2117
2.5633 5.4706 4.3978 2.3975
3.4198 6.4371 4.6686 1.3328
4.4011 7.1970 4.7696 0.0468
5.4744 7.7088 4.6725 -1.4214
6.6545 7.9415 4.3348 -3.1032
7.8440 7.8325 3.7366 -4.8735

2
8.9900 7.3614 2.8689 -6.6666
10.0378

6.5223 1.7343 -8.4134

10.9650

5.2663 0.2850 -10.1060

11.6660

3.6395 -1.4137 -11.5930

12.0850

1.6771 -3.3247 -12.7992

12.1744 -0.5697 -5.3983 -13.6582


11.8233 -3.4110 -7.8972 -14.1436
10.9449 -6.4287 -10.4293 -14.0270
9.5167 -9.4963 -12.8832 -13.2615
7.5446 -12.4765 -15.1414 -11.8321
5.0571 -15.2306 -17.0877 -9.7509
2.1070 -17.6139 -18.6040 -7.0565
-1.2294 -19.4934 -19.5850 -3.8166
-4.8498 -20.7537 -19.9439 -0.1309
-8.9108 -21.3100 -19.5624

4.1771

-12.9906 -20.9498 -18.3293

8.6785

-16.9088 -19.6186 -16.2225 13.1777


-20.4782 -17.3129 -13.2666 17.4659
-23.5026 -14.0922 -9.5463 21.3159
-25.8258 -10.0245 -5.1455 24.5444
-27.2947 -5.2305 -0.1973 26.9653
-27.7897 0.1229 5.1260 28.4244
-27.1825 6.0641 10.8429 28.7947
-25.3735 12.1409 16.5067 27.8990
-22.3572 18.0824 21.8622 25.6956
-18.1940 23.6084 26.6527 22.2135
-12.9390 28.4927 30.6718 17.4864
-6.7958 32.4000 33.6260 11.6873
0.0200 35.0924 35.3159 5.0173
7.2418 36.3862 35.5982 -2.2623
14.6129 36.1492 34.3756 -9.8934
21.7698 34.2898 31.6032 -17.5030
28.3836 30.8027 27.3137 -24.7444
34.1356 25.7723 21.6234 -31.2728
38.8860 19.0811 14.4251 -36.9532
42.0882 11.1392 6.1816 -41.1706
43.5058

2.2633 -2.7758 -43.6436

42.9919 -7.1578 -12.0561 -44.1792


40.5900 -16.4111 -20.9672 -42.7464
36.3221 -25.3578 -29.3822 -39.3578
30.2849 -33.5815 -36.9065 -34.0730
22.6743 -40.6868 -43.1742 -27.0574

77

Matlab/Simulink

78

12.8965 -46.7482 -48.2049 -17.7219


2.0066 -50.6367 -50.9909 -7.0354
-9.4849 -52.0404 -51.2747

4.5031

-21.0015 -50.7935 -48.9455 16.3134


>> t=0:0.1:10;
>> [t y]=ode45(@yprime,t,[1 2 3 4])
t=
0
0.1000
0.2000
0.3000
0.4000
0.5000
0.6000
0.7000
0.8000
0.9000
1.0000
1.1000
1.2000
1.3000
1.4000
1.5000
1.6000
1.7000
1.8000
1.9000
2.0000
2.1000
2.2000
2.3000
2.4000
2.5000
2.6000
2.7000
2.8000
2.9000
3.0000
3.1000
3.2000

2
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

79

Matlab/Simulink

80
7.5000
7.6000
7.7000
7.8000
7.9000
8.0000
8.1000
8.2000
8.3000
8.4000
8.5000
8.6000
8.7000
8.8000
8.9000
9.0000
9.1000
9.2000
9.3000
9.4000
9.5000
9.6000
9.7000
9.8000
9.9000
10.0000

y=
1.0000 2.0000 3.0000 4.0000
1.2447 2.8931 3.3922 3.8220
1.5780 3.7662 3.7598 3.5071
1.9967 4.6008 4.0892 3.0576
2.4961 5.3790 4.3675 2.4781
3.0696 6.0825 4.5815 1.7759
3.7092 6.6944 4.7191 0.9599
4.4050 7.1994 4.7696 0.0417
5.1455 7.5837 4.7238 -0.9652
5.9177 7.8354 4.5740 -2.0450
6.7081 7.9441 4.3136 -3.1812
7.5016 7.9006 3.9374 -4.3554

2
8.2827 7.6985 3.4422 -5.5484
9.0356 7.3340 2.8272 -6.7402
9.7440 6.8062 2.0939 -7.9103
10.3917

6.1170 1.2461 -9.0377

10.9629

5.2698 0.2889 -10.1021

11.4415

4.2706 -0.7707 -11.0822

11.8124

3.1278 -1.9235 -11.9581

12.0620

1.8524 -3.1583 -12.7110

12.1781

0.4584 -4.4619 -13.3238

12.1499 -1.0380 -5.8187 -13.7809


11.9688 -2.6192 -7.2128 -14.0688
11.6264 -4.2657 -8.6264 -14.1744
11.1162 -5.9564 -10.0407 -14.0866
10.4346 -7.6691 -11.4362 -13.7976
9.5809 -9.3807 -12.7930 -13.3026
8.5570 -11.0670 -14.0903 -12.6003
7.3675 -12.7026 -15.3069 -11.6920
6.0191 -14.2638 -16.4232 -10.5818
4.5197 -15.7257 -17.4186 -9.2751
2.8799 -17.0636 -18.2733 -7.7805
1.1129 -18.2543 -18.9687 -6.1094
-0.7658 -19.2763 -19.4885 -4.2767
-2.7379 -20.1100 -19.8177 -2.3000
-4.7829 -20.7371 -19.9434 -0.2004
-6.8790 -21.1426 -19.8553

2.0000

-9.0039 -21.3122 -19.5440

4.2779

-11.1329 -21.2330 -19.0017

6.6070

-13.2408 -20.8957 -18.2238

8.9603

-15.3021 -20.2947 -17.2091 11.3099


-17.2906 -19.4284 -15.9601 13.6267
-19.1798 -18.2987 -14.4822 15.8808
-20.9429 -16.9112 -12.7847 18.0415
-22.5557 -15.2740 -10.8783 20.0810
-23.9928 -13.3968 -8.7759 21.9695
-25.2298 -11.2931 -6.4932 23.6779
-26.2446 -8.9797 -4.0489 25.1795
-27.0176 -6.4768 -1.4648 26.4500
-27.5318 -3.8083 1.2350 27.4674
-27.7726 -1.0013 4.0229 28.2120
-27.7283 1.9147 6.8697 28.6672
-27.3901 4.9107 9.7473 28.8193
-26.7498 7.9539 12.6238 28.6549

81

Matlab/Simulink

82

-25.8029 11.0104 15.4668 28.1648


-24.5495 14.0458 18.2441 27.3442
-22.9933 17.0251 20.9233 26.1930
-21.1428 19.9127 23.4716 24.7153
-19.0103 22.6725 25.8567 22.9200
-16.6118 25.2692 28.0471 20.8199
-13.9644 27.6709 30.0146 18.4290
-11.0885 29.8426 31.7288 15.7652
-8.0081 31.7523 33.1623 12.8498
-4.7499 33.3713 34.2910

9.7081

-1.3439 34.6742 35.0943

6.3687

2.1768 35.6386 35.5551 2.8643


5.7763 36.2460 35.6594 -0.7690
9.4165 36.4811 35.3975 -4.4928
13.0617 36.3326 34.7626 -8.2708
16.6719 35.7900 33.7493 -12.0614
20.2066 34.8476 32.3566 -15.8228
23.6264 33.5050 30.5890 -19.5131
26.8922 31.7673 28.4555 -23.0907
29.9657 29.6449 25.9705 -26.5141
32.8090 27.1533 23.1530 -29.7419
35.3860 24.3133 20.0267 -32.7337
37.6653 21.1463 16.6160 -35.4544
39.6129 17.6782 12.9494 -37.8654
41.1980 13.9388 9.0588 -39.9312
42.3944

9.9615 4.9794 -41.6210

43.1806

5.7833 0.7492 -42.9083

43.5397

1.4451 -3.5905 -43.7713

43.4593 -3.0087 -7.9955 -44.1926


42.9317 -7.5301 -12.4186 -44.1591
41.9536 -12.0737 -16.8152 -43.6632
40.5237 -16.5921 -21.1394 -42.6985
38.6449 -21.0345 -25.3421 -41.2630
36.3258 -25.3515 -29.3764 -39.3609
33.5808 -29.4949 -33.1966 -37.0024
30.4300 -33.4175 -36.7590 -34.2036
26.8989 -37.0735 -40.0212 -30.9870
23.0191 -40.4182 -42.9428 -27.3808
18.8247 -43.4120 -45.4885 -23.4169
14.3513 -46.0173 -47.6247 -19.1284
9.6396 -48.1944 -49.3167 -14.5539
4.7334 -49.9096 -50.5358 -9.7355

83

-0.3210 -51.1351 -51.2590 -4.7186


-5.4748 -51.8493 -51.4696

0.4483

-10.6761 -52.0360 -51.1565

5.7133

-15.8707 -51.6854 -50.3148 11.0211


-21.0015 -50.7935 -48.9455 16.3134
>> yprime([0 10],[1 2 3 4])
ans =
2.0000
8.9685
4.0000
:

-1.0947

2.6

MATLAB MATLAB
m
2.5 C Fortran mex MATLAB
m
e:\material\mytoolbox e:\material\mytoolbox MATLAB
2.14 Matlab

2.14 MATLAB

: (
: )
:

:
:

Matlab/Simulink

84

:
:
:

2.7

:
:
:

Matlab m C/Fortran
MATLAB

4 1010 0123
0.50.10.150.25 Communications Toolbox m
randsrc

: (
: )

>> which randsrc


D:\MATLAB6p1\toolbox\comm\comm\randsrc.m
>> type randsrc
function out = randsrc(varargin);
%RANDSRC Generate random matrix using prescribed alphabet.
% OUT = RANDSRC generates a "-1" or "1" with equal probability.
%
% OUT = RANDSRC(M) generates an M-by-M random bipolar matrix.
% "-1" and "1" occur with equal probability.
%
% OUT = RANDSRC(M,N) generates an M-by-N random bipolar matrix.
% "-1" and "1" occur with equal probability.
%
% OUT = RANDSRC(M,N,ALPHABET) generates an M-by-N random matrix, using the
% alphabet specified in ALPHABET.

: the

%
% ALPHABET can be either a row vector or a two-row matrix:
% Row

: If ALPHABET is a row vector then the contents of ALPHABET define

% Vector which possible elements RANDSRC can output. The elements of


ALPHABET may be either real or complex. If all entries of

: of

ALPHABET are distinct, then the probability distribution is

: of

uniform.

: is

% Two-Row : If ALPHABET is a two-row matrix, the first row defines the


% Matrix possible outputs (as above). The second row of ALPHABET
%

specifies the probability for each corresponding element. The

elements of the second row must sum to one.

%
% OUT = RANDSRC(M,N,ALPHABET,STATE) resets the state of RAND to STATE.

: The

85

%
% Examples:
%

out = randsrc(2,3)

% out =

out = randsrc(2,3,[3 4])


: =

out =

-1

-1

-1

-1

%
%

out = randsrc(2,3,[3 4;0 1])

% out =

out = randsrc(2,3,[3 4;0.8 0.2])

out =

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

Matlab/Simulink

86
% --- randsrc
case ''
% --- randsrc(m)
case 'n'
m

= varargin{1};
% --- randsrc(m, n)
case 'n/n'

= varargin{1};

= varargin{2};
% --- randsrc(m, n, alpha)
case 'n/n/n'

= varargin{1};

= varargin{2};

alpha = varargin{3};
% --- randsrc(m, n, alpha, state)
case 'n/n/n/n'
m

= varargin{1};

= varargin{2};

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

87

error('Matrix dimensions must be finite.');


elseif (floor(m) ~= m) | (floor(n) ~= n) | (~isreal(m)) | (~isreal(n))
error('Matrix dimensions must be real integers.');
elseif (m < 0) | (n < 0)
error('Matrix dimensions must be positive.');
elseif (length(m) > 1) | (length(n) > 1)
error('Matrix dimensions must be scalars.');
end
ar = size(alpha,1);
ac = size(alpha,2);
if ar > 2
error('The ALPHABET parameter cannot contain more than two rows.');
% If the alphabet probabilities are explicitly defined.
elseif ar == 2
aprob = alpha(2,:);
% Error-check the probabilities.
if (~isreal(aprob)) | (~isfinite(aprob)) | max(aprob < 0) | max(aprob > 1)

error('The ALPHABET probability elements must be real numbers between

zero and one.');

elseif (abs(sum(aprob) - 1) > sqrt(eps))


error('Sum of ALPHABET probability elements must equal one.');
end
% 'prob' is used to facilitate assigning the random elements to the output.

% Ex: if the second row of the alphabet input parameter


%

is [0.3 0.4 0.3] then 'prob' would be set to [0.3 0.7 1.0].
prob = cumsum(aprob);

else
% Define the 'prob' vector if the probabilities are not given in the function call.

prob = (1:ac) / ac;


end
% Set the initial state if specified.
if ~isempty(state)

Matlab/Simulink

88
rand('state', state);
end
% Generate the random matrix.
r = rand(m,n);

% 'idx' is used to place the alphabet elements in the output matrix.


idx = ones(m,n);
% Use the random matrix 'r' to determine which alphabet element to use
% in the output matrix.
% Ex: if the alphabet parameter is {'a' 'b' 'c' 'd'}, the 'idx' matrix
%

will contain integers from one to four after this loop has run.

for i = 1:ac
idx = idx + (r >= prob(i));
end
alphabet = alpha(1,:);
% Assign alphabet elements to the output matrix as specified by 'idx'.
out = alphabet(idx);
% A special case, if the m and n parameters specify a column vector.
if n == 1
out = out(:);
end
% [EOF] randsrc.m
>> randsrc(10,10,[0 1 2 3;0.5 0.1 0.15 0.25])
ans =
3

5 H (z ) =

89

1 + 2 z 1
m
1 + 2 z 1 + 3z 2

plotpz.m
%plotpz.m - plot the zero and pole plane from
%transfer function
%
%

-1

-2

b(1)+b(2)*z +b(3)*z

%H(z)=------------------------%
%

-1

-2

a(1)+a(2)*z +a(3)*z

b=[1 2 0];
a=[1 2 3];
[z,p,k]=tf2zp(b,a);
zplane(z,p);
>> plotpz

2.15

2.15 plotpz

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

:
:
: :

Matlab/Simulink

90
I = imread(filename);

%The Sobel method finds edges using the Sobel approximation


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

2.16 2.17
>> which rice.tif
D:\MATLAB6p1\toolbox\images\imdemos\rice.tif
>> [sobel canny]=edge_detect('rice.tif');

91

2.18 2.19
:

2.16

edge_detect('blood1.tif')1

2.17

edge_detect('blood1.tif')2

:
:

Matlab/Simulink

92

2.18

:
edge_detect('rice.tif')1

:
: 3

2.19

:
edge_detect('rice.tif')2

>> whos

:
: 4

Name

Size

Bytes Class

canny

256x256

65536 uint8 array (logical)

sobel

256x256

65536 uint8 array (logical)

Grand total is 131072 elements using 131072 bytes

71:

[1]

xiao

2002-10-4 12:06:00

#if !defined

71:

[2]

xiao

2002-10-4 12:06:00

71:

[2]

xiao

2002-10-4 12:09:00

xiao

2002-10-4 12:08:00

xiao

2002-10-4 12:10:00

xiao

2002-10-4 12:13:00

[6]

xiao

2002-10-4 12:13:00

[7]

xiao

2002-10-4 12:14:00

xiao

2002-10-4 12:14:00

xiao

2002-10-4 12:14:00

xiao

2002-10-4 12:16:00

xiao

2002-10-4 12:17:00

#endif

71:

[3]

)
#define

71:

MIN

[4]

#define PI 3.14159265

72:

[5]

);
r2 = sqrt

72:
);

72:

(r1 == 0.0 || r2 == 0.0

72:

[8]

mexWarnMsgTxt

72:

[9]

("Division by zero!\n"

72:

[10]

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

72:

[11]

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

MATLAB Compiler m
MATLAB

MATLAB Compiler
z MATLAB C/C++ Math Library
m

MATLAB C/C++ Graphics Library


3.1

m
()

MATLAB Compiler

mC/C++

C/C++

MATLAB C/C++ Graphics Library


MATLAB Math m-file Library
MATLAB Math Built-in Library
MATLAB API Library
MATLAB MAT-file Library
ANSI C/C++ Library

3.1

MATLAB Compiler m C/C++ C/C++


m C/C++

Matlab/Simulink

94

C/C++
C/C++ MATLAB C/C++ MATLAB
C/C++ Math Library MathWorks C/C++ MATLAB
C/C++ C/C++ MATLAB fft
MATLAB C/C++ Math Library mlfFft FFT
MATLAB
m C/C++ C/C++

3.1

: (
: )

: 1

C/C++ compiler

MATLAB mex mbuild


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

[2] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc


[3] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio

[0] None
Compiler: 3
Please verify your choices:
Compiler: Microsoft Visual C/C++ 6.0
Location: C:\Program Files\Microsoft Visual Studio
Are these correct?([y]/n): y
The default options file:
"C:\Documents and Settings\Yongchun\Application Data\MathWorks\MATLAB\R12\mexopts.bat"
is being updated from D:\MATLAB6P1\BIN\WIN32\mexopts\msvc60opts.bat...

95

Installing the MATLAB Visual Studio add-in ...


Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.awx

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

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

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

Note: If you want to use the MATLAB Visual Studio add-in with the MATLAB
C/C++Compiler, you must start MATLAB and run the following commands:

:
:

cd(prefdir);
mccsavepath;
(You only have to do this configuration step once.)

MATLAB R12.1 C/C++


Windows 95/98/2000/NT
z MATLAB Lcc C version 2.4
Watcom C/C++ versions 10.6 & 11.0
Borland C++ versions 5.0, 5.2, 5.3, 5.4, & 5.5
z Microsoft Visual C++MSVC versions 5.0 & 6.0
UNIX
z GNU C compiler, gccHP SGI64
z UNIX ANSI C compiler
z U N IX C ++ com pilerL inux
z Linux GNU C++ compiler, g++
MATLAB
http://www.mathworks.com/support/tech-notes/v5/1600/1601.shtml
mex setup
<UserProfile>\Application Data\MathWorks\MATLAB\R12 Windows
$HOME/.matlab/R12 UNIX mex/mcc
Microsoft Visual C++ 3.2 MATLAB Project
Wizard
z
z

>> cd(prefdir)
>> mccsavepath

: (
: )
: (
: )
: (
: )

: (
: )
: (
: )
:

Matlab/Simulink

96

:
:

>> mbuild -setup

Please choose your compiler for building standalone MATLAB applications:


Would you like mbuild to locate installed compilers [y]/n? y
Select a compiler:
[1] Lcc C version 2.4 in D:\MATLAB6P1\sys\lcc
[2] Microsoft Visual C/C++ version 6.0 in C:\Program Files\Microsoft Visual Studio

[0] None
Compiler: 2
Please verify your choices:
Compiler: Microsoft Visual C/C++ 6.0
Location: C:\Program Files\Microsoft Visual Studio
Are these correct?([y]/n): y
The default options file:
"C:\Documents and Settings\Yongchun\Application Data\MathWorks\MATLAB\R12\compopts.bat"

is being updated from D:\MATLAB6P1\BIN\WIN32\mbuildopts\ msvc60compp.bat...


Installing the MATLAB Visual Studio add-in ...
Updated C:\Program Files\Microsoft Visual Studio\common\msdev98\template\MATLABWizard.awx

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

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

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

mbuild setup
<UserProfile>\Application Data\MathWorks\MATLAB\R12 Windows
$HOME/.matlab/R12 UNIX mbuild/mcc m

:
: (
: )
: (
: )

97

3.2 MATLAB Project Wizard

3.2 m
C/C++
7 16 Butterworth Fs=16kHz 1.5kHz
5kHz m C/C++

:
: kHz
:
:

function designbutworth

: kHz

%designbutworth.m

%used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz

: kHz

%passband with a sampling rate 16kHz.

: KHz

Fs=16;

: KHz

[b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass')

: K

freqz(b,a,512,16000)
>> designbutworth

: KHz

b=
Columns 1 through 6
0.0040

0 -0.0320

0 0.1120

Matlab/Simulink

98

Columns 7 through 12
-0.2241

0 0.2801

0 -0.2241

Columns 13 through 17
0.1120

0 -0.0320

0 0.0040

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

3.3
:

3.3
>> mcc -B sgl designbutworth.m

99

mcc B sgl m C

bin
bilinear.c
freqz.c
buffer_mex_interface.c
freqzplot.c
buttap.c
signal_private_dividenowarn.c
butter.c
signal_private_db.c
datawrap.c
psdoptions.c
designbutworth.c
lp2lp.c
designbutworth_mainhg.c
signal_private_iirchk.c
subplot.c
lp2hp.c
lp2bs.c
lp2bp.c
designbutworth.exe
designbutworth.h
lp2bs.h
lp2bp.h
datawrap.h
lp2hp.h
butter.h
lp2lp.h
buttap.h
psdoptions.h
buffer_mex_interface.h
signal_private_db.h
bilinear.h
signal_private_dividenowarn.h
freqz.h
signal_private_iirchk.h
freqzplot.h

Matlab/Simulink

100
subplot.h

bin MATLAB FigureMenuBar.fig FigureToolBar.fig


designbutworth.exe
designbutworth.exe

>> !designbutworth
b=
Columns 1 through 7
0.0040

0 -0.0320

0 0.1120

0 -0.2241

Columns 8 through 14
0 0.2801

0 -0.2241

0 0.1120

Columns 15 through 17
-0.0320

0 0.0040

a=
Columns 1 through 7
1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294
Columns 8 through 14
-6.6792 4.5314 -2.7004

1.3838 -0.6100 0.2342 -0.0737

Columns 15 through 17
0.0181 -0.0032 0.0004

3.4

3.4
>> !del bin
E:\material\book\example7\bin\*, (Y/N) ? y
y
>> !designbutworth
b=
Columns 1 through 7
0.0040

0 -0.0320

0 0.1120

0 -0.2241

Columns 8 through 14
0 0.2801

0 -0.2241

0 0.1120

Columns 15 through 17
-0.0320

0 0.0040

a=
Columns 1 through 7
1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294
Columns 8 through 14

101

Matlab/Simulink

102

-6.6792 4.5314 -2.7004

1.3838 -0.6100 0.2342 -0.0737

Columns 15 through 17
0.0181 -0.0032 0.0004
Warning: Unable to find FigureToolBar.fig on path - not adding built-in toolbar.

Warning: Unable to find FigureMenuBar.fig on path - not adding built-in menus.

Warning: Unable to find FigureToolBar.fig on path - not adding built-in toolbar.

3.5

3.5

>> mcc -B sglcpp designbutworth.m

mcc B sglcpp m C++

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

103

datawrap.cpp
psdoptions.cpp
designbutworth.cpp
lp2lp.cpp
designbutworth_mainhg.cpp
signal_private_iirchk.cpp
subplot.cpp
lp2hp.cpp
lp2bs.cpp
lp2bp.cpp
designbutworth.exe
designbutworth.hpp
lp2bs.hpp
lp2bp.hpp
datawrap.hpp
lp2hp.hpp
butter.hpp
lp2lp.hpp
buttap.hpp
psdoptions.hpp
buffer_mex_interface.hpp
signal_private_db.hpp
bilinear.hpp
signal_private_dividenowarn.hpp
freqz.hpp
signal_private_iirchk.hpp
freqzplot.hpp
subplot.hpp
>> which mcc
D:\MATLAB6p1\toolbox\compiler\mcc.dll
>> help mcc
MCC MATLAB to C/C++ Compiler (Version 2.2).
MCC [-options] fun [fun2 ...] [mexfile1 ...] [mlibfile1 ...]
Translate fun.m to fun.c or fun.cpp, and optionally create any Supported

binary file. Write any resulting files into the current directory, by default.

If more than one M-file is specified, a C or C++ file is generated


for each M-file.

Matlab/Simulink

104

If C or object files are specified, they are passed to MEX or MBUILD


along with any generated C files.
If MEX-files are specified, MCC will generate wrapper code so that
calls can be made from compiled M-files to the specified MEX-files.
Also, if a MEX-file and an M-file with the same base name are
located in the same directory, specifying the MEX-file causes MCC to
use it instead of the M-file. Otherwise MCC favors M-files over MEX-files.
MLIB files describe the functions in a shared library created by MCC
(see -Wlib below). Specifying an MLIB file tells MCC to link to the
MLIB file's corresponding shared library whenever it needs to use
any of the functions found in that library. The MLIB file and its
corresponding shared library file must be located within the same directory.

If conflicting options are presented to MCC, the rightmost


conflicting option is used.
In order to assist in migrating to this new release, we have
prepared a quick-reference card which contains the Compiler 2.2
options. You can access this pdf file by selecting "Online Manuals" from the HELPDESK.

OPTIONS:
A <option> Specify annotation. The following table shows valid
<option>strings and their effects:
annotation:all (*) - All lines from source M-file appears as
comments in generated output file.
annotation:comments - Comments from source M-file appear as
comments in generated output file.
annotation:none

- No text from source M-file appears in

generated output file.


line:on

- #line directives appear in generated


output file which map lines in source Mcode to lines in output file.

line:off (*)
debugline:on

- No such #line directives are generated.


- Run-time error messages report the source
file name and line number where they occurred.

debugline:off (*) - Run-time error messages do not report any

information about the source where they occurred.

105
:

(*) indicates default setting.


B <filename> Specify bundle file. <filename> is a text file
containing Compiler command line options. The Compiler behaves
as if the "-B <filename>" were replaced by the contents of the
bundle file. Newlines appearing in these files are allowed and
are treated as whitespace.The MathWorks provides options files for the following:
sgl

Used for building stand-alone C Graphics Library


applications

sglcpp

Used for building stand-alone C++ Graphics Library

applications
pcode

Used for building MATLAB P-Code files.

c C only. Translate M-file to C, but do not produce a MEX-file or


stand-alone application. This is equivalent to "-T codegen" as
the rightmost argument on the command line.
d <directory> Output directory. All generated files will be put in
<directory>.
F list. List the <option>s available in the next form of the command,
together with their current values and a short explanation.
F <option>:<number> Typesetting format options. Assign the value
<number> to the formatting option <option>. See "F list" for <option>s.
f <filename> Use the specified options file when calling MEX or
MBUILD. This allows you to use different ANSI compilers. This
option is a direct pass-through to the MEX or MBUILD script. See
the "Application Program Interface Guide" for more information.
G Debug only. Simply turn debugging on, so debugging symbol
information is included.
g Debug. Include debugging symbol information. This option also
includes the -A debugline:on switch. This will have an impact on
performance of the generated code. If you wish to have debugging
information, but do not want the performance degradation
associated with the debug line information use: -g -A
debugline:off. This option also includes the -O none switch.
That switch causes all compiler optimizations to be turned off.

Matlab/Simulink

106

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

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

107

For example "-O all" looks for a bundle file called


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

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

macro_option_S.
Note: the absence of "-h" means that helper functions will not
be included.
t Translate M code to target language. Translate any M-functions
specified on the command line to C or C++ functions. This option
is included in all macro options. Omitting it allows the
generation of wrapper C/C++files without generating the C/C++ files corresponding to M-files.

T <option> Specify target phase and type. The following table shows
valid <option> strings and their effects:
codegen

- translate M-files to C/C++ files and


generate a wrapper file. (This is the default -T setting.)

compile:mex

- same as codegen, plus compile C/C++ files


to object form suitable for linking into a
SIMULINK S-function MEX-file.

compile:mexlibrary - same as codegen, plus compile C/C++ files


to object form suitable for linking into an
ordinary (non-S-function) MEX-file.
compile:exe

- same as codegen, plus compile C/C++ files


to object form suitable for linking into a
standalone executable.

compile:lib

- same as codegen, plus compile C/C++ files


to object form suitable for linking into a
shared library/DLL.

link:mex

- same as compile:mex, plus link object files


into a SIMULINK S-function MEX-file.

Matlab/Simulink

108

link:mexlibrary - same as compile:mexlibrary, plus link


object files into an ordinary (non S-function) MEX-file.
link:exe

- same as compile:exe, plus link object files


into a standalone executable.

link:lib

- same as compile:lib, plus link object files


into a shared library/DLL.

u <number> Specify that the number of inputs to a generated


Simulink S-function should be <number>. Valid only if either "S" or "-W simulink" option has also been specified.
v Verbose. Show compilation steps.
w list. List the <msg> strings allowed in the next form of the
command,together with the full text of the warning messages to
which they correspond.
w <option>[:<msg>] Warnings. The possible options are "enable",
"disable",and "error". If "enable:<msg>" or "disable:<msg>" is
specified, enable or disable the warning associated with <msg>.
If "error:<msg>" is specified, enable the warning associated
with <msg> and treat any instances of that warning as an error.
If the <option> but not ":<msg>"is specified, the Compiler
applies the action to all warning messages. For backward
compatibility with previous Compiler revisions,"-w" (with no option) is the same as "-w enable".

W <option> Wrapper functions. Specify which type of wrapper file


should be generated by the Compiler. <option> can be one of
"mex", "main","simulink", "lib:<string>", or "none" (default).
For the lib wrapper,<string> contains the name of the shared
library to build. When generating a "lib" wrapper, MCC also
creates an MLIB file describing the functions in the shared library.

x Macro that generates a MEX file. This is equivalent to the


options "-t -W mex -L C -T link:mex libmatlbmx.mlib", which can
be found in the file <MATLAB>/toolbox/compiler/bundles/
macro_option_x. Note: the absence of "-h" means that helper functions will not be included.
y <number> Specify that the number of outputs from a generated
Simulink S-function should be <number>. Valid only if either "S" or "-W simulink" option has also been specified.

Y <license.dat file> Override default license.dat file with


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

109

Matlab/Simulink

110

Make a generic C++ translation of myfun.m:


mcc -t -L Cpp myfun
Make a C MEX wrapper file from myfun1.m and myfun2.m:
mcc -W mex -L C libmatlbmx.mlib myfun1 myfun2
Make a C translation and a stand-alone executable from myfun1.m and
myfun2.m (using one mcc call):
mcc -m myfun1 myfun2
Make a C translation and a stand-alone executable from myfun1.m and
myfun2.m (by generating each output file with a separate mcc call).
Note that the MLIB file "libmmfile.mlib" only needs to be specified
when generating a wrapper file, and when linking the final executable:
mcc -t -L C myfun1

% yields myfun1.c

mcc -t -L C myfun2

% yields myfun2.c

mcc -W main -L C myfun1 myfun2 libmmfile.mlib % yields


myfun1_main.c mcc -T compile:exe myfun1.c
mcc -T compile:exe myfun2.c
mcc -T compile:exe myfun1_main.c

% yields myfun1.o

% yields myfun2.o
% yields myfun1_main.o

mcc -T link:exe myfun1.o myfun2.o myfun1_main.o libmmfile.mlib


Make a shared/dynamically linked library called "liba" from a0.m and
a1.m,where neither a0 nor a1 calls functions in libmmfile:
mcc -t -W lib:liba -T link:lib a0 a1
Make a shared/dynamically linked library called "liba" from a0.m and
a1.m, where at least one of a0 or a1 calls at least one function in
libmmfile. Define LIBMMFILE to be 1 when compiling the C code.:
mcc -t -W lib:liba -T link:lib a0 a1 libmmfile.mlib -M "-DLIBMMFILE=1"
Make a C translation and a stand-alone graphics library executable
from myfun.m (using one mcc call):
mcc -B sgl myfun1
Make a C++ translation and a stand-alone graphics library executable
from myfun.m (using one mcc call):
mcc -B sglcpp myfun1
Make a shared/dynamically linked library called "liba" from a0.m and
a1.m that makes calls into the MATLAB C/C++ Graphics Library:
mcc -B sgl -t -W libhg:liba -T link:lib a0 a1

111

Note: on PCs, filenames ending with .o above would actually end with .obj.

See also COMPILER/FUNCTION, MCCSAVEPATH, REALONLY, REALSQRT, REALLOG,


REALPOW, COMPILER_SURVEY, COMPILER_BUG_REPORT, MEX, MBUILD.
:

3.3

m C/C++

MATLAB R12.1 MATLAB Compiler m


C/C++
m m
m m m
m

8 Butterworth 16
Fs=16kHz1.5kHz~5kHz m
C

: (
: )
:
: A
: kHz
:
:

function dsgnbutworth_varorder(order)

: kHz

%dsgnbutworth_varorder.m

%used to design a Butterworth filter,which has a variable


%even order(>=16)and a 1.5kHz-5kHz passband with a sampling
%rate 16kHz.
if order<16|(mod(order,2)~=0)
disp('The order should be an even integer,not less than 16!');

: kHz
: KHz
: KHz
: KHz

return;

: ~

end

Fs=16;
[b,a]=butter(order/2,[1.5/(Fs/2) 5/(Fs/2)],'bandpass')

freqz(b,a,512,16000)

>> dsgnbutworth_varorder(14)
The order should be an even integer,not less than 16!
>> dsgnbutworth_varorder(15)
The order should be an even integer,not less than 16!
>> dsgnbutworth_varorder(16)
b=

Matlab/Simulink

112

Columns 1 through 7
0.0040

0 -0.0320

0 0.1120

0 -0.2241

Columns 8 through 14
0 0.2801

0 -0.2241

0 0.1120

Columns 15 through 17
-0.0320

0 0.0040

a=
Columns 1 through 7
1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294
Columns 8 through 14
-6.6792 4.5314 -2.7004

1.3838 -0.6100 0.2342 -0.0737

Columns 15 through 17
0.0181 -0.0032 0.0004

3.6
>> mcc -B sgl dsgnbutworth_varorder.m
>> !dir /w /b dsgnbutworth_varorder.exe
dsgnbutworth_varorder.exe
>> !dsgnbutworth_varorder 14
Warning: COLON arguments must be real scalars.
ERROR: Matrix dimensions must agree.
EXITING
>> !dsgnbutworth_varorder 15
The order should be an even integer,not less than 16!
>> !dsgnbutworth_varorder 16
Warning: COLON arguments must be real scalars.

:
3.6

113

ERROR: Matrix dimensions must agree.


EXITING

3.6

mcc dsgnbutworth_varorder.m dsgnbutworth_


varorder.exe dsgnbutworth_varorder.m order
dsgnbutworth_varorder.exe dsgnbutworth_varorder.m
mcc
function dsgnbutworth_varorder(order)
%dsgnbutworth_varorder.m
%used to design a Butterworth filter,which has a variable

: KHz

%even order(>=16)and a 1.5kHz-5kHz passband with a sampling

: KHz

%rate 16kHz.

: KHz

if ischar(order)
disp('The input argument is always taken as a string when converting');
disp('m function to console Application!');
order=str2num(order);
end

:
:

return;

end

if order<16|(mod(order,2)~=0)
disp('The order should be an even integer,not less than 16!');

Matlab/Simulink

114
Fs=16;

[b,a]=butter(order/2,[1.5/(Fs/2) 5/(Fs/2)],'bandpass')
freqz(b,a,512,16000)
>> mcc -B sgl dsgnbutworth_varorder.m
>> !dsgnbutworth_varorder 14
The input argument is always taken as a string when converting
m function to console Application!
The order should be an even integer,not less than 16!
>> !dsgnbutworth_varorder 15
The input argument is always taken as a string when converting
m function to console Application!
The order should be an even integer,not less than 16!
>> !dsgnbutworth_varorder 16
The input argument is always taken as a string when converting
m function to console Application!
b=
Columns 1 through 7
0.0040

0 -0.0320

0 0.1120

0 -0.2241

Columns 8 through 14
0 0.2801

0 -0.2241

0 0.1120

Columns 15 through 17
-0.0320

0 0.0040

a=
Columns 1 through 7
1.0000 -3.3774 6.1293 -8.2873 9.8335 -10.1137 8.8294
Columns 8 through 14
-6.6792 4.5314 -2.7004

1.3838 -0.6100 0.2342 -0.0737

115

Columns 15 through 17
0.0181 -0.0032 0.0004

3.7
:

3.7

m MATLAB Compiler C/C++

z MATLAB
7 II
function designbutworthand2df2
%designbutworthand2df2.m
%used to design 16-order Butterworth filter,which has a 1.5kHz-5kHz passband

: KHz

%a sampling rate 16kHz, then construct a direct-form II object.

: KHz

Fs=16;

[b,a]=butter(8,[1.5/(Fs/2) 5/(Fs/2)],'bandpass');

: KHz

h=df2(b,a)

>> mcc -B sgl designbutworthand2df2.m


Warning: File: designbutworthand2df2 Line: 7 Column: 3
The MATLAB Compiler does not currently support MATLAB object-oriented
programming. References to the method "df2" will produce a run-time error.
MATLAB Complier df2

Matlab/Simulink

116

>> !designbutworthand2df2

ERROR: Undefined function or variable 'df2'.


EXITING
z

input eval MATLAB MATLAB


input eval

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

MATLAB
>> mcc -B sgl testinputandeval
>> a='sin(10)'
a=
sin(10)
>> !testinputandeval
Input MATLAB expression: a
R=
a
ERROR: Reference to unknown function or variable 'a' while evaluating
expression.
EXITING
>> !testinputandeval
Input MATLAB expression: sin(10)
R=
sin(10)

117

ans =
-0.5440
z

load save

function testls
%testls.m
y= 'a';
load('testls.mat',y);

a MATLAB testls.mat

>> mcc -B sgl testls.m


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

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

>> mcc -B sgl testls.m


>> !testls
ans =
17 24

23

7 14 16

6 13

15

20 22

Matlab/Simulink

118
10 12 19 21

11 18 25

MATLAB Compiler
MATCOM MATCOM m m m
C/C++

3.4 VC++ m
VC++ m mex setupcdprefdir
mccsavepath mbuild setup Microsoft Visual C++ MSVCversions 5.0 & 6.0
Microsoft Visual C++
MSVC versions 6.0 Microsoft Visual C++ MSVC
versions 5.0
1. Microsoft Visual C++ IDE File|New... MATLAB
Project Wizard 3.8 OK 3.9

: (
: )
:
: (
: )
: (
: )
:
: (
: (
: )
: )

3.8 MATLAB Project Wizard

2. 3.9 Finish 3.10


3. 3.10 OK 3.11 m

4. 3.11 m
3.12

: (
: )

119
:

3.9 MATLAB Project Wizard

3.10 New Project Information

3.11

120

Matlab/Simulink

3.12

mcc-log.txt

5. 4 plotfreq.m 3.13
VC++ 3.14

:
:

3.13 plotfreq.m

6. Microsoft Visual C++ IDE 3.14


3.15
plotfreqprj.exe plotfreqprj.exe bin
FigureMenuBar.fig FigureToolBar.fig
plotfreqprj.exe bin FigureMenuBar.fig
FigureToolBar.fig 3.16
3.16 3.17 3.15 3.17

: (
: )
:

3.14 plotfreq.m VC++

3.15 plotfreqprj.exe

121

Matlab/Simulink

122

3.16 bin plotfreqprj.exe

3.17

bin plotfreqprj.exe

3.5 VC++ MATLAB C Math Library


Microsoft Visual C++ 6.0 VC++ MATLAB C Math Library
Microsoft Visual C++ 5.0

: (
: )

Win32 MATLAB C Math Library


1. Microsoft Visual C++ IDE File|New Win32 Console

123

Application 3.18 OK 3.19

3.18

3.19

Win32 Console Application

Win32 Console Application

2. 3.19 A Hello,World! application Finish


3.20
3. 3.20 OK 3.21
4. Microsoft Visual C++ IDE Project|Add To Project|New
consoleprj mysvd.cpp 3.22

124

Matlab/Simulink

3.20 New Project Information

3.21

consoleprj

3.22

125

mysvd.cpp

5. 3.23 mysvd.cpp MATLAB C Math Library


MATLAB svd
MATLAB C Math Library MATLAB PDF cmath_ref2b.pdf
cmath_ug2b.pdf MATLAB Document mysvd.cpp

: (
: )

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

Matlab/Simulink

126

mlfPrintf("S = \n"); mlfPrintMatrix(S);


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

3.23

mysvd.cpp

6. 3.24
MATLAB C Math Library

3.24

127

consoleprj.cpp

7. Microsoft Visual C++ IDE Tools|Options


%MATLABROOT%\extern\include MATLAB C/C++ Math
Library 3.25
8. Microsoft Visual C++ IDE Tools|Options
%MATLABROOT%\extern\lib\win32\Microsoft\msvc60 Microsoft Visual
C++ 5.0%MATLABROOT%\extern\lib\ win32\Microsoft\msvc50
MATLAB C/C++ Math Library 3.26
9. 3.27 Microsoft Visual C++ IDE Project|
Settings %MATLABROOT%\extern\lib\win32\Microsoft\msvc60
libmmfile.lib libmwarpack.lib libeng.lib libmwlapack.lib libmat.lib libmwsglm.lib
libmatlb.liblibmx.liblibmatlbmx.libsgl.lib libmex.lib Link Object/library
modules Microsoft Visual C++ 5.0
%MATLABROOT%\extern\lib\win32 \Microsoft\msvc50
10. 3.28

: (
: )

: (
: )

Matlab/Simulink

128

3.25 %MATLABROOT%\extern\inlcude

:
:

3.26

%MATLABROOT%\extern\lib\win32\Microsoft\msvc60

3.27

: 9.
3.27 Microsoft
Visual C++ IDE
Project|Settings
%MATLABROOT%\extern\lib
\win32\Microsoft\msvc60
libmmfile.lib
libmwarpack.liblibeng.lib
libmwlapack.liblibmat.lib
libmwsglm.liblibmatlb.lib
libmx.liblibmatlbmx.lib
sgl.lib libmex.lib
Link Object/library
modules
( Microsoft Visual
C++ 5.0
%MATLABROOT%\extern\lib
\win32 \Microsoft\msvc50
)
10.

3.28

3.28

129

consoleprj.exe

MFC Windows MATLAB C Math Library


1. Microsoft Visual C++ IDE File|New MFC AppWizard
exe 3.29 OK 3.30

: (
: )
:

3.29 MFC AppWizard (exe)

130

Matlab/Simulink

2. 3.30 Single document


3.31

3.30

Single document

:
: 3.
mfcprjView.h
int mysvd
: (
: CDC *pDC
: )
: ;

3.31

mfcprj

3. mfcprjView.hint mysvd(CDC *pDC);

131

#if !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_)
#define AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CMfcprjView : public CView


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

: #if !defined(AF
X_MFCPRJVIEW_H__8A4E
40B9_A69C_4760_AE4C_06
D3FB7B69CC__INC
#LUDED_)define
AFX_MFCPRJVIEW_H__8A
4E40B9_A69C_4760_AE4C_
06D3FB7B69CC__
#INCLUDED_
:

:
:
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CMfcprjView : public


CView
{
protected: // create from
serialization only
CMfcprjView();
DECLARE_DYNCREATE(C
MfcprjView)
// Attributes
public:
CMfcprjDoc*
GetDocument();
// Operations
public:
int mysvd(CDC *pDC);
// Overrides
// ClassWizard generated
virtual function overrides
//{{AFX_VIRTUAL(CMfcp
rjView)
public:
virtual void OnDraw(CDC*
pDC); // overridden to draw
this view
virtual BOOL
PreCreateWindow(CREATES
TRUCT& cs);
protected:
virtual BOOL
OnPreparePrinting(CPrintInfo*
pInfo);
virtual void
OnBeginPrinting(CDC*
pDC,
...
[1]

Matlab/Simulink

132

protected:
//{{AFX_MSG(CMfcprjView)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};

:
:

#ifndef _DEBUG // debug version in mfcprjView.cpp


inline CMfcprjDoc* CMfcprjView::GetDocument()
{ return (CMfcprjDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous
//line.
#endif // !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_06D3FB7B69CC__INCLUDED_)

4.
matlab.h
z
z mysvdCDC *pDC
z OnDrawCDC* pDC mysvdCDC *pDC
z

: (
: )
: (

// mfcprjView.cpp : implementation of the CMfcprjView class


//

: )

#include "stdafx.h"
#include "mfcprj.h"

: )

#include "mfcprjDoc.h"
#include "mfcprjView.h"
#include "matlab.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static double data[] = { 21, 3, 15, 57, 12, 83, 6, 90 };

: (

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

133

Matlab/Simulink

134

// TODO: add draw code for native data here


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

: pDC>TextOut(0,nHeight,"This is a
demo of calling SVD function
directly");

135

//mlfPrintf("S = \n"); mlfPrintMatrix(S);


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

:
:
:
:

Matlab/Simulink

136

//mlfPrintf("Two inputs, three outputs:\n");


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

137

void CMfcprjView::Dump(CDumpContext& dc) const


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

5. Win32 MATLAB C Math Library 789

6. mfcprj 3.32

:
:

3.32

mfcprj.exe

138

Matlab/Simulink

3.6 VB MATLAB
VB MATLAB
MATLAB MatrixVB MatrixVB MATLAB
MathWorks http://www.mathworks.com MatrixVB4.51

1. Windows MatrixVB4.51 matrix


VB4510.exe 3.33

3.33

Welcome to MatrixVB Setup

2. 3.33 Next 3.34

3.34 Read Me File

139

3. 3.34 Next MathWorks


3.35

3.35 MathWorks Inc. Software License Agreement

4. 3.35 3.36

Next 3.37

3.36

5. MatrixVB license
3.38 license license OK

:
: (
:
: )

140

Matlab/Simulink

3.37

Installing

3.38 MatrixVB License

MatrixVB MatrixVB 3.39 3.40


VB MATLAB invhilb plot Microsoft Visual Basic
3.41 VB MATLAB
3.39
MatrixVB Guide Reference Guide

3.39 MatrixVB

: L

: r

141

3.40 VB MATLAB invhilb plot

3.41

VB MATLAB invhilb plot

>> plot(invhilb(5))

3.42

: L

Matlab/Simulink

142

3.42

plot(invhilb(5))

>> which invhilb


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

131:

[1]

fcr

#if _MSC_VER > 1000


#pragma once
#endif // _MSC_VER > 1000

class CMfcprjView : public CView


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

2002-9-17 9:16:00

};
#ifndef _DEBUG // debug version in mfcprjView.cpp
inline CMfcprjDoc* CMfcprjView::GetDocument()
{ return (CMfcprjDoc*)m_pDocument; }
#endif
////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous //line.
#endif // !defined(AFX_MFCPRJVIEW_H__8A4E40B9_A69C_4760_AE4C_
06D3FB7B69CC__ INCLUDED_)

Simulink

Simulink MATLAB
Simulink Real-Time Workshop
C

4.1

Simulink
Simulink Simulink
Simulink Simulink
Stateflow
Simulink Simulink
z
z
z
z
z
z
z
Simulink Simulink

MATLAB Simulink

Simulink
z DSP Blockset
z Communications Blockset
MATLAB
z

: (
: )
:

Matlab/Simulink

144

4.2

Simulink 4.1

4.1 Simulink

z Simulink/Continuous 4.2

: (
: )

4.2
z

Simulink/Discrete 4.3

: (
: )

Simulink

145

4.3
z

S-Simulink/Functions & Tables 4.4

4.4 S-
z
z
z

Simulink/Math 4.5
Simulink/Nonlinear 4.6
Simulink/Signals & Systems 4.7

: (
: )

: (
: )
: (
: )
: (
: )

146

Matlab/Simulink

4.5

4.6

Simulink

147

4.7
z

Simulink/Sinks 4.8

: (
: )
: ,

4.8

Matlab/Simulink

148
z

Simulink/Sources 4.9

: (
: )

4.9
z

Simulink/Subsystems 4.10

: (
: )

4.10

Simulink

4.3

149

Blocksets

Blocksets MathWorks
Simulink
DSP Blockset
4.11

4.11

DSP Blockset

MATLAB R12.1 Simulink 4.12 MATLAB


RadioScape RadioLab
3G 3GPP UMTS Layer 1 FDD Mode

Matlab/Simulink

150

4.12

4.4

Simulink

Simulink

MATLAB

:
:
:

Simulink

151

Simulink Simulink
4.13

SIMULINK

<#>

<#>

4.13

4.13

4.14

Matlab/Simulink

152

()

4.14 Simulink

4.5

4.13

z 0 0
z

Simulink
Simulink

: (
: )
:

: (
: )

Simulink

153

Simulink 4.15

4.15 Simulink

Abs
Saturation
Signals&Systems HitCrossing

z
z
z
9 4.16 Fcn Abs
Fcn Abs
4.17

4.18 Advanced
Opimimations/Zero crossing detection Off
4.16 4.19

<#>

Matlab/Simulink

154

4.16

4.17

zerocrossing_detect.mdl

zerocrossing_detect.mdl

4.18

Simulink

155

4.19 zerocrossing_detect.mdl

Direct feedthrough
Gain
Unit Delay Simulink

Simulink

4.20
Simulink

1-x-x=xx=0.3333

4.20

algebra_loop.mdl

Simulink 4.20
Simulink/Math Algebraic Constraint Algebraic

156

Matlab/Simulink

Constraint
Simulink/Signals & Systems/IC
IC
Simulink Newton

4.21 4.22 Simulink x 2 x 2 = 0


Algebraic Constraint

4.21 x x 2 = 0
2

4.22 x x 2 = 0
2

: (
: )
:
:
:

Simulink

157

4.21 4.22
x 2 x 2 = 0 Algebraic Constraint

4.23
Configuration options/Algebraic loop Warning
MATLAB 4.23
4.21 algebraic_constraint.mdl
algebraic_constraint MATLAB

:
:
:
:
?
: Warning: Block
diagram 'algebraic_constraint'
contains 2 algebraic

Warning: Block diagram 'algebraic_constraint' contains 2 algebraic loop(s).

Found algebraic loop containing block(s):

: loop(s).
Found algebraic loop
containing block(s):

'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Initial Guess'


'algebraic_constraint/Sum'
'algebraic_constraint/Sum1'
'algebraic_constraint/Product'
'algebraic_constraint/Algebraic Constraint Initial Guess: -5/Sum' (algebraic variable)
Found algebraic loop containing block(s):
'algebraic_constraint/Algebraic Constraint Initial Guess: 5/Initial ]Guess'
'algebraic_constraint/Sum2'
'algebraic_constraint/Sum3'

'algebraic_constraint/Algebraic
Constraint Initial Guess: 5/Initial

:
: Guess'
'algebraic_constraint/Sum'
'algebraic_constraint/Sum1'
'algebraic_constraint/Product'

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

'algebraic_constraint/Algebraic
Constraint Initial Guess: 5/Sum'

:
: (algebraic
variable)
Found algebraic loop
containing block(s):
'algebraic_constraint/Algebraic
Constraint Initial Guess:
5/Initial ]

:
: Guess'
'algebraic_constraint/Sum2'
'algebraic_constraint/Sum3'
'algebraic_constraint/Product1'

4.23

'algebraic_constraint/Algebraic
Constraint Initial Guess:
5/Sum'

:
: (algebraic
variable)

Matlab/Simulink

158

4.6

C m

Simulink C m Simulink
C m C m
S- S- Simulink
m C
z C S- Simulink Real-Time
Workshop m S- Simulink

z C S- m
C S-
z Simulink
S-

S- S- MATLAB
Document PDF sfunctions.pdf C m

10 Simulink y = 10 * x C
1. S-
/*
* File : times10_c.c
* An example C-file S-function for multiplying an input by 10,
*

y = 10*u

*/

#define S_FUNCTION_NAME times10_c


#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
/*================*
* Build checking *
*================*/

: (
: )

Simulink

/* Function: mdlInitializeSizes =======================================


* Setup sizes of the various vectors.
*/
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return; /* Parameter mismatch will be reported by Simulink */
}
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetInputPortDirectFeedThrough(S, 0, 1);
if (!ssSetNumOutputPorts(S,1)) return;
ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetNumSampleTimes(S, 1);
/* Take care when specifying exception free code */
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE |
SS_OPTION_USE_TLC_WITH_ACCELERATOR);
}

/* Function: mdlInitializeSampleTimes ==================================


* Specifiy that we inherit our sample time from the driving block.
*/
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}

/* Function: mdlOutputs ================================================


* y = 10*u
*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
int_T

i;

159

Matlab/Simulink

160

InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);


real_T

*y

int_T

width = ssGetOutputPortWidth(S,0);

= ssGetOutputPortRealSignal(S,0);

for (i=0; i<width; i++) {


/*
* This example does not implement complex signal handling.
*/
*y++ = 10.0 *(*uPtrs[i]);
}
}

/* Function: mdlTerminate ==============================================


* Abstract:
*

No termination needed, but we are required to have this routine.

*/
static void mdlTerminate(SimStruct *S)
{
}

#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */


#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"

/* Code generation registration function */

#endif

2. MATLAB mex times10_c.c


Windows times10_c.dll UNIX
C mex setup

: (
: )
:

>> mex times10_c.c


>> dir times10_c.dll
TIMES10_C.DLL

Simulink

161

3. 4.24 Simulink/Functions & Tables S-Function


y = 10 * x x = sin(t ) 10 4.25

4.24 S-Function

4.25

sintx10.mdl

4. 4.25 Sine Wave 4.26 SFunction 4.27 times10_c MATLAB

5. 4.28
4.29 C 10

: (
: )

162

Matlab/Simulink

4.26 Sine Wave

4.27 S-Function

4.28 sintx10.mdl

Simulink

4.29

163

sintx10.mdl

11 Simulink y = 10 * x m
1. m S-
function [sys,x0,str,ts] = times10_m(t,x,u,flag)
%TIMES10_m S-function whose output is ten times its input.
% This M-file illustrates how to construct an M-file S-function that
% computes an output value based upon its input. The output of this
% S-function is ten times the input value:
%
%

y = 10 * u;

%
% Dispatch the flag. The switch function controls the calls to
% S-function routines at each simulation stage of the S-function.
%
switch flag,
%%%%%%%%%%%%%%%%%%
% Initialization %
%%%%%%%%%%%%%%%%%%
% Initialize the states, sample times, and state ordering strings.
case 0
[sys,x0,str,ts]=mdlInitializeSizes;
%%%%%%%%%%%
% Outputs %
%%%%%%%%%%%
% Return the outputs of the S-function block.
case 3
sys=mdlOutputs(t,x,u);

Matlab/Simulink

164

%%%%%%%%%%%%%%%%%%%
% Unhandled flags %
%%%%%%%%%%%%%%%%%%%
% There are no termination tasks (flag=9) to be handled.
% Also, there are no continuous or discrete states,
% so flags 1,2, and 4 are not used, so return an emptyu
% matrix
case { 1, 2, 4, 9 }
sys=[];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Unexpected flags (error handling)%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Return an error message for unhandled flag values.
otherwise
error(['Unhandled flag = ',num2str(flag)]);
end
% end timestwo
%
%=======================================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the S-function.

%=======================================================================

%
function [sys,x0,str,ts] = mdlInitializeSizes()
sizes = simsizes;
sizes.NumContStates = 0;
sizes.NumDiscStates = 0;
sizes.NumOutputs
sizes.NumInputs

= -1; % dynamically sized


= -1; % dynamically sized

sizes.DirFeedthrough = 1; % has direct feedthrough


sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
str = [];
x0 = [];
ts = [-1 0]; % inherited sample time

Simulink

165

% end mdlInitializeSizes
%
%=======================================================================
% mdlOutputs
% Return the output vector for the S-function
%=======================================================================
%
function sys = mdlOutputs(t,x,u)
sys = u * 10;
% end mdlOutputs

2. m S- 10
sintx10.mdl S-Function 4.30 times10_m.m
MATLAB 10

MATLAB

: 22

4.30 S-Function

: (
: )
: 22

4.7

Blockset
:

Blockset Simulink Library Browser

12 10 11 Blockset
1. times10_c Windows times10_c.dlltimes10_c.c

: [ 10]
: [ 11]

: (
: )

166

Matlab/Simulink

times10_m.m e:/material/book/myblksetdemo
2. e:\material\book\myblksetdemo Simulink
Library Browser|File|New|Library
3. Simulink\Functions & Tables\S-Function 4.31
4.32 4.33

4.31

: (
: )
: (
: )

m S-Function C S-Function

4.32

m S-

4.33 C S-

4. 4.34 Create subsystem 4.31

Simulink

167

4.35

4.34

4.35

5. 4.36 4.35 4.37

4.36

6. 4.37 Mask subsystem 4.38

7. 4.39 Mask Editor 4.40

168

Matlab/Simulink
:

4.37

4.38

4.39 Mask Editor

Simulink

4.40

169

8. 4.40 Subsystem my own X 10 blocks


times10.mdl 4.41

4.41 times10.mdl

9. 4.40 Simulink\Math\Gain 10
4.42

4.42

Gain times10.mdl

10. times10.mdl e:\material\book\myblksetdemo m


slblocks.m

1.

function blkStruct = slblocks

2.

%SLBLOCKS Defines the Simulink library block representation

3.

%for My Simulink Blockset demo.

4.

Matlab/Simulink

170
5.
6.

blkStruct.Name

7.

blkStruct.OpenFcn = 'times10';

= ['times10' sprintf('\n') 'Blockset'];

8.

blkStruct.MaskInitialization = '';

9.

blkStruct.MaskDisplay = ['disp(''times10 Blockset'')'];

10.
11.

% Define the library list for the Simulink Library browser.

12.

% Return the name of the library model and the name for it

13.

14.

Browser(1).Library = 'times10';

15.

Browser(1).Name = 'Times10 Blockset';

16.
17.

blkStruct.Browser = Browser;

18.
19.

% End of slblocks.m

7 mdl
z 14 mdl
z 15 Simulink Library Browser
Simulink Library Browser MATLAB
slblocks.m Simulink Library Browser
11. e:\material\book\myblksetdemo MATLAB 4.43

4.43 MATLAB

: (
: )
: (
: )

Simulink

171

12. Simulink Library Browser


Times10 Blockset Simulink Library Browser 4.44 4.45
Times10 Blockset

4.44 Times10 Blockset

4.45 Times10 Blockset\my own X 10 blocks

Matlab/Simulink

172

4.8

Simulink
Simulink
Simulink Matlab Matlab
Simulink
Simulink MATLAB
Document PDF sl_using.pdf MathWorks
http://www.mathworks.com Simulink

13 4.46 F-14 4.47

4.46 %MATLABROOT%\toolbox\simulink\simdemos\aerospace\f14.mdl

14 4.48
15 4.49 IS-95A
4.50

Simulink

4.47 f14.mdl

4.48 bluetooth_voice.mdl

173

174

Matlab/Simulink

4.49

tpc95.mdl

4.50 tpc95.mdl

Simulink

175

16 4.51 GSM EDGE


4.52 4.53 4.54 4.55

4.51 gsm_edge.mdl
:

4.52 GSM

176

Matlab/Simulink

4.53 GSM/EDGE
:

4.54 EDGE

Simulink

177

4.55 EDGE

17 4.56 IS-95A
Stateflow

178

Matlab/Simulink

4.56

IS-95A

Simulink

179

18 4.57

4.57 softdec.mdl

Real-Time Workshop

m MATLAB Compiler
C/C++MATLAB Compiler C/C++
PC UNIX
DSP FPGA VxWorks
MATLAB DSPFPGA VxWorks
Simulink Real-Time
WorkshopRTW Xilinx System GeneratorAltera DSP Builder
678

: )
: (
: )

5.1

Real-Time Workshop MathWorks Simulink


ANSI C Ada

5.1

5.1

RTW 5.2

Real-Time Workshop

181

Simulink RTW

5.2 RTW

5.2
Real-Time Workshop 5.3 Real-Time Workshop
RTW Matlab Matlab
RTW RTW Simulink

z model.rtw model.mdl model Simulink


Matlab rtwgen model.rtw
model.mdl S-
TLC Blockmodel.rtw model.mdl
z model.c 5.3 tornado.tlc
model.c Simulink C model.rtw
Block{} TLC
5.3 gain.tlc TLC
TLC model.c TLC
%MATLABROOT%\rtw\cada\tlc\ tlc_ctlc_ada
Simulink TLC
5.3 sfun.tlc C S- 5.3
sfun.c S- C C-MEX S-

:
5.3 RTW

: (
: )
: (
: )
: (
: )
: (
: )
: (
: )
: (
: )
: (
: )

Matlab/Simulink

182

model.c

5.3 RTW
z

model.mk makefile Matlab rtw_c.p


rtw_ada.p makefile 5.3 tornado.tmf
makefile .tmf
VxWorks/Tornado makefile tornado.tmfrtw_c.p rtw_ada
makefile makefile
|>TOKEN<| makefile

model.exe.exe Microsoft

exe

5.3

: (
: )

: (
: )

RTW

Real-Time Workshop Simulink


Real-Time Workshop 5.4 Browse

z *.tlcTarget Language Compiler


z makefile *.tmf
Tornado VxWorks Real-Time Target
makefile tornado.tlctornado.tmf 5.2

:
: (
: )
: (
: )
: (
: )
: (
: )
:

5.4

Real-Time Workshop

183

Real-Time Workshop

Windows MATLAB R12.1 Real-Time Workshop 5.5

5.5 Real-Time Workshop

ASAM-ASAP2 Data Definition Target


ASAP2 ASAM
RTW ASAP2

z ASAM-ASAP2 Data Definition Target ASAP2

: (
: )

Matlab/Simulink

184

z RTW Embedded Coder ASAP2


ASAM-ASAP2 Data Definition Target
%MATLABROOT%\toolbox\stateflow\sfdemos\sf_car.mdl ASAP2
************************************************************************
*
* ASAP2 file:

sf_car.a2l

*
* Real-Time Workshop code generation for Simulink model "sf_car.mdl".
*
* Model Version

: 1.132

* Real-Time Workshop file version : 4.1 $Date: 2001/05/16 13:59:43 $


* Real-Time Workshop file generated on : Mon Dec 17 20:59:10 2001
* TLC version

: 4.1 (May 19 2001)

* C source code generated on

: Mon Dec 17 20:59:15 2001

*
* Relevant TLC Options:
* InlineParameters

=1

* RollThreshold

=5

* CodeFormat

= RealTime

*
* Simulink model settings:
* Solver

: FixedStep

* StartTime : 0.0 s
* StopTime : 30.0 s
* FixedStep : 0.04 s
*
* (add additional file header information here)
*
***************************************************************************/
ASAP2_VERSION 1 30
/begin PROJECT unspecified ""
/begin HEADER ""
/* (add HEADER definition here) */
/end HEADER
/begin MODULE unspecified ""
/begin A2ML

: on

Real-Time Workshop

/* (add A2ML definition here) */


/end A2ML
/begin MOD_PAR ""
/* (add mod_par definition here) */
/end MOD_PAR
/begin MOD_COMMON ""
/* (add mod_common definition here) */
/end MOD_COMMON
/begin RECORD_LAYOUT Scalar_UBYTE
FNC_VALUES 1 UBYTE COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_BYTE
FNC_VALUES 1 SBYTE COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_UWORD
FNC_VALUES 1 UWORD COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_WORD
FNC_VALUES 1 SWORD COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_ULONG
FNC_VALUES 1 ULONG COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_LONG
FNC_VALUES 1 SLONG COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_FLOAT32_IEEE
FNC_VALUES 1 FLOAT32_IEEE COLUMN_DIR DIRECT
/end RECORD_LAYOUT
/begin RECORD_LAYOUT Scalar_FLOAT64_IEEE
FNC_VALUES 1 FLOAT64_IEEE COLUMN_DIR DIRECT
/end RECORD_LAYOUT

185

Matlab/Simulink

186

/begin RECORD_LAYOUT Lookup1D_UBYTE


NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 UBYTE INDEX_INCR DIRECT

: X

FNC_VALUES

4 UBYTE COLUMN_DIR DIRECT

: VALUES

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_BYTE
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 SBYTE INDEX_INCR DIRECT

FNC_VALUES

4 SBYTE COLUMN_DIR DIRECT

: RESERVED

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_UWORD
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 UWORD INDEX_INCR DIRECT

FNC_VALUES

4 UWORD COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_WORD
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 SWORD INDEX_INCR DIRECT

FNC_VALUES

4 SWORD COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_ULONG
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 ULONG INDEX_INCR DIRECT

FNC_VALUES

4 ULONG COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_LONG
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 SLONG INDEX_INCR DIRECT

FNC_VALUES

4 SLONG COLUMN_DIR DIRECT

/end RECORD_LAYOUT

: VALUES

Real-Time Workshop

187

/begin RECORD_LAYOUT Lookup1D_FLOAT32_IEEE


NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 FLOAT32_IEEE INDEX_INCR DIRECT

FNC_VALUES

4 FLOAT32_IEEE COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup1D_FLOAT64_IEEE
NO_AXIS_PTS_X 1 UBYTE
RESERVED

2 UBYTE

AXIS_PTS_X

3 FLOAT64_IEEE INDEX_INCR DIRECT

FNC_VALUES

4 FLOAT64_IEEE COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_UBYTE
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 UBYTE COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_BYTE
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 SBYTE COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_UWORD
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 UWORD COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_WORD
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 SWORD COLUMN_DIR DIRECT

/end RECORD_LAYOUT

: RESERVED

Matlab/Simulink

188

/begin RECORD_LAYOUT Lookup2D_ULONG


NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 ULONG COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_LONG
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 SLONG COLUMN_DIR DIRECT

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_FLOAT32_IEEE
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 FLOAT32_IEEE COLUMN_DIR DIRECT

: RESERVED

/end RECORD_LAYOUT
/begin RECORD_LAYOUT Lookup2D_FLOAT64_IEEE
NO_AXIS_PTS_X 1 UBYTE
NO_AXIS_PTS_Y 2 UBYTE
RESERVED

3 UBYTE

FNC_VALUES

4 FLOAT64_IEEE COLUMN_DIR DIRECT

: RESERVED

/end RECORD_LAYOUT
/end MODULE

: (
: )

/end PROJECT
/* (add any file trailer comments here) */
/* EOF sf_car.a2l */

DOS4GWReal-Time Target

:
: (
: )
:
: (

DOS4GWReal-Time Target DOS Simulink


xPC Target Real-Time Windows Target
xPC Target Real-Time Windows Target PC
DOS4GWReal-Time Target WATCOM C DOS4GW Real-Time
Target DOS
Microsoft Windows DOS Microsoft Windows

: )
:
: (
: )
:
:

Real-Time Workshop

189

Real-Time Windows Target

RTW Embedded Coder


RTW Embedded Coder MathWorks RTW
RTW
Embedded Coder C
RTW Embedded Coder
z
z
z
z S- Simulink RTW Embedded Coder

z HTML
RTW Embedded Coder inlinedS-
RTW Embedded Coder 5.6
MATLAB R12.1 RTW Embedded Coder 2.0

:
: (
: )
: (
: )

5.6 RTW Embedded Coder

Visual C/C++ Project Makefile only for the RTW Embedded Coder
RTW Embedded Coder Visual C/C++

190

Matlab/Simulink

Generic Real-Time Target


Generic Real-Time Target

Visual C/C++ Project Makefile only for the grt target


Generic Real-Time Target Visual C/C++

Generic Real-Time Target with dynamic memory allocation


Generic Real-Time target

: ,

Visual C/C++ Project Makefile only for the grt_malloc target


Generic Real-Time Target with dynamic memory allocation
Visual C/C++

(Beta)LE/O (Lynx-Embedded OSEK) Real-Time Target


LE/O(Lynx-Embedded OSEK)Real-Time Target Lynx-Embedded OSEK
OSEK

: (
: )
:

Rapid Simulation Target


Rapid Simulation Target
Monte Carlo Rapid Simulation Target
m

Ada83 Target for GNAT


Ada Simulation Target for GNAT
Ada Multitasking Real-Time Target for GNAT
Ada

Real-Time Windows Target


Real-Time Windows Target MathWorks PC

Real-Time Workshop

191

Microsoft Windows Simulink


Real-Time Windows Target
z
z
z

S-function Target
S-function target S- Simulink Sfunction Target Simulink C MEX S- API S-function Target

z Simulink
z
z
z
S-function Target noninlinedS- RTW Embedded
Coder RTW Embedded Coder inlinedS-

: target
: :

: target
: (
: )

Target for C6701 EVM


Target for C6701 EVM Simulink C6701 EVM TI CCS

: (
: )
: (
: )

TornadoVxWorksReal-Time Target
TornadoVxWorksReal-Time Target Simulink VxWorks/Tornado

: (
: )
:

xPC Target
xPC Target MathWorks PC
- xPC Target Simulink
xPC
Simulink

MathWorks Real-Time Workshop


http://www.mathworks.com/products/connections

192

Matlab/Simulink

5.4

RTW

RTW Simulink

C6701 EVM
RTW

z
z
z
z
z
Real-Time Workshop

:
:

Real-Time
Workshop

6
6.1

TI DSP
Developers Kit for TI DSP

Developers Kit for TI DSP MathWorks Texas InstrumentsTI


Simulink Real-Time Workshop
Simulink Real-Time Workshop
TMS320C6701 Evaluation ModuleC6701 EVM Texas Instruments Code Composer
Studio Integrated Development EnvironmentCCS IDE ANSI C Developers Kit
for TI DSP TI C6701 EVM
C6701 EVM C6701 EVM
Developers Kit for TI DSP Real-Time Workshop Target for C6701
EVM Simulink C6701 EVM
C6701 EVM CCS IDE CCS IDE

Texas Instruments C6701 EVM TMS320C6701


C6701 EVM TMS320C6701 DSP
MathWorks TI Windows
C6701 EVM

C6701 EVM Developers Kit for TI DSP CCS


IDE TI Real-Time Data Exchange RTDX

: (
: )
:
: (
: )
:
: (
: )
:
:

: (
: )

6.2

Developers Kit for TI DSP 6.1

Target for CCS IDE/C6701 EVM


Target for CCS IDE/C6701 EVM Simulink

Matlab/Simulink

194

C6701 EVM CCS IDE C6701 EVM

CCS IDE Simulink CCS IDE


Target for CCS IDE/C6701 EVM MathWorks
DSP DSP
Target for CCS IDE/C6701 EVM

z DSP
z
z Simulink CCS IDE
z DSP

:
:
:
:
DSP
:

Simulink CCS IDE

DSP

6.1

Link for CCS IDE


Link for CCS IDE CCS IDE Matlab MATLAB
CCS IDE
DSP Link for CCS IDE
z MATLAB

z m

z TI C5000/6000 DSP

: (
: )

TI DSP

195

Link for RTDX


Link for RTDX MATLAB RTDX TI DSP
Developers Kit for TI DSP MATLAB ActiveX
CCSDSP MATLAB DSP MATLAB DSP
Link for RTDX

z
z DSP
z TI C5000/6000 DSP

6.3

Developers Kit for TI DSP

:
:

DSP

TI C5000/6000
DSP

Developers Kit for TI DSP MATLAB R12.1 MATLAB R12.1


1.1 ver
>> ver tiddk
Developer's Kit for TI(tm) DSP

Version 1.1 (R12.1) 08-Jun-2001

Developers Kit for TI DSP


z MATLAB
z Simulink
z DSP Blockset
z Real-Time Workshop
z Signal Processing Toolbox
z Texas Instruments Code Composer Studio Integrated Development Environment 1.2

z Target for C6701 EVM DSP


TMS320C6701 EVM C6701 EVM
TMS320C6701 EVM
z Link for CCS IDE Link for RTDX CCS IDE
TI DSP Link for CCS IDE CCS IDE
Link for RTDX RTDX C5000/6000
z Link for CCS IDE Link for RTDX( Matlab TI DSP

Matlab/Simulink

196

)
MATLAB
Simulink
Developers Kit for TI DSP %MATLABROOT%\toolbox
6.2 Developers Kit for TI DSP

6.2 Developers Kit for TI DSP

6.4 Matlab TI DSP


Matlab TI DSP Link for CCS IDE Link for RTDX

Link for CCS IDE

: ide
: (

19Link for CCS IDE linkforccsidedemo.m Link for CCS IDE


TI DSP %MATLABROOT%\toolbox\tiddk\
tidemos\ccstutorial.m MATLAB Code Composer
Setup TI DSP 6.3

:
: )
:
:
:

TI DSP

197

6.3 Code Composer Setup

linkforccsidedemo.m

: s

% linkforccsidedemo.m

: (linkforccsdemo.
m )

% LINKFORCCSIDEDEMO is an example script intended to get the user started with

% the 'Link for Code Composer Studio IDE'. A simple target DSP

% application is loaded and run on the target DSP. Memory reads/writes

% are demonstrated. Methods that are demonstrated include

% Global Commands:

% CCSDSP object methods:

ccsboardinfo, boardprocsel, ccsdsp, clear

visible,disp,info,isrunning,address,halt,run,restart,read, write

10

regread,regwrite,visible.

11

12
13

echo off

14
15

% ==================================================================

Matlab/Simulink

198
16

% Intro

17

disp(sprintf(['=================================================\n'

18

' The ''Link for Code Composer(tm) Studio IDE'' provides a direct\n'

19

' connection between MATLAB and a DSP CPU in Code Composer.\n'

20

' This provides a mechanism for controlling and manipulating\n'

21

' a DSP application using the full computational power of MATLAB.\n'

... [1]
: ... [2]
:
:
:

... [3]

' This can be used to assist DSP debugging and development.\n'

... [4]

23

' Another possible use is for creation of MATLAB scripts for\n'

24

' verification and testing of algorithms that exist in their \n'

25

' final implementation on an actual DSP target.\n\n'

26

' Before discussing the methods available with the link object,\n'

27

' it''s necessary to select a DSP CPU to target. When the\n'

... [5]

28

' link is created, it is specific to a particular CPU,\n'

... [6]

29

' (i.e. a DSP chip) so selection is required before proceeding\n'

... [7]

30

' In general, the selection processor is only necessary \n'

... [8]

31

' for multiprocessor configurations of Code Composer.\n'

32

'===========================================================\n\n']));

33

disp('--- Press any key to continue ---');

34

pause;

22

35
36

% =================================================================

37

... [9]
: ... [10]
: ... [11]
:

... [12]

... [13]

... [14]
... [15]
... [16]

38

% command line board/processor selection command: ccsboardinfo

39

disp(sprintf(['=================================================\n'

40

' The ''Link for Code Composer(tm) Studio'' provides two tools for\n'

41

' selecting a DSP board and processor in multiprocessor\n'

42

' configurations. First, a command line version called: ''ccsboardinfo'' \n'

... [17]
:
... [18]
:
... [19]

43

' which prints a list of the available boards and processors.\n'

44

' For scripting, this command can return a structure, which\n'

45

' can be applied to programmatically select a particular DSP chip.\n'

46

'==========================================================\n\n']));

47

disp('--- Press any key to continue: ccsboardinfo ---');

48

pause;

49

echo on

... [21]
:
... [22]
: ... [23]

50

ccsboardinfo

51

echo off;

53

52
% ==================================================================

54

... [20]

... [24]

... [25]

:
:

... [26]

55

% GUI board/processor selection tool: boardprocsel

56

disp(sprintf(['================================================\n'

... [27]

... [28]

:
:

... [29]
:
... [30]
:
:

... [31]

:
6

TI DSP

57

' Another selection option is a GUI tool called ''boardprocsel''.\n'

58

' Please Note the CPU that is selected in the GUI will be used\n'

59

' for the rest of this tutorial. For single processor installations,\n'

60

' of Code Composer Studio, simply press ''OK'' to continue.\n

61

'=========================================================\n\n']));

:
:

disp('--- Press any key to continue, then select a DSP from the GUI: boardprocsel ---');

64

... [32]

:
:
... [33]
:

... [34]

:
:

62
63

199

... [35]

:
:

65

pause;

66

echo on

67

[boardNum,procNum] = boardprocsel

68

echo off

69
70

if isempty(boardNum) | isempty(procNum),

71

disp(sprintf(['The board/processor GUI was canceled without selecting a valid device\n'

... [36]

:
:

... [37]

:
:

... [38]

72

' Please restart the tutorial and select a valid board and processor\n']));

73

error('No board or processor selected to create Link' );

74

else

75

fprintf(1,[ '\n The goal of this selection process is a board number\n'

76

' and processor number that uniquely identify a particular\n'

77

' target DSP. These values are then applied during the link creation.\n\n'

78

' You selected board number = %d, and processor number = %d\n\n'],boardNum,procNum);

79

end

80

%==================================================================

81

% Object Constructor: ccsdsp

82

disp(sprintf(['================================================\n'

83

' Next, the actual connection between the MATLAB command line and Code \n'

... [39]

... [40]

... [41]

:
:

... [42]

:
:

... [43]

84

' Composer will be established. This link is represented by a MATLAB\n'

85

' object, which for this session will be saved in variable ''cc''. The\n'

86

' link object is created with the ''ccsdsp'' command, which accepts the\n'

87

' board number and processor number as input parameters. Other\n'

88

' properties can also be defined during the object creation; refer to\n'

89

' the ''ccsdsp'' documentation for more information on these properties.\n'

90

' The generated ''cc'' object will be used to direct actions to the \n'

91

' designated DSP chip. Therefore, it will appear in all commands that\n'

92

' follow the object creation. Naturally, in multiprocessor \n'

:
... [46]
:
... [47]

93

' implementations it is possible to have more than one link object.\n'

94

' NOTE Before proceeding, your DSP hardware should be reset and \n'

95

' configured as needed for operation by Code Code Composer.\n'

:
... [48]
:
... [49]

96

'==========================================================\n\n']));

97

... [44]

... [45]

:
:

... [50]

:
:
:

... [51]

:
:
... [52]
:
... [53]
:
... [54]
... [55]

... [56]

Matlab/Simulink

200
98

disp('--- Press any key to continue: ccsdsp ---');

99
100 pause;
101 echo on
102 cc=ccsdsp('boardnum',boardNum, 'procnum',procNum)
103 echo off
104 %==================================================================
105 % Visibility of Code Composer
106 disp(sprintf([=================================================\n'
107 ' You may have noticed Code Composer appear briefly when ''ccsdsp''\n'
108 ' was called. If Code Composer was not running before the link\n'
109 ' is established, it is started and then placed in the background.\n'
110 ' In most cases, the user will need to interact with Code Composer,\n'
111 ' so the first method that will be introduced (called ''visible'')\n'
112 ' controls the state of Code Composer on the desktop. This accepts\n
113 ' a Boolean input that makes Code Composer visible (1) or \n
114 ' invisible (0) on the desktop. For the rest of this tutorial, \n
115 ' we will need to interact with Code Composer, so we''ll use \n'
116 ' ''visible'' to bring it up to the desktop.\n'
117 '===========================================================\n\n']));
118
119 disp('--- Press any key to continue: visible ---');

:
... [60]
:
:
:
:
... [61]
: ... [62]
:
:
:
:
:
:
:
:
:
... [63]
:

120

121 pause;

122 echo on

123 cc.visible(1) % Force Code Composer to be visible on the desktop

124 echo off


125 %==================================================================
126 % Link Status: info, isrunning, disp
127 disp(sprintf(['================================================\n'
128 ' With the link in place, it is now possible from MATLAB to\n'
129 ' query Code Composer for status on the specified DSP CPU\n'
130 ' Three methods are available to receive status information: \n'
131 ' ''info'' returns a structure of testable Target conditions.\n'

... [59]

... [64]

... [65]
: ... [66]
:
... [67]
:

... [68]

... [69]

... [70]

... [71]

... [72]

133 ' ''isrunning'' returns the state (running or halted) of the CPU.\n'

... [73]
:
... [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;

138 echo on

... [78]

... [79]

132 ' ''disp'' prints a list of information about the target CPU.\n'

:
... [80]
:
... [81]
:
:
:
:
... [82]
6

TI DSP

139 disp(cc)
140 linkinfo = info(cc)
141 cpurunstatus = isrunning(cc)
142 echo off

201

:
... [84]
:
... [85]
:

143

144 %===================================================================

145

146 % Determine family (5x or 6x)

147 sfamily = linkinfo.subfamily;

148 if sfamily >= hex2dec('50') & sfamily < hex2dec('60'),

149 c5xfamily = (1==1);

150 elseif sfamily >= hex2dec('60') & sfamily < hex2dec('70'),


151 c5xfamily = (1==0);
152 else
153 error(' The selected family of DSP Processors is NOT supported by this product');
154 end

157 ' a TMS%03dC%2s%02d DSP processor.\n'

158 'Please note In some cases, the values reported by Code Composer\n'

159 ' do not match the physical device numbering scheme.\n\n'],

160 linkinfo.family,dec2hex(linkinfo.subfamily),linkinfo.revfamily));

164 % The Code Composer Files: load/open


165

... [88]

... [89]

... [90]

156 ' returned by the ''info'' method, it was determined that you selected\n'

163

... [87]

161

... [86]

155 disp(sprintf(['From the ''subfamily'' and ''revfamily'' members of the structure\n'

162 %==================================================================

... [83]

... [91]

... [92]

:
:

... [93]

:
:
:

168 ' Now that a connection has been established, the target CPU needs\n'

... [94]
:
... [95]
:

169 ' something to do! Therefore, the next step is to create executable \n'

170 ' code for the target CPU with Code Composer. For this tutorial, a\n'

171 ' Code Composer project file was written and included with MATLAB. \n'

172 ' The following set of commands will locate the tutorial project\n'

166 disp(sprintf([================================================\n
167

173 ' file and load it into Code Composer. This will use the ''open''\n'
174 ' method, which can direct Code Composer to load a project files \n'
175 ' or workspace file. (Note Code Composer has its own workspace\n'
176 ' files, which are quite different from MATLAB workspace files).\n'
177 ' Before proceeding, load a valid GEL file to configure the EMIF\n',

... [96]

... [97]

:
:
:

... [98]

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]

Matlab/Simulink

202

180 ' (TI)\\cc\\gel. Use menu option File->Load_GEL in Code Composer. \n',

181 ' With executable code running on the DSP, we can get down to the\n'

182 ' ultimate goal: exchanging data blocks with the target!\n'

183 '==========================================================\n\n']));

184 disp('--- Load a GEL File(if necessary), then press any key to continue: open ---');

185 pause;
186 if c5xfamily,
187 echo on
188 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_54xx.mak')
189 projpath = fileparts(projfile)

... [102]

... [103]

: ... [104]
: ... [105]
:
:

... [106]

190 open(cc,projfile)

% Open project file

191 cd(cc,projpath)

% Change working directory of Code Composer(only)

:
... [107]
:

192 echo off


193 elseif cc.info.revfamily > 10,

... [108]
:
... [109]

194 echo on

195 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x11.mak')


196 projpath = fileparts(projfile)
197 open(cc,projfile)

% Open project file

198 cd(cc,projpath)

% Change working directory of Code Composer(only)

199 echo off


200 else

... [110]
:
... [111]
:

... [112]
:
... [113]
:

... [114]
:
... [115]
:

202 projfile = fullfile(matlabroot, 'toolbox', 'tiddk', 'tidemos', 'ccstutorial', 'ccstut_6x0x.mak')

... [116]
:
... [117]

203 projpath = fileparts(projfile)

201 echo on

204 open(cc,projfile)

% Open project file

205 cd(cc,projpath)

% Change working directory of Code Composer(only)

206 echo off


207 end
208 %==================================================================
209 % The Code Composer Files: address
210
211 disp(sprintf(['=================================================\n'
212

... [118]
: ... [119]
: ... [120]
:
... [121]
: ... [122]
: ... [123]
:
: ... [124]
:

213 213 ' You should notice the tutorial''s project file in Code Composer.\n'

214 ' At this point, build the tutorial project from Code Composer.\n'

215 ' (Go to the Project->Build menu option in Code Composer)\n'

216 ' The ''Link for Code Composer'' includes methods for reading\n'

217 ' the target''s symbol table to give direct access to data in \n'

218 ' the DSP memory. Note The symbol table is only available after \n'

219 ' the program file is loaded into the DSP (and after build!).\n'

: ... [126]
:
... [127]

220 ' The next step will load the generated program file ''a.out''\n'

... [125]

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'


224 '==========================================================\n\n]));

: ... [130]
:

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
233 ddatA = address(cc, 'ddat') % Now it should find the address of global value: ddat
234 dec2hex(ddatA)

: ... [132]
:

% in hexadecimal (address and page)

235 echo off


236 catch
237 echo off
238 warnState = warning(warnState);
239 disp(lasterr);

240 240 disp(sprintf(['!!!!! The load of ''a.out'' failed. Please attempt to rebuild it\n'
241 'and then manually load it from Code Composer before proceeding. \n'
242 'Then press return to attempt the load operation again\n']));

: ... [133]
: ... [134]
:
... [135]
:
... [136]

... [137]

243 pause;

244 echo on

245 load(cc, 'a.out',40) % Load the target execution file

246 ddatA = address(cc, 'ddat') % Read the address of global: ddat

: ... [139]
: ... [140]
: ... [141]

247 dec2hex(ddatA)

% in hexadecimal (address and page)

248 echo off


249 end
250
251 %===================================================================
252

... [138]

: ... [142]
: ... [143]
: ... [144]

255 ' With the target code loaded, it is now possible to examine\n'

: ... [145]
: ... [146]
:
... [147]

256 ' and modify data values in the DSP target from MATLAB.\n'

257 ' If you look at the source file listing in the Code Composer \n'

258 ' application window, there should be a file labeled:\n'

:
... [149]

259 ' ''ccstut.c'', which was shipped with this tutorial and included\n'

:
... [150]
:
... [151]

253 % Halt, run, read


254 disp(sprintf(['================================================\n'

260 ' in the project. It has two global data arrays: ''ddat'' and \n'
261 ' ''idat''. They are declared and initialized in lines 10 and 11.\n'

... [148]

Matlab/Simulink

204

263 ' MATLAB command line using the ''read'' and ''write'' methods.\n'

: ... [152]
:
... [153]

264 ' To control target execution use the ''run'', ''halt'' and\n'

262 ' These DSP memory arrays can be accessed directly from\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]
:
... [157]

271 try
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
278 ddatV = read(cc,address(cc, 'ddat'), 'single',4) % Should equal initialized value from C-Code

:
:
: ... [159]
:

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
288 ddatV = read(cc,address(cc, 'ddat'), 'single',4)
289

: ... [163]
: ... [164]
:

290 idatV = read(cc,address(cc, 'idat'), 'int16',4)


291

:
... [165]

292 restart(cc);

:
... [166]

293 echo off


294 else
295 echo on
296 halt(cc)

% halt the CPU (if necessary)

297 restart(cc)

% reset the PC to start of program

298 run(cc, 'runtohalt',20);

% wait for program execution to stop at breakpoint! (timeout = 20 seconds)

299
300 ddatV = read(cc,address(cc, 'ddat'), 'double',4) % Should equal initialized value from C-Code
301

: ... [167]
:
:
... [168]
:

TI DSP

302 idatV = read(cc,address(cc, 'idat'), 'int32',4)


303
304 write(cc,address(cc, 'ddat'),double([pi 12.3 exp(-1) sin(pi/4)])) % Modify memory values
305
306 write(cc,address(cc, 'idat'),int32([1:4]))
307
308 run(cc, 'runtohalt',20);

% Resume execution from breakpoint, then modify

309
310 ddatV = read(cc,address(cc, 'ddat'), 'double',4)
311

205

:
... [169]
: ... [170]
:
... [171]
: ... [172]
: ... [173]
:
... [174]
:
... [175]
:
... [176]
:
:

... [177]

312 idatV = read(cc,address(cc, 'idat'), 'int32',4)

313

314 restart(cc);

315
316 echo off

: ... [179]
:

317 end

318 catch

319 echo off


320 disp(lasterr);
321 disp(sprintf(['!!!! The program execution failed Generally this is because the\n'.
322 'breakpoint was not included in the source file. This caused the\n'
323 'CPU to continue execution without halting. Try re-running the\n'

... [178]

... [180]

:
:

... [181]

:
:

324 'tutorial and be sure to insert the breakpoint when it is requested.\n'

325 'In some cases, resetting the board before running the tutorial may be\n'

326 'necessary. It is often helpful to verify the Target code in Code\n'

: ... [183]
: ... [184]
:

327 'Composer before executing the tutorial.\n']));


328 error('CCS Tutorial failure');
329 end
330
331 %===================================================================
332
333 % regread/regwrite
334 if c5xfamily,

... [182]

: ... [185]
: ... [186]
:
:

... [187]

336 ' For Assembly language programmers, there are also methods\n'

:
... [188]
:
... [189]

337 ' to directly access CPU registers. For the c5xxx family, most\n'.

338 ' registers are memory-mapped and consequently are available using \n'

339 ' standard memory read/write methods. However, the ''PC'' register\n'

340 ' is not memory-mapped and therefore requires a special pair of \n'

341 ' methods: ''regread'' and ''regwrite''.\n'

:
... [191]

335 disp(sprintf([================================================\n'

342 '==========================================================\n\n']));

... [190]

: ... [192]

Matlab/Simulink

206

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'
351 ' For Assembly language programmers, there are also methods\n'
352 ' to access CPU registers: ''regread'' and ''regwrite''.\n'
353 '===========================================================\n\n']));
354 disp('--- Press any key to continue: regread/regwrite ---' );
355 pause;

: ... [196]
: ... [197]
:

... [198]
: ... [199]
: ... [200]

356 echo on
357 tReg = cc.regread('A0', '2scomp') % 2's complement version of A0

:
... [201]

358 cc.regread('B2', 'binary')

:
... [202]

% Unsigned version of B2

359 cc.regwrite('A2',tReg, '2scomp')

:
... [203]

360 echo off


361 end
362
363 %==================================================================
364
365 % Deleting the link: clear
366 disp(sprintf(['================================================\n'
367 ' Finally, to delete the link to Code Composer, use\n'
368 ' ''clear cc''. Note, if a link object exists, manually \n'
369 ' exiting Code Composer will not kill the application. It\n'
370 ' simply moves to the background. Once all link objects\n'
371 ' have been deleted (or by quiting MATLAB), then\n'
372 ' the Code Composer Application will be terminated.\n'
373 ' However, a ''visible'' Code Composer is assumed\n'
374 ' to be active and will never be halted by clearing\n'

: ... [204]
: ... [205]
:
... [206]
: ... [207]
: ... [208]
: ... [209]
: ... [210]
:
... [211]

377 disp('--- Press any key to continue: clear ---' );

: ... [212]
: ... [213]
:

378 pause;

: ... [214]

375 ' any Maltab links.\n'


376 '==========================================================\n\n]));

379 echo on
380 clear cc

381 echo off

: echo off
:

6
z
z
z

TI DSP

207

13 MATLAB
49 MATLAB
50 Code Composer Setup

>> ccsboardinfo
Board Board

Proc Processor

Num Name

Num Name

Processor
Type

--- ------ --- ---------------------------- -------------1 C64xx Simulator (Texas Instrum ... 0 CPU

TMS320C6400

0 C6xxx EVM (Texas Instruments)

TMS320C6200

CPU_1

67
6.4

>> [boardNum,procNum] = boardprocsel


:

boardNum =
1

procNum =
0

6.4

6.4
z
z

70~79
102 MATLAB CCSDSP cc MATLAB
Code Composer StudioLink for CCS
IDE CCSDSP

:
:
:

Matlab/Simulink

208

>> cc=ccsdsp('boardnum',boardNum,'procnum',procNum)
CCSDSP Object:
API version

: 1.0

Processor type : TMS320C64127


:

Processor name : CPU


Running?
Board number

: No
:1

Processor number : 0
Default timeout

: 10.00 secs

Developers Kit for TI DSP Link for CCS IDE 6.1

z 123 cc visible Code Composer Studio

>> cc.visible(1)

6.5

6.5
z

cc.visible(1)

139

>> disp(cc)
CCSDSP Object:

6
API version

: 1.0

Processor type

: TMS320C64127

Processor name

: CPU

Running?

: No

Board number

:1

TI DSP

209

Processor number : 0
Default timeout

: 10.00 secs

140

>> linkinfo = info(cc)


linkinfo =
procname: 'CPU'
isbigendian: 0
family: 320
subfamily: 100
revfamily: 127

:
timeout: 10
6.1

Link for CCS IDE

animate

ccsboardinfo

CCS IDE

ccsdsp

CCS IDE

cd

CCS IDE

clear

CCS IDE
CCS IDE

dir
disp

CCS IDE

display

CCS IDE

get

CCS IDE

halt
info

isreadable

CCS IDE PC

isvisible

MATLAB
(*.out*.obj)

load
open

MATLAB

isrunning
iswritable

CCS IDE

6.5 cc.visible(1)

: linkinfo =
info(cc)

Matlab/Simulink

210
read

TI DSP

211

regread

regwrite

reset

restart

run

set

CCS IDE

symbol

CCS IDE

visible

CCS IDE

write

141 0 1

cpurunstatus = isrunning(cc)
cpurunstatus =
0
z
z

146~154 TI C5000/6000 DSP


155~160 info

>> disp(sprintf(['From the ''subfamily'' and ''revfamily'' members of the structure\n'...


' returned by the ''info'' method, it was determined that you selected\n'...

:
:
:
:

' a TMS%03dC%2s%02d DSP processor.\n'...


'Please note - In some cases, the values reported by Code Composer\n'...

' do not match the physical device numbering scheme.\n\n'],...

linkinfo.family,dec2hex(linkinfo.subfamily),linkinfo.revfamily));
From the 'subfamily' and 'revfamily' members of the structure
returned by the 'info' method, it was determined that you selected
a TMS320C64127 DSP processor.
Please note - In some cases, the values reported by Code Composer
do not match the physical device numbering scheme.
z

186~207 CCS IDE


MATLAB
6.6
227~249 a.out ddat

:
:
:

Matlab/Simulink

212

>> warnState = warning('on'); address(cc,'ddat')


Warning: Address: Failed to locate symbol 'ddat' in symbol table
ans =
[]
>>ddatA = address(cc,'ddat')
ddatA =
1.0e+009 *
2.1475

>>dec2hex(ddatA)
ans =
80000010
00000000

6.6
z

ccstut_6x11.mak

269~270 6.6 3 printf

271~329 6.6 3
ddat 4 MATLAB ddatV idat 4
MATLAB idatV ddat 4
double([pi 12.3 exp(-1) sin(pi/4)] idat 4 int32([1:4])

:
:
:
: (
: )

TI DSP

213

ddat 4
MATLAB ddatV idat 4
MATLAB idatV DSP

>> halt(cc)
restart(cc)
run(cc,'runtohalt',20);
ddatV = read(cc,address(cc,'ddat'),'double',4)
idatV = read(cc,address(cc,'idat'),'int32',4)
write(cc,address(cc,'ddat'),double([pi 12.3 exp(-1) sin(pi/4)]))
write(cc,address(cc,'idat'),int32([1:4]))
run(cc,'runtohalt',20);
ddatV = read(cc,address(cc,'ddat'),'double',4)
idatV = read(cc,address(cc,'idat'),'int32',4)
restart(cc);
ddatV =
16.3000 -2.1300 5.1000 11.8000

idatV =
1

508

647

7000

ddatV =
3.1416 12.3000 0.3679 0.7071

idatV =
1
z

333~361
tReg = cc.regread('A0','2scomp') A0

Matlab/Simulink

214

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


tReg =
3

cc.regread('B2','binary') B2

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

z
z

cc.regwrite('A2',tReg,'2scomp') A2 tReg
cc.regread('PC','binary')
cc.regwrite('PC',hex2dec('100'),'binary') 256

380 CCSDSP Link for CCS IDE


disp pause MATLAB

Link for RTDX


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

:
: (
:
: )
:
: (
: linkforrtdxde
mo.m
:
:
: )
:
:
:
:

%linkforrtdxdemo.m

% LINKFORRTDXDEMO is an example script intended to get the user started with the

% Link for RTDX. A simple target DSP application is loaded and run on the

% target DSP, and data messages are transfered via RTDX between the host

% application (MATLAB) and the target DSP. The tutorial writes integers 1:10

% to the target DSP. The target DSP takes the array of integers and

% increments it by 1 and writes the resultant array to the host. This action

% is performed 20 successive times, with each iteration incrementing the the

% previous array result by one. The 20 messages are read by the script using

10

% READMSG and READMAT, employing various output formats.

11

:
:
:
:
:
:

TI DSP

215

12
13

% Board and processor selection

14

disp(sprintf(['You will need to select a board and processor using the '...

15

'BOARD SELECTION TOOL.\nHit any key to bring up the selection tool...']));

16

pause;

:
:

17
18

[boardNum,procNum] = boardprocsel;

19

echo on

20

cc=ccsdsp('boardnum',boardNum,'procnum',procNum)

21

echo off

22
23

% Make sure selected processor is RTDX-compatible

24

% =================================================================

25

count = 0;

26

notReady = 1;

27

while notReady & count < 2,

28
29
30

if cc.isrtdxcapable,
if (cc.info.subfamily >= hex2dec('50')) & ...
(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
40

'Warning: Reset GEL','modal'));

41

elseif (cc.info.subfamily >= hex2dec('60')) & ...

42

c5x = logical(0);

44

if cc.info.revfamily > 10,

46
47
48
49
50
51

(cc.info.subfamily <= hex2dec('6f')),

43
45

'and then run C5402_DSK_Init under GEL --> C54x.'}, ...

target_subdir = 'c6x';
outFile = 'rtdxtutorial_6x1x.out';
else
target_subdir = 'c6x';
outFile = 'rtdxtutorial_6x0x.out';
end
notReady = 0;

52

else % Selected processor is not a C5xxx nor C6xxx

53

uiwait(msgbox({'RTDX is not supported for the selected board, ';

Matlab/Simulink

216

:
54

'please select another board'},...

55

'Selection Error','modal'));

56

count = count+1;

57

if count<2,

58

clear cc;

59

[boardNum,procNum] = boardprocsel;

60

pause(0.1);

61

echo on;

62

cc=ccsdsp('boardnum',boardNum,'procnum',procNum);

63

echo off;

64

end

65
66

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

:
uiwait(msgbox({'RTDX is not
supported for the
selected board, ';

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

TI DSP

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

217

Matlab/Simulink

218

136 % test DISPLAY and DISP


137 cc.rtdx
138
139 % RESTART target
140 cc.restart;
141
142 % RUN target
143 cc.run;
144
145 %==================================================================
146 echo off
147 pause(3)
148 disp('Hit any key to continue...');
149 pause
150 echo on
151
152 % ENABLE write channel
153 cc.rtdx.enable('ichan');
154 cc.rtdx.isenabled('ichan')
155
156 % write to target DSP
157 if cc.rtdx.iswritable('ichan'),
158

disp('writing to target...')

159

indata=1:10

10 1:10

160

cc.rtdx.writemsg('ichan', int16(indata))

161 end
162
163 %==================================================================
164 echo off
165 disp('Hit any key to continue...');
166 pause
167 echo on
168
169 % Check enable status of read channel
170 cc.rtdx.isenabled('ochan')
171
172 % Query for number of available messages -- should be 0
173 num_of_msgs = cc.rtdx.msgcount('ochan')
174
175 % ENABLE read channel, and verify
176 cc.rtdx.enable('ochan');

TI DSP

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

219

Matlab/Simulink

220
219 echo on
220
221 % READMAT

222 % Read into a 5x2 matrix:


223 outdata = cc.rtdx.readmat('ochan','int16', [5 2])
224
225 % Query for remaining number of available messages in read channel queue...
226 num_of_msgs = cc.rtdx.msgcount('ochan')
227

: % Query for
remaining number of available
messages in read channel
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

TI DSP

221

261 % FLUSH all remaining messages:


262 cc.rtdx.flush('ochan','all')
263
264 % Check the remaining number of available messages in read channel queue.
265 % Note: COUNT has been reset to zero.
266 num_of_msgs = cc.rtdx.msgcount('ochan')
267
268 %===================================================================
269 echo off
270 disp('Hit any key to continue...');
271 pause
272 echo on
273
274 % DISABLE all open channels
275 cc.rtdx.disable('ALL');
276
277 if cc.isrunning,

% if the target DSP is running

278 cc.halt;

% halt the processor

279 end
280
281 % DISABLE RTDX
282 cc.rtdx.disable;
283
284 % CLOSE channels
285 cc.rtdx.close('ichan');
286 cc.rtdx.close('ochan');
287 % or use: cc.rtdx.close('all');
288
289 if cc.isvisible,
290 cc.visible(0);
291 end
292
293 clear cc; % Call destructors
294 echo off;
295
296 % ======================= END OF DEMONSTRATION=====================
297
298 % [EOF] linkforrtdxdemo.m

z 18
C6701 EVM

Matlab/Simulink

222
z

z
z

z
z
z
z
z

z
z

20 MATLAB CCSDSP cc MATLAB


Code Composer StudioLink for RTDX
cc.rtdx Developers Kit for TI DSP
Link for RTDX(cc.rtdx) 6.2
23~80 RTDX
CCSDSP CCSDSP
1 C5X C6X1X
C6X0X C5X C6X
CCSDSP CCSDSP
1
81~84
90~104 cc visible
Code Composer Studio
%MATLABROOT%\toolbox\tiddk\tidemos\rtdxtutorial\c6x\
rtdxtutorial_6x0x.out
112~123 RTDX
Matlab Link for RTDX Matlab TI DSP
Matlab TI DSP RTDX
C54X
131~134 Link for RTDX
137 RTDX
139~143
152~154
156~162 RTDX DSP 10 16 [1 2 3 4 5 6 7 8
9 10]
169~170 0

172~173 0
175~177
6.2 Link for RTDX

address
clear

:
: ( 1
: )
: (
: 1 )
:
:
: (
:

%MATLABROOT%\toolbox\t
iddk\tidemos\rtdxtutorial\c6x\
rtdxtutorial_
:
: 6x0x.out)
:
: (
:
Matlab
Link for RTDX
Matlab TI
DSP Matlab
TI DSP
)
: (
: C54X)
:

RTDX CCS IDE

close

RTDX

configure

RTDX

:
:
:
:

TI DSP

223

RTDX RTDX RTDX

disable

disp

RTDX

display

RTDX
RTDX RTDX RTDX

enable

RTDX

flush
get

RTDX

info

RTDX

isreadable

MATLAB RTDX

iswritable

MATLAB RTDX

RTDX RTDX

isenabled

msgcout

RTDX

open

RTDX

readmat

RTDX
RTDX

readmsg

set
writemsg

RTDX

179~181 DSP RTDX


C6701 EVM DSP

/* RTDX tutorial target application: read from host and echo back */
#include <rtdx.h>

/* RTDX_Data_Read*/

#include <stdio.h>

/* printf

#include <target.h>

/*TARGET_INITIALIZE*/

*/

#define MAX 10
short recvd[MAX];
RTDX_CreateInputChannel(ichan);

/* Channel to receive data from */

RTDX_CreateOutputChannel(ochan);

/* Channel to use to write data */

void main( void )


{
int i,j;
TARGET_INITIALIZE();

/* target specific RTDX init */

while ( !RTDX_isInputEnabled(&ichan) )
{/* wait for channel enable from MATLAB */}
RTDX_read( &ichan, recvd, sizeof(recvd) );

10 1:10

:
:

Matlab/Simulink

224

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


for (j=1; j<=20; j++) {

20

for (i=0; i<MAX; i++) {


recvd[i] +=1;
}
while ( !RTDX_isOutputEnabled(&ochan) )
{ /* wait for channel enable from MATLAB */ }
RTDX_write( &ochan, recvd, sizeof(recvd) );

while ( RTDX_writing != NULL )


{ /* wait for data xfer INTERRUPT DRIVEN for C6000 */ }
}
while ( RTDX_isInputEnabled(&ichan) || RTDX_isOutputEnabled(&ochan))
{ /* wait for channel disable from MATLAB */ }
puts("\n\n Test Completed ");
181

while (1) {}

}
z
z

189~190 20
192~193

:
:

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


outdata =
2
z

9 10 11

195~198 3

:
:

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


outdata =
[110 int16]

[110 int16] [110 int16]

>>outdata{1,2}
ans =
4
z

9 10 11 12 13

206~210

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


outdata =
[25 int16]

[25 int16]

TI DSP

212~213

225

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


outdata =
8
9
10
11
12
13
14
15
16
17
z

222~223 52

:
: (

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

: )

outdata =
9

14

10

15

11

16

12

17

13

18

z
z

225~226 12
228~229 45

:
:
: (

>>outdata = cc.rtdx.readmat('ochan', 'int16',[4 5] )

: )

outdata =
10

14

18

13

17

11

15

19

14

18

12

16

11

15

19

13

17

12

16

20
:

z
z

231~233 10
241~242 105

:
: (
: )

Matlab/Simulink

226

:
>>outdata = cc.rtdx.readmat('ochan', 'int16',[4 5] )
outdata =
12

13

14

15

16

13

14

15

16

17

14

15

16

17

18

15

16

17

18

19

16

17

18

19

20

17

18

19

20

21

18

19

20

21

22

19

20

21

22

23

20

21

22

23

24

21

22

23

24

25

z
z
z
z
z
z
z
z
z
z
z

244~246 5
254~255
257~259 4
261~262
264~266 0
274~275 RTDX
277~279
281~282 RTDX
284~287 RTDX
289~291 CCS IDE
293 CCSDSP CCS IDE CCS IDE
CCSDSP

6.5 Simulink C6701 EVM

Developers Kit for TI DSP Simulink Library Browser


C6701 EVM 6.7 C6701 EVM
Simulink

:
:
:
:
:
:
:
:
:
:

TI DSP

6.7

227

C6701 EVM

C6701 EVM ADC


C6701 EVM
C6701 EVM ADC Simulink C6701
EVM codec Line In Mic In
C6701 EVM DSP TMS320C6701

:
: (
: )

C6701 EVM DAC


C6701 EVM DAC Simulink C6701 EVM codec
LINE OUT

C6701 EVM LED


Simulink C6701 EVM LED C6701 EVM
USER Status LED0User Status LED1

: (
: )

Reset C6701 EVM

: (
: )

Simulink Reset C6701 EVM


C6701 EVM MS-DOS
C6701 EVM DSP TMS320C6701
21 C6701 EVM 6.8 C6701
EVM 6.9 y1 = 0.2 sin (2 500t )

y 2 = 0.2 sin (2 1000t ) 1000Hz

: 0.2sin(2

... [215]

: *
228

Matlab/Simulink

:
: pi

16kHz 6.9 y1=0.2sin(2*pi*500*t)


y2=0.2sin(2*pi*1000*t) Digital Filter Design 6.10 6.11 6.12

:
: 500
: *
: *

: t)

... [216]
: 0.2sin(2
: *
:
6.8 C6701 EVM

: pi
:
: *
: 1000
: *

: t)

6.9

lfilterwithsimulink.mdl

:
:
... [217]

... [218]

... [219]
: 0.2sin(2
: *
:
: pi
:
: *
: 500
: *

6.10

y1=0.2sin(2*pi*500*t)

: t)

TI DSP

229
:

6.11

: *pi
y2=0.2sin(2*pi*500*t)

: 0.2sin(2
:
: *
: 1000
: *

: t)

6.12 Digital Filter Design

230

Matlab/Simulink

6.13 6.9 lfilterwithsimulink.mdl


6.14 1000Hz

6.13

: (
: )

6.14 lfilterwithsimulink.mdl

C6701 EVM 6.9 lfilterwithsimulink.mdl


6.8 C6701 EVM lfilterwithsimulink.mdl
lfilterwithc6701.mdl 6.15
6.15 Digital Filter Design 6.9
C6701 EVM ADC 6.16 6.9 Scope C6701
EVM DAC 6.17 C6701 EVM RESET
C6701 EVM C6701 EVM

:
: (
: )
: (
: )
:
:
: (
: )

TI DSP

6.15 lfilterwithc6701.mdl

6.16 C6701 EVM ADC

6.17 C6701 EVM DAC

231

232

Matlab/Simulink

lfilterwithc6701.mdl
1. 6.18 Solver Real-Time Workshop

:
: )

: (
:

6.18

2. 6.19 Real-Time Workshop Target for C6701


EVM Real-Time Workshop Category 6.20

3. 6.21 Real-Time Workshop TLC debugging

6.19 Target for C6701 EVM

:
: (
: )

: 6.29

TI DSP

233

6.20 Target for C6701 EVM

6.21

TLC debugging

4. 6.22 Real-Time Workshop General code generation


options

6.22 General code generation options

Matlab/Simulink

234

5. 6.23 Real-Time Workshop General code generation


options(cont.)

:
: (
:
: cont.
: )
:

6.23

General code generation options(cont.)

6. 6.24 Real-Time Workshop MATLAB to CCS Link

7. C6701 EVM TI C6701 compiler


Little_Endian Big_Endian C6701 EVM 6.25
8. 6.26 Real-Time Workshop TI C6701 linker

: 6.23

:
:
:

6.24 MATLAB to CCS Link

TI DSP

6.25

6.26

235

TI C6701 compiler

TI C6701 linker

9. 6.27 Real-Time Workshop TI C6701 EVM runtime


C6701 EVM
Make Project Simulink CCS IDE CCS
IDE 6.28 lfiterwithc6701.mdl
CCS IDE
C6701 EVM 6.27
Options\Build action Build_and_execute Make Project Build &
Run
lfilterwithc6701.mdl RealTime Workshop Target configuation Build & Run CCS IDE
CCS IDE ISR

: (
: )
:

:
:

236

Matlab/Simulink

lfilterwithc6701.mdl Digital Filter Design


6.12 135 C6701 EVM

6.15 Digital Filter Design


6.29 FIR I
Ctrl+B C6701 EVM
CCS IDE

: (
: )
:
:
: (
: )
: (
: )
:

6.27

TI C6701 EVM runtime

6.28 lfilterwithc6701.mdl CCS IDE

TI DSP

237

: *
: *

: sin(2
:
:
: pi
: 500
6.29

10. Line Out 6.30

: *
: t)

: 6.29
: (

>> daqfcngen

: )

: (

: 2
: *
:
: pi
6.30

y=sin(2*pi*500*t)

daqfcngen %MATLABROOT%\
toolbox\daq\daqdemos\daqfcngen.m daqfcngen Line Out
6.31 Start Start
Stop y1=0.2sin(2*pi*500*t)

:
: *
: 500
: *
: t)

: 0.2sin(2
: *
:
: pi
:

Matlab/Simulink

238

... [220]

: *
: 500
: *

: t)
: 6.30
:
: () ... [221]
: 0.2sin(2
: *

6.31

y1=0.2sin(2*pi*500*t)

daqfcngen Line Out


6.32 Start Start Stop
y2=0.2sin(2*pi*1000*t)
>>daqfcngen

:
: pi
:
: *
: 1000
: *

: t)

... [222]

... [223]
: 0.2sin(2
: *
:
: pi
6.32

y2=0.2sin(2*pi*1000*t)

6.8 C6701 EVM Line In


y=y1+y2=0.2[sin(2*pi*500*t) + sin(2*pi*1000*t)]
y C6701 EVM 6.15
AD DA
C6701 EVM Line Out 6.8
Line In
11. Line In
>> daqscope

daqscope %MATLABROOT%\toolbox\daq\
daqdemos\daqscope.m daqscope Line In 6.33
6.34
500Hzf=7.344100/644.714=499.34 1000Hz

:
: *
: 1000
: *
: t)

... [224]

: sin(2
: *
:
: pi
:
: *
: 500
: *

: t)

: sin(2
: *
:
: pi
:
: *

... [225]

... [226]

TI DSP

6.33

239

6.34 500Hz

Line Out Line In 6.35


500Hz 1000Hz

6.35 500Hz 1000Hz

Matlab/Simulink

240
>> which daqfcngen

D:\MATLAB6p1\toolbox\daq\daqdemos\daqfcngen.m
>> help daqfcngen
DAQFCNGEN Example function generator for the Data Acquisition Toolbox.
DAQFCNGEN creates a function generator window which can be used with
the Data Acquisition Toolbox's analog output objects.
The function generator window is divided into three sections.
The top section contains a popup menu which displays the analog output

objects that currently exist in the data acquisition engine. The


selected analog output object's channels are listed in the listbox.
The bottom section consists of a popup menu that has a list of the
supported waveforms. These waveforms include sin, sinc, square,
triangle, sawtooth, random, and chirp. Waveform-specific information
such as frequency or amplitude can be entered for each waveform. If

:
:
:
:

values are not entered, the default values displayed are used.
The right section consists of three buttons which start/stop the
selected analog output object, reset the function generator window
to its original state and close the function generator window.
The selected waveform can be sent to multiple channels of the same
analog output object. Channels of the same object cannot be connected

to different waveforms.
Information on DAQFCNGEN and the Data Acquisition Toolbox are
available through the Help menu.
The daqfcngen window can be closed either by selecting the File menu

and then selecting the Close Function Generator menu or by selecting


the "x" close button. When the daqfcngen window is closed, the analog
output object will be stopped, if it is running, and deleted.
See also DAQSCOPE
>> which daqscope
D:\MATLAB6p1\toolbox\daq\daqdemos\daqscope.m
>> help daqscope

:
:
:

TI DSP

241

DAQSCOPE Example oscilloscope for the Data Acquisition Toolbox.


DAQSCOPE creates an oscilloscope window for displaying the incoming
signals which can be used with the Data Acquisition Toolbox's analog
input objects.
DAQSCOPE can run any registered adaptor that has an analog input
subsystem. The name of these adaptors and the adaptors' device

identification number are displayed in the popup menu. This allows,


for example, multiple nidaq cards to be distinguished from each other
by their device identification number. The listbox beneath the popup
menu contains a list of the channels that can be added to the selected
adaptor. If all the channels were added to the analog input object,
Channel1 would correspond to the first hardware channel that could be
specified, Channel2 would correspond to the second hardware channel
that could be specified and so on. A maximum of sixteen channels can
be selected and displayed. If more than sixteen channels are selected,

:
:
:
:
:

a warning will occur and no channels will be displayed.


:
An analog input object is created from the selected adaptor, adaptor

device identification number and the selected channels. When the button
with the triangle image is selected, the created analog input object is

started with the start command and the selected channels' signal will
be displayed in the daqscope axes. While the analog input object is

running, it is not possible to change the selected adaptor or the

selected channels. However, by selecting the pause button (the same


button as the start button - toggled), the channels and adaptor

selected can be modified.

The time range or x-axis range can be modified while the object is

running by moving the X-Axis range slider. The volts per division (or

the y-axis range) can be modified while the object is running by


entering a value in the Volts Per Division edit text box. The volts

per division can be calculated internally by selecting the Autoset

radiobutton to produce a usable display of the incoming signal.


:
A legend can be added to the axes window to distinguish between the

channel signals plotted by selecting the View menu and then selecting
the Legend menu.

:
:

Information on DAQSCOPE and the Data Acquisition Toolbox are available


through the Help menu.

Matlab/Simulink

242

The daqscope window can be closed either by selecting the File menu
and then selecting the Close Oscilloscope menu or by selecting the
"x" close button. When the daqscope window is closed, the analog
input object will be stopped, if it is running, and deleted.
See also DAQFCNGEN.

Xilinx FPGA

:
: w
: <#>
<#>
:

MathWorks Xilinx
Simulink FPGA System Generator for Simulink
Simulink MatlabMathWorks FGPA

z
Simulink DSP
z
System Generator for Simulink Simulink Xilinx FPGA
VHDL
z
Xilinx IP

: <#>
: <#>
: <#>
<#>
<#> System Generator for
Simulink Simulink
Xilinx FPGA
VHDL
: <#>
: <#>

7.1

FPGA

FPGA 7.1 DSP FPGA


Simulink
FPGA FPGA
VHDL FPGA Simulink
FPGA
FPGA Simulink FPGA

:
:

7.1

FPGA

Xilinx FPGA

243

System Generator for Simulink DSP


Simulink FPGA
Simulink
FPGA FPGA 7.2

:
: System
Generator for Simulink
:

7.2 System Generator for Simulink FPGA

7.2

Xilinx Blockset

System Generator for Simulink Xilinx MATLAB


Xilinx System Generator for
Simulink V1.0 MATLAB R12 Xilinx
MATLAB R12.1
1 System Generator for Simulink Real-Time Workshop
Simulink
2System Generator for Simulink FPGA DSP
FPGA FPGA
System Generator for Simulink FPGA
VHDL Simulink System Generator for Simulink
Simulink Xilinx Blockset 7.3
System Generator VHDL

:
:
:
:

Matlab/Simulink

244

7.3 Xilinx Blockset

: (
: )

Xilinx Blockset
z
Basic Elements 7.4

:
: (
: )
:
:
Word
7.4 Basic Elements
z

DSP FFT 7.5

: (
: )

Xilinx FPGA

245

7.5 DSP FFT


z

Math 7.6

: (
: )

7.6 Math
z
z

Memory 7.7
Matlab IO 7.8

: (
: )
: (
: )

246

Matlab/Simulink

7.7 Memory

:
: ()
7.8 Matlab IO

FPGA Simulink 7.9

... [1]
:
Word
: ()

... [2]

Xilinx FPGA

247

7.9 FPGA Simulink

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
z

7.3

: (
: )
: (
: )
:
: (
: )

VHDL

FPGA Simulink VHDL

22 7.10 FIR FPGA


Xilinx Blockset FIR Xilinx Blockset
FIR
7.10 Din 7.11 FIR 7.12
Dout 7.13 Dout MAC 7.14
MAC Based FIR 7.15

:
7.10 firandmac.mdl(

)
: Xilinx Blockset
FIR
:
:
Xilinx Blockset
FIR

:
:
:
:
:

248

Matlab/Simulink

7.10 firandmac.mdl

7.11

Din Gateway In

: (
: )

Xilinx FPGA

7.12

249

FIR
:

7.13 Dout Gateway Out

7.14 Dout MAC Gateway Out

: (
: )

: (
: )

250

Matlab/Simulink

7.15 MAC Based FIR

7.15 Controller MAC 7.16


7.17

7.16 Controller
:

7.17 MAC

Xilinx FPGA

251

7.10 firandmac.mdl Simulink 7.18


coef = [3 5 7 0] 7.19

7.18 firandmac.mdl

7.19 firandmac.mdl

firandmac.mdl FPGA VHDL FPGA


System Generator 7.10 Xilinx
Blockset/Basic Elements Xilinx FPGA VHDL
7.10 System Generator 7.20

: ,

Matlab/Simulink

252

7.20 System Generator

7.20

Xilinx Product Family


System Generator for Simulink V1.0 Xilinx FPGA
z
z

Virtex
Spartan-II

Target Directory

Create Testbench
VHDL

Override with Doubles


Simulink Xilinx
Blockset\Matlab IO\Gateway In Simulink FPGA
FPGA Xilinx Blockset\Matlab IO\Gateway Out
FPGA Simulink
FPGA Simulink Override
with Doubles Simulink

: /
: /
: /
: /

Xilinx FPGA

253

FPGA

FPGA

FPGA override with doubles


Xilinx
According to Block Masks
Simulink FPGA

Everywhere in Subsystem
Simulink FPGA

Nowhere in Subsystem
Simulink FPGA

Generate Cores
VHDL Xilinx LogiCOREs
According to Block Masks
Xilinx LogiCOREs

Everywhere Available
Xilinx LogiCOREs

Nowhere
Xilinx LogiCOREs

Block Masks FPGA


System Generator 7.15
MAC Based FIR 7.17 MAC System Generator
System Generator Override with Doubles Generate Cores 7.10
System Generator System Generator
According to Block Masks System Generator
System Generator Generate VHDL

7.21

: (
: )
: (
: )

:
: (
: )
:
:

Matlab/Simulink

254

7.21

7.20 firandmac.mdl FPGA


c:\temp\firandmac VHDL
makeproj
vhdlFiles
xlcounter_core1.asy
xlspram_core1.asy
xlfir_core1.asy
xlmult_core1.asy
xlsprom_core1.asy
vcomscr.bat
firandmac_FIR.coe
firandmac_Dout.dat
firandmac_Din.dat
firandmac_Dout_MAC.dat
vsim.do
vcom.do
xlfir_core1.edn
xlmult_core1.edn
xlcounter_core1.edn
xlspram_core1.edn
xlsprom_core1.edn
coregen.log
sysgen.log
firandmac_MAC_Based_FIR_Circular_Data_Buffer.mif
xlfir_core1.mif
firandmac_MAC_Based_FIR_Coef_LUT.mif
firandmac_FIR.mif
coregen.prj
firandmac_MAC_Based_FIR_MAC.vhd
firandmac_MAC_Based_FIR_Controller.vhd
firandmac_testbench.vhd
firandmac.vhd
xlcounter.vhd
firandmac_MAC_Based_FIR.vhd

Xilinx FPGA

255

xlfir.vhd
xlfir_core1.vhd
const_pkg.vhd
clock_driver.vhd
xlmult.vhd
xlcounter_core1.vhd
xlspram_core1.vhd
xlmult_core1.vhd
xlsprom_core1.vhd
xlrelational.vhd
xlspram.vhd
xlsprom.vhd
xlfir_core1.vho
xlspram_core1.vho
xlcounter_core1.vho
xlmult_core1.vho
xlsprom_core1.vho
xlfir_core1.xco
sysgen.xco
xlmult_core1.xco
xlcounter_core1.xco
xlsprom_core1.xco
xlspram_core1.xco

vhdlFiles
const_pkg.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/conv_pkg.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_reg.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_reg_w_init.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_valid_pipe.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/synth_mult.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlshutter.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xldelay.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlfromfile.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlregister.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlclockdriver.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xldsamp.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlconstant.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xltofile.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlusamp.vhd
C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xladdsub.vhd

: 7.17

Matlab/Simulink

256

C:/matlabR12/toolbox/xilinx/sysgen/vhdl/xlclk.vhd
clock_driver.vhd
xlspram_core1.vhd
xlcounter_core1.vhd
xlmult_core1.vhd
xlfir_core1.vhd
xlsprom_core1.vhd
xlcounter.vhd
xlspram.vhd
xlfir.vhd
xlsprom.vhd
xlrelational.vhd
xlmult.vhd
firandmac_MAC_Based_FIR_MAC.vhd
firandmac_MAC_Based_FIR_Controller.vhd
firandmac_MAC_Based_FIR.vhd
firandmac.vhd
firandmac_testbench.vhd

MAC Based FIR VHDL 7.15


System Generator System Generator

7.4

: 7.10

Simulink Simulink Fixed-Point Blockset


FPGA Simulink FPGA
Simulink Fixed-Point Blockset
System Generator Override with Doubles FPGA
Simulink

:
: (
: )
: (
: )
:
:

7.5

MathWorks Xilinx
C MathWorks Simulink

Xilinx FPGA

257

Xilinx System Generator for Simulink


FPGA Xilinx IP 7.22

7.22 Simulink+System Generator

System Generator Simulink DSP


Simulink from The MathWorks +
Xilinx System Generator for Simulink +
Xilinx Platform FPGA
7.2
FPGA
FPGA DSP
DSP FPGA MathWorks Xilinx
Altera System Generator for Simulink Simulink
FPGA DSPBuilder

:
: (
: )
: (
: )
:

VxWorks
8.1

VxWorks/Tornado

UNIX Windows
Tornado WindRiver
VxWorks Tornado
VxWorks 1800 API
VxWorks RTOS Wind
I/O C++
VxWorks WindRiver Tornado 300
MathWorks Simulink VxWorks
Tornado VxWorks Real-Time TargetTornado VxWorks

VxWorks/Tornado WindRiver
http://www.windriver.com

8.2

: (
: )

: (
: )
:

Simulink VxWorks

Tornado VxWorks Real-Time Target MATLAB Real-Time


Workshop Real-Time Workshop Simulink Library Browser
Real-Time Workshop\VxWorks Support 8.1
Tornado VxWorks Real-Time Target Simulink
VxWorks Asynchronous Support 8.2
z
z
z
z
z

: (
: )
:
: (
: )

VxWorks

259

8.1 VxWorks

8.2 Asynchronous Support

VxWorks IO Devices 8.3

z
z
z
z
z

Matrix MS-AD12
Matrix MS-DA12
VME Microsystems VMIVM-3115-1
Xycom XVME-500/590
Xycom XVME-505/595

260

Matlab/Simulink

8.3

8.3

IO Devices

Tornado (VxWorks) Real-Time Target

VxWorks 8.4
MatlabSimulink Real-Time Workshop UNIX/PC VxWorks
Ethernet A/DD/A IO

:
Visio
: (
8.4 VxWorks

: )

UNIX/PC Torando Real-Time


Workshop\TornadoVxWorksReal-Time Target model.lo
Tornado shell Windsh VxWorks VxWorks
IO
VxWorks Simulink StethoScope
Simulink StethoScope VxWorks
TornadoVxWorksReal-Time Target VxWorks Simulink
StethoScope
TornadoVxWorksReal-Time Target 8.5

:
: (
: )
:
: (
: )
:
: (
: )
:

VxWorks

261

8.5 VxWorks Real-Time Target

StethoScope MATLAB Real-Time Innovations, Inc.


Real-Time Workshop\Tornado
VxWorks Real-Time Target StethoScope
z
z
z
z MATLAB
z VxWorks

: (
: )
:

:
:
: (
: )

8.5
z Simulink
Simulink Simulink
MEX- Windows ext_com.dll VxWorks

z StethoScope
VxWorks StethoScope

: (
: )
: (
: )

VxWorks

: (
: )

262

Matlab/Simulink

Solver 8.6

8.6

%MATLABROOT%\rtw\c\tornado\rt_main.c
TornadoVxWorksReal-Time Target rt_main.c

z
tSingleRate
tSingleRate
tSingleRate VxWorks semTake
semGive semTake
tSingleRate semTake
tSingleRate 30

8.5
tBaseRate
30

tRaten ()
tRate1tRate2tRaten
tRate1 tRaten
tRate1 tBaseRate

:
: (
: )
:
:
: (
: )

: (
: )
: (
: )
:
: (
: )
: (
: )
:

:
: (
: )

VxWorks

263

TornadoVxWorksReal-Time Target
StethoScope 8.5
tExtern -
Simulink tExtern Simulink
tExtern tExtern
tRaten()
tExtern %MATLABROOT%\rtw\c\src\ext_svr.c
tScopeDaemon and tScopeLink StethoScop VxWorks
tSingleRate
tBaseRate
StethoScope

: (
: )
:
: (
: )
:
:
:

: (
: )

8.4

Tornado(VxWorks)Real-Time Target

Real-Time Workshop VxWorks

1 Simulink
2 Simulink
3 makefile tornado.tmf
4 Simulink VxWorks Ethernet Simulink
VxWorks Ethernet Simulink

5 Real-Time Workshop Tornado


VxWorksReal-Time Target VxWorks makefile
make
8.7 8.8 F-14 f14.mdl Real-Time Workshop
Tornado 8.7 VxWorks

: (
: )
: (
: )
:

Simulink
Simulink Simulink
:

Matlab/Simulink

264

VxWorks IO
IO
Simulink C S-
Real-Time Workshop C
TLC S-
C S-
IO MATLAB Document PDF
rtw_ug.pdf Targeting Real-Time Systems

8.7 VxWorks

makefile
VxWorks makefile tornado.tmf Real-Time Workshop
VxWorks tornado.tmf

VxWorks

265

8.8 F-14 %MATLABROOT%\toolbox\simulink\simdemos\aerospace\f14.mdl

VxWorks
CPU
CPU CPU VxWorks
CPU VxWorks
CPU tornado.tmf
z

#-------------- VxWorks Configuration -------------


VX_TARGET_TYPE = 68k
CPU_TYPE = MC68040

Tornado Target
Server
z

#-------------- Macros for Downloading to Target-------------TARGET = targetname

Matlab/Simulink

266
TGTSVR_HOST = hostname

Tornado
makefile tornado.tmf 3
z

#-------------- Tool Locations -------------WIND_BASE = c:/Tornado


WIND_HOST_TYPE = x86win32
WIND_REGISTRY = $(COMPUTERNAME)

Simulink
makefile
z
Solver 8.9 Real-Time
Workshop 8.10

: (
: )
: (
: )

8.9

Solver

Solver Fixed-step
discrete no continuous status

: (
: )

VxWorks

267

Real-Time Workshop Target configuration


Browse System Target File Browser 8.11
:

8.10

Real-Time Workshop

8.11 System Target File Browser

8.11 Tornado VxWorks Real-Time Target OK


Target configuration

System target file tornado.tlc


Template makefile tornado.tmf 8.4 makefile
tornado.tmf

Make command make_rtw

: (
: )

Matlab/Simulink

268

TornadoVxWorksReal-Time Target
Real-Time Workshop Tornado code generation options
8.12

8.12

: (
: )
:

Tornado code generation options

Real-Time Workshop
TornadoVxWorksReal-Time Target
MAT-file logging
model.mat
Workspace I/O Real-Time Workshop
MAT-file variable name modifier
VxWorks
VxWorks
Make command OPTS
"-DSAVEFILE=filename"
make_rtw OPTS="-DSAVEFILE=filename"
External mode Simulink
Make command OPTS="-DVERBOSE"
verbose VxWorks

Code format RealTime RealTimeMalloc


StethoScope StethoScope
Download to VxWorks target
z
Real-Time Workshop Target Configuration

: (
: )
:

: :
: :

VxWorks

269

Build Generate code only Build Generate code


makefile
model.lololoadable object
Download to VxWorks targetTarget Server

perl %MATLABROOT%\rtw\c\
tornado\downld.pl
StethoScope(StethoScope) StethoScope
libxdr.solibutilstssip.so libscope.so VxWorks
StethoScope

: (
: )
: (

: )
:
: (
: )
:
: (
:

: )

TornadoVxWorksReal-Time Target
Tornado
z VxWorks
VxWorks
Target Server VxWorks Target Agent
Tornado DOS DOS

: (
: )
:
: (
: )
: (
: )
: (

tgtsvr target_network_name

VxWorks
Tornado DOS Tornado WindSh
WindSh
z

ld <model.lo

StethoScope
StethoScope libxdr.solibutilstssip.so libscope.so
z
VxWorks rt_main
Simulink StethoScope
StethoScope rt_main rt_main.c
%MATLABROOT%\rtw\c\tornado
/* Function: rt_main ===========================================================
* Abstract:

: )
: /* Function:
rt_main
======================
======================
=======
* Abstract:
* Initialize the Simulink
model pointed to by
"model_name" and start
* model execution.
*
* This routine spawns a task
to execute the passed model. It
will
* optionally initialize
StethoScope (via
ScopeInitServer), if it
* hasn't already been done. It
also optionally sets up external
mode
* communications channels
to Simulink.
*
* Parameters:
... [1]

Matlab/Simulink

270

* Initialize the Simulink model pointed to by "model_name" and start


* model execution.
*
* This routine spawns a task to execute the passed model. It will
* optionally initialize StethoScope (via ScopeInitServer), if it hasn't
* already been done. It also optionally sets up external mode
* communications channels to Simulink.
*
* Parameters:
*
* "model_name" is the entry point for the Simulink-generated code
* and is the same as the Simulink block diagram model name.
*
* "optStr" is an option string of the form:
*

-option1 val1 -option2 val2 -option3

*
*

for example, "-tf 20 -w" instructs the target program to use a stop time

of 20 and to wait (in external mode) for a message from Simulink

before starting the "simulation". Note that -tf inf sets the stop time to

infinity.

*
* "scopeInstallString" determines which signals will be installed to
* StethoScope. If scopeInstallString is NULL (the default) no signals
* are installed. If it is "*", then all signals are installed. If it
* is "[A-Z]*", signals coming from blocks whose names start with capital
* letters will be installed. If it is any other string, then signals
* starting with that string are installed.
*
* "scopeFullNames" parameter determines how signals are named: if
* 0, the block names are used, if 1, then the full hierarchical
* name is used.
*
* "priority" is the priority at which the model's highest priority task
* will run. Other model tasks will run at successively lower priorities
* (i.e., high priority numbers).
*
* Example:
* To run the equalizer example from windsh, with printing of external mode
* information, use:
*
*
*

sp(rt_main,vx_equal,"0.0", "*", 0, 30)

VxWorks

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

VxWorksTIDs[NUMST];
optStrLen

SEM_ID
int_T

parseError

double
int

= strlen(optStr);

rtClockSem
finaltime

argc

char_T

= NULL;

= FALSE;
= -2.0;

= 0;

**argv

= NULL;

#ifdef MULTITASKING
SEM_ID
int_T

rtTaskSemaphoreList[NUMST];
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.
*/

271

Matlab/Simulink

272

if ((optStr != NULL) && (optStrLen > 0)) {


int i;
int

count;

char_T *thisStr;
char_T *nextStr;
/*
* Convert to lower case.
*/
for (i=0; i<optStrLen; i++) {
optStr[i] = tolower(optStr[i]);
}
/*
* Convert error string to standard argc and argv format.
*/
/* count strings and allocate an argv */
argc = CountStrs(optStr) + 1;
argv = (char **)calloc(argc,sizeof(char *));
if (argv == NULL) {
(void)fprintf(stderr,
"Memory allocation error while parsing options string.");
exit(EXIT_FAILURE);
}
/* populate argv & terminate the individual substrings */
argv[0] = "dummyProgramName";
i=1;
nextStr = optStr;
while ((nextStr != NULL) && (thisStr = GetNextStr(nextStr, &nextStr)) != NULL && ( i < argc )) {
argv[i] = thisStr;
i++;
}
/*
* Parse the standard RTW parameters. Let all unrecognized parameters
* pass through to external mode for parsing. NULL out all args handled
* so that the external mode parsing can ignore them.
*/
count = 1;

VxWorks

while(count < argc) {


const char_T *option = argv[count++];
/* final time */
if ((strcmp(option, "-tf") == 0) && (count != argc)) {
char_T

tmpstr[2];

char_T

str2[200];

double

tmpDouble;

const char_T *tfStr = argv[count++];


sscanf(tfStr, "%200s", str2);
if (strcmp(str2, "inf") == 0) {
tmpDouble = RUN_FOREVER;
} else {
char_T tmpstr[2];
if ( (sscanf(str2, "%lf%1s", &tmpDouble, tmpstr) != 1) ||
(tmpDouble < 0.0) ) {
(void)printf("finaltime must be a positive, real value or inf\n");
parseError = TRUE;
break;
}
}
finaltime = (real_T) tmpDouble;
argv[count-2] = NULL;
argv[count-1] = NULL;
}
}
if (parseError) {
PrintUsageMsg();
goto PARSE_EXIT;
}
#ifdef EXT_MODE
{
const char_T *extParseErrorMsg = ExtParseArgsAndInitUD(argc,
(const char_T **)argv);
if (extParseErrorMsg != NULL) {
printf(
"\nError processing External Mode command line arguments:\n");

273

Matlab/Simulink

274

printf("\t%s",extParseErrorMsg);
parseError = TRUE;
goto PARSE_EXIT;
}
}
#endif
/*
* Check for unprocessed ("unhandled") args.
*/
{
int i;
for (i=1; i<argc; i++) {
if (argv[i] != NULL) {
if (strcmp(argv[i], "-w") == 0) {
printf("Ignoring command line argument: '-w'\n'-w' only applies to external mode.\n");
continue;
} else {
printf("Unexpected command line argument: %s\n Exiting\n",argv[i]);
parseError = TRUE;
goto PARSE_EXIT;
}
}
}
}
PARSE_EXIT:
free(argv);
argv = NULL;
if (parseError) {
exit(EXIT_FAILURE);
}
}
if (priority <= 0 || priority > 255-(NUMST)+1) {
priority = BASE_PRIORITY;
}
/************************
* Initialize the model *
************************/

VxWorks

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

275

Matlab/Simulink

276

rtClockSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);


startStopSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
#ifdef EXT_MODE
uploadSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
rt_ExtModeInit();
extern_msg_tid = taskSpawn("tExternMsg",
priority+(NUMST), VX_FP_TASK, STACK_SIZE, (FUNCPTR)rt_MsgServer, (int_T) S,
0, 0, 0, 0, 0, 0, 0, 0, 0);
if (extern_msg_tid == ERROR) {
printf("handle taskpawn error"); /* xxx */
}
extern_upload_tid = taskSpawn("tExternUpload",
priority+(NUMST)+1,VX_FP_TASK, STACK_SIZE,(FUNCPTR)rt_UploadServer,(int_T) S,
0, 0, 0, 0, 0, 0, 0, 0, 0);
if (extern_upload_tid == ERROR) {
printf("handle taskpawn error"); /* xxx */
}
/*
* Pause until receive model start message - if external mode.
* Make sure the external mode tasks are running so that
* we are listening for commands from the host.
*/
if (ExtWaitForStartMsg()) {
printf("\nWaiting for start message from host.\n");
semTake(startStopSem, WAIT_FOREVER);
}
modelStatus = TARGET_STATUS_RUNNING;
#endif
START(S);
if (ssGetErrorStatus(S) != NULL) {
/* Need to execute MdlTerminate() before we can exit */
goto TERMINATE;
}
#ifdef STETHOSCOPE

VxWorks

/* Make sure that Stethoscope has been properly initialized. */


ScopeInitServer(4*32*1024, 4*2*1024, 0, 0);
rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,1);
#endif
sysAuxClkDisable();
rtSetSampleRate(1.0 / ssGetStepSize(S));
#ifdef MULTITASKING
for (i = FIRST_TID + 1; i < NUMST; i++) {
static char taskName[20];
sprintf(taskName, "tRate%d", i);
rtTaskSemaphoreList[i] = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
VxWorksTIDs[i] = taskSpawn(taskName,
priority + i, VX_FP_TASK, STACK_SIZE, tSubRate, (int_T) S,
(int_T) rtTaskSemaphoreList[i], i,
0, 0, 0, 0, 0, 0, 0);
}
VxWorksTIDs[0] = taskSpawn("tBaseRate",
priority, VX_FP_TASK, STACK_SIZE, tBaseRate, (int_T) S, (int_T) rtClockSem,
(int_T) startStopSem, (int_T) rtTaskSemaphoreList,
0, 0, 0, 0, 0, 0);
#else /*SingleTasking*/
VxWorksTIDs[0] = taskSpawn("tSingleRate",
priority, VX_FP_TASK, STACK_SIZE, tSingleRate, (int_T) S,
(int_T) rtClockSem, (int_T) startStopSem,
0, 0, 0, 0, 0, 0, 0);
#endif
if (sysAuxClkConnect((FUNCPTR) semGive, (int_T) rtClockSem) == OK) {
rebootHookAdd((FUNCPTR) sysAuxClkDisable);
printf("\nSimulation Starting\n");
sysAuxClkEnable();
}

/*start the real-time simulation*/

277

Matlab/Simulink

278

semTake(startStopSem, WAIT_FOREVER);
/********************
* Cleanup and exit *
********************/
printf("\nSimulation Finished\n");
sysAuxClkDisable();
taskDelete(VxWorksTIDs[0]);
semDelete(rtClockSem);
semDelete(startStopSem);
#ifdef EXT_MODE
taskDelete(extern_msg_tid);
taskDelete(extern_upload_tid);
rt_ExtModeShutdown();
semDelete(uploadSem);
#endif
#ifdef STETHOSCOPE
rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,0);
#endif
#ifdef MULTITASKING
for (i = FIRST_TID + 1; i < NUMST; i++) {
taskDelete(VxWorksTIDs[i]);
semDelete(rtTaskSemaphoreList[i]);
}
#endif
TERMINATE:
#ifdef MAT_FILE
rt_StopDataLogging(MATFILE,S);
#endif
#if defined(RT_MALLOC) && NCSTATES > 0
rt_DestroyIntegrationData(S);
#endif
TERMINATE(S);

VxWorks

279

return(EXIT_SUCCESS);
} /* end rt_main */

rt_main6

: in */

int_T rt_main(
SimStruct * (*model_name)(void),
char_T
char_T
int_T

*optStr,
*scopeInstallString,
scopeFullNames,

int_T

priority,

int_T

port)

model_name
Simulink
SimStruct
z

optStr
-tf
Simulink -w-tf 20 -w 20
Simulink
z

scopeInstallString
StethoScope
NULL
*
[A-Z]*

scopeFullName
StethoScope

1
0
S-

: (
: )
: (
: )
:

:
:
:

priority
tBaseRate

:
:

port
TCP 256~65535 17725
tornado.tmf PROGRAM_OPTS-w -tf rt_main

: (
: )
:
:

Matlab/Simulink

280

ROGRAM_OPTS = "-tf inf -w

WindShrt_main

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


z
z
z
z
z
z

model
20
StethoScope

30 tBaseRate
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
int

VxWorksTIDs[NUMST];
optStrLen

SEM_ID
int_T

rtClockSem
parseError

double
int

= strlen(optStr);

finaltime
argc

char_T

= NULL;

= FALSE;
= -2.0;

= 0;

**argv

= NULL;

#ifdef MULTITASKING
SEM_ID
int_T

rtTaskSemaphoreList[NUMST];
i;

#endif
#ifdef EXT_MODE
int_T

extern_msg_tid;

int_T

extern_upload_tid;

#endif
/*
* Do error checking on input args and parse the options string.
*/
if (model_name == NULL) {
parseError = TRUE;
goto PARSE_EXIT;
}
/*
* Parse option string.
*/
if ((optStr != NULL) && (optStrLen > 0)) {
int i;
int

count;

char_T *thisStr;
char_T *nextStr;
/*
* Convert to lower case.
*/
for (i=0; i<optStrLen; i++) {
optStr[i] = tolower(optStr[i]);

}
/*
* Convert error string to standard argc and argv format.
*/
/* count strings and allocate an argv */
argc = CountStrs(optStr) + 1;
argv = (char **)calloc(argc,sizeof(char *));
if (argv == NULL) {
(void)fprintf(stderr,
"Memory allocation error while parsing options string.");
exit(EXIT_FAILURE);
}
/* populate argv & terminate the individual substrings */
argv[0] = "dummyProgramName";
i=1;
nextStr = optStr;
while ((nextStr != NULL) && (thisStr = GetNextStr(nextStr,
&nextStr)) != NULL && ( i < argc )) {argv[i] = thisStr;
i++;
}
/*
* Parse the standard RTW parameters. Let all unrecognized
* parameters pass through to external mode for parsing. NULL
* out all args handled so that the external mode parsing can
* ignore them.
*/
count = 1;
while(count < argc) {
const char_T *option = argv[count++];
/* final time */
if ((strcmp(option, "-tf") == 0) && (count != argc)) {
char_T

tmpstr[2];

char_T

str2[200];

double

tmpDouble;

const char_T *tfStr = argv[count++];


sscanf(tfStr, "%200s", str2);
if (strcmp(str2, "inf") == 0) {
tmpDouble = RUN_FOREVER;
} else {
char_T tmpstr[2];
if ( (sscanf(str2, "%lf%1s", &tmpDouble, tmpstr) !=

1) || (tmpDouble < 0.0) ) {


(void)printf("finaltime must be a positive, real
value or inf\n");
parseError = TRUE;
break;
}
}
finaltime = (real_T) tmpDouble;
argv[count-2] = NULL;
argv[count-1] = NULL;
}
}
if (parseError) {
PrintUsageMsg();
goto PARSE_EXIT;
}
#ifdef EXT_MODE
{
const char_T *extParseErrorMsg = ExtParseArgsAndInitUD(argc,
(const char_T **)argv);
if (extParseErrorMsg != NULL) {
printf(
"\nError processing External Mode command line
arguments:\n");
printf("\t%s",extParseErrorMsg);
parseError = TRUE;
goto PARSE_EXIT;
}
}
#endif
/*
* Check for unprocessed ("unhandled") args.
*/
{
int i;
for (i=1; i<argc; i++) {
if (argv[i] != NULL) {
if (strcmp(argv[i], "-w") == 0) {
printf("Ignoring command line argument: '-w'\n'-w' only
applies to external mode.\n");
continue;
} else {
printf("Unexpected command line argument: %s\n
Exiting\n",argv[i]);

parseError = TRUE;
goto PARSE_EXIT;
}
}
}
}
PARSE_EXIT:
free(argv);
argv = NULL;
if (parseError) {
exit(EXIT_FAILURE);
}
}
if (priority <= 0 || priority > 255-(NUMST)+1) {
priority = BASE_PRIORITY;
}
/************************
* Initialize the model *
************************/
rt_InitInfAndNaN(sizeof(real_T));
S = model_name();
if (S == NULL) {
(void)fprintf(stderr,"Memory allocation error during model "
"registration");
exit(EXIT_FAILURE);
}
if (ssGetErrorStatus(S) != NULL) {
(void)fprintf(stderr,"Error during model registration: %s\n",
ssGetErrorStatus(S));
TERMINATE(S);
exit(EXIT_FAILURE);
}
if (finaltime >= 0.0 || finaltime == RUN_FOREVER) {
ssSetTFinal(S, (real_T)finaltime);
}
INITIALIZE_SIZES(S);
INITIALIZE_SAMPLE_TIMES(S);
if ((status=rt_InitTimingEngine(S)) != NULL) {
fprintf(stderr,
"Failed to initialize sample time engine: %s\n", status);
exit(EXIT_FAILURE);
}
rt_CreateIntegrationData(S);
#if defined(RT_MALLOC) && NCSTATES > 0

if(ssGetErrorStatus(S) != NULL) {
fprintf(stderr, "Error creating integration data.\n");
rt_DestroyIntegrationData(S);
TERMINATE(S);
exit(EXIT_FAILURE);
}
#endif
#ifdef MAT_FILE
if (rt_StartDataLogging(S) != NULL) {
fprintf(stderr,"Error starting data logging.\n");
return(EXIT_FAILURE);
}
#endif
rtClockSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
startStopSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
#ifdef EXT_MODE
uploadSem = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
rt_ExtModeInit();
extern_msg_tid = taskSpawn("tExternMsg",
priority+(NUMST), VX_FP_TASK, STACK_SIZE, (FUNCPTR)rt_MsgServer,
(int_T) S,0, 0, 0, 0, 0, 0, 0, 0, 0);
if (extern_msg_tid == ERROR) {
printf("handle taskpawn error"); /* xxx */
}
extern_upload_tid = taskSpawn("tExternUpload",
priority+(NUMST)+1,VX_FP_TASK,STACK_SIZE,(FUNCPTR)rt_UploadServer,
(int_T) S,0, 0, 0, 0, 0, 0, 0, 0, 0);
if (extern_upload_tid == ERROR) {
printf("handle taskpawn error"); /* xxx */
}
/*
* Pause until receive model start message - if external mode.
* Make sure the external mode tasks are running so that
* we are listening for commands from the host.
*/
if (ExtWaitForStartMsg()) {
printf("\nWaiting for start message from host.\n");
semTake(startStopSem, WAIT_FOREVER);
}
modelStatus = TARGET_STATUS_RUNNING;
#endif

START(S);
if (ssGetErrorStatus(S) != NULL) {
/* Need to execute MdlTerminate() before we can exit */
goto TERMINATE;
}
#ifdef STETHOSCOPE
/* Make sure that Stethoscope has been properly initialized. */
ScopeInitServer(4*32*1024, 4*2*1024, 0, 0);
rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,1);
#endif
sysAuxClkDisable();
rtSetSampleRate(1.0 / ssGetStepSize(S));
#ifdef MULTITASKING
for (i = FIRST_TID + 1; i < NUMST; i++) {
static char taskName[20];
sprintf(taskName, "tRate%d", i);
rtTaskSemaphoreList[i] = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY);
VxWorksTIDs[i] = taskSpawn(taskName,
priority + i, VX_FP_TASK, STACK_SIZE, tSubRate, (int_T) S,
(int_T) rtTaskSemaphoreList[i], i,
0, 0, 0, 0, 0, 0, 0);
}
VxWorksTIDs[0] = taskSpawn("tBaseRate",
priority, VX_FP_TASK, STACK_SIZE, tBaseRate, (int_T) S, (int_T)
rtClockSem, (int_T) startStopSem, (int_T) rtTaskSemaphoreList,
0, 0, 0, 0, 0, 0);
#else /*SingleTasking*/
VxWorksTIDs[0] = taskSpawn("tSingleRate",
priority, VX_FP_TASK, STACK_SIZE, tSingleRate, (int_T) S,
(int_T) rtClockSem, (int_T) startStopSem,
0, 0, 0, 0, 0, 0, 0);
#endif
if (sysAuxClkConnect((FUNCPTR) semGive, (int_T) rtClockSem) == OK) {
rebootHookAdd((FUNCPTR) sysAuxClkDisable);
printf("\nSimulation Starting\n");
sysAuxClkEnable();

/*start the real-time simulation*/

}
semTake(startStopSem, WAIT_FOREVER);
/********************
* Cleanup and exit *
********************/
printf("\nSimulation Finished\n");
sysAuxClkDisable();
taskDelete(VxWorksTIDs[0]);
semDelete(rtClockSem);
semDelete(startStopSem);
#ifdef EXT_MODE
taskDelete(extern_msg_tid);
taskDelete(extern_upload_tid);
rt_ExtModeShutdown();
semDelete(uploadSem);
#endif
#ifdef STETHOSCOPE
rtInstallRemoveSignals(S, scopeInstallString,scopeFullNames,0);
#endif
#ifdef MULTITASKING
for (i = FIRST_TID + 1; i < NUMST; i++) {
taskDelete(VxWorksTIDs[i]);
semDelete(rtTaskSemaphoreList[i]);
}
#endif
TERMINATE:
#ifdef MAT_FILE
rt_StopDataLogging(MATFILE,S);
#endif
#if defined(RT_MALLOC) && NCSTATES > 0
rt_DestroyIntegrationData(S);
#endif
TERMINATE(S);
return(EXIT_SUCCESS);
} /* end rt_ma

9
9.1

DSP

MATLAB R12.1 vs MATLAB 6.1

MATLAB X.X MATLAB RY.Y


MATLAB RY.Y MATLAB MATLAB X.X MATLAB
RY.Y MATLAB m
MATLAB RX.X MATLAB X.X
Simulink Real-Time Workshop
MATLAB R12.1 60 MATLAB
ver MATLAB R12.1
ver

: (
: )
: X
: X
:
:
:

>> ver

: (

-------------------------------------------------MATLAB Version 6.1.0.450 (R12.1) on PCWIN

MATLAB
12.1

MATLAB License Number: DEMO


-------------------------------------------------MATLAB Toolbox
MATLAB
Simulink
6.1
Stateflow

Version 6.1 (R12.1)

18-May-2001

Version 4.1 (R12.1)

06-Apr-2001

Version 4.1 (R12.1)

21-May-2001

Stateflow Coder

Version 4.1 (R12.1)

21-May-2001

Real-Time Workshop

Version 4.1 (R12.1)

18-May-2001

Real-Time Windows Target

Version 2.1 (R12.1)

02-Feb-2001

Real-Time Workshop Ada Coder

Version 4.1 (R12.1)

18-May-2001

CDMA Reference Blockset

Version 1.1 (R12.1)

18-May-2001

Communications Toolbox

Version 2.0.1 (R12.1)

18-May-2001

Communications Blockset

Version 2.0.1 (R12.1)

18-May-2001

MATLAB Compiler

Version 2.2 (R12.1)

30-Mar-2001

Control System Toolbox

Version 5.1 (R12.1)

18-May-2001

Data Acquisition Toolbox

Version 2.1 (R12.1)

06-Apr-2001

Database Toolbox

Version 2.2 (R12.1)

04-Jan-2001

Datafeed Toolbox

Version 1.3 (R12.1)

03-Jan-2001

Dials & Gauges Blockset

Version 1.1.1 (R12.1)

02-Feb-2001

DSP Blockset

Version 4.1 (R12.1)

18-May-2001

:
: )

282

Matlab/Simulink
Real-Time Workshop Embedded Coder Version 2.0 (R12.1) 01-Mar-2001
Filter Design Toolbox
Version 2.1 (R12.1) 01-Feb-2001
Financial Toolbox
Version 2.1.3 (R12.1) 12-Mar-2001
Financial Derivatives Toolbox
Version 1.0 (R12.1) 14-Aug-2000
Fixed-Point Blockset
Version 3.1 (R12.1) 18-May-2001
Financial Time Series Toolbox
Version 1.1 (R12.1) 01-Dec-2000
Fuzzy Logic Toolbox
Version 2.1.1 (R12.1) 18-May-2001
GARCH Toolbox
Version 1.0 (R12.1) 01-Jun-1999
System Identification Toolbox
Version 5.0.1 (R12.1) 18-May-2001
Image Processing Toolbox
Version 3.1 (R12.1) 18-May-2001
Instrument Control Toolbox
Version 1.1 (R12.1) 18-May-2001
LMI Control Toolbox
Version 1.0.7 (R12.1) 18-May-2001
Mapping Toolbox
Version 1.2 (R12.1) 22-May-2000
Motorola DSP Developer's Kit
Version 1.1 (R12.1) 01-Sep-2000
Model Predictive Control Toolbox
Version 1.0.6 (R12.1) 18-May-2001
Mu-Analysis and Synthesis Toolbox Version 3.0.6 (R12.1) 18-May-2001
Nonlinear Control Design Blockset
Version 1.1.5 (R12.1) 18-May-2001
Neural Network Toolbox
Version 4.0.1 (R12.1) 02-Feb-2001
Optimization Toolbox
Version 2.1.1 (R12.1) 18-May-2001
Partial Differential Equation Toolbox
Version 1.0.4 (R12.1) 06-Apr-2001
Simulink Performance Tools
Version 1.1 (R12.1) 18-May-2001
Power System Blockset
Version 2.2 (R12.1) 06-Apr-2001
Requirements Management Interface
Version 1.0.2 (R12.1) 30-Nov-2000
Robust Control Toolbox
Version 2.0.8 (R12.1) 18-May-2001
MATLAB Report Generator
Version 1.2 (R12.1) 01-Apr-2001
Simulink Report Generator
Version 1.2 (R12.1) 01-Apr-2001
MATLAB Runtime Server Development Kit Version 6.1 (R12.1) 18-May-2001
SB2SL (converts SystemBuild to Simu...
Signal Processing Toolbox
Version 5.1 (R12.1)
Spline Toolbox
Version 3.0 (R12.1)
Statistics Toolbox
Version 3.0 (R12.1)
Symbolic Math Toolbox
Version 2.1.2 (R12.1)
Developer's Kit for TI(tm) DSP
Version 1.1 (R12.1)
Virtual Reality Toolbox
Version 2.0 (R12.1)
Wavelet Toolbox
Version 2.1 (R12.1)
MATLAB Web Server
Version 1.2.1 (R12.1)
xPC Target
Version 1.2 (R12.1)
xPC Target Embedded Option
Version 1.2 (R12.1)

Version 2.2 (R12.1)


06-Apr-2001
13-Mar-2000
01-Sep-2000
11-Sep-2000
08-Jun-2001
06-Apr-2001
06-Apr-2001
23-Apr-2001
09-Apr-2001
09-Apr-2001

:
10-Apr-2001
:
1

9.2

DSP

283

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

Simulink
Stateflow
CDMA Reference Blockset
Communications Blockset
DSP Blockset
Motorola DSP Developers Kit
Xilinx Blockset
Altera DSP Builder
Real-Time Workshop
Developers kit for TI DSP
Real-time Windows Target
RTW Embedded Coder
Stateflow Coder
Tornado (VxWorks) Real-Time Target
Xilinxs System Generator for Simulink
Altera SignalCompiler for Simulink
xPC Target

:
:

: /

Matlab/Simulink

284

9.3

MATLAB

MATLAB MATLAB
m
m
MATLAB m

>> A=magic(3)
A=
8

>> invA=inv(A)
invA =
0.1472 -0.1444 0.0639
-0.0611 0.0222 0.1056
-0.0194 0.1889 -0.1028
>> [v,d]=eig(A)
v=
-0.5774 -0.8131 -0.3416
-0.5774 0.4714 -0.4714
-0.5774 0.3416 0.8131

d=
15.0000
0

4.8990

:
:

9
0

DSP

285

0 -4.8990

>> rankofA=rank(A)
rankofA =
3

m Welch %MATLABROOT%\toolbox\
signal\signal\pwelch.m
function varargout = pwelch(x,win,noverlap,varargin)
%PWELCH Power Spectral Density estimate via Welch's method.
% Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate,
% Pxx, of a discrete-time signal vector X using Welch's averaged,
% modified periodogram method. By default, X is divided into eight
% sections with 50% overlap, each section is windowed with a Hamming
% window and eight modified periodograms are computed and averaged.
%
% If the length of X is such that it cannot be divided exactly into
% eight sections with 50% overlap, X will be truncated accordingly.
%
% Pxx is the distribution of power per unit frequency. For real signals,
% PWELCH returns the one-sided PSD by default; for complex signals, it
% returns the two-sided PSD. Note that a one-sided PSD contains the
% total power of the input signal.
%
% Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into
% overlapping sections of length equal to the length of WINDOW, and then
% windows each section with the vector specified in WINDOW. If WINDOW is
% an integer, X is divided into sections of length equal to that integer
% value, and a Hamming window of equal length is used. If the length of
% X is such that it cannot be divided exactly into integer number of
% sections with 50% overlap, X will be truncated accordingly. If WINDOW
% is omitted or specified as empty, a default window is used to obtain
% eight sections of X.
%
% Pxx = PWELCH(X,WINDOW,NOVERLAP) uses NOVERLAP samples of overlap from
% section to section. NOVERLAP must be an integer smaller than the WINDOW
% if WINDOW is an integer. NOVERLAP must be an integer smaller than the

:
:

: function
varargout =
pwelch(x,win,noverlap,varargi
n)
%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 twosided PSD. Note that a onesided PSD
% contains the total power of
the input signal.
%
% Pxx =
PWELCH(X,WINDOW),
when WINDOW is a vector,
divides X into
% overlapping sections of
length equal to the length of
WINDOW, and
% then windows each section
with the vector specified in
WINDOW. If
% WINDOW is an integer,
X
... [1]

Matlab/Simulink

286

% length of WINDOW if WINDOW is a vector. If NOVERLAP is omitted or


% specified as empty, the default value is used to obtain a 50% overlap.
%
% [Pxx,W] = PWELCH(X,WINDOW,NOVERLAP,NFFT) specifies the number of FFT
% points used to calculate the PSD estimate. For real X, Pxx has length
% (NFFT/2+1) if NFFT is even, and (NFFT+1)/2 if NFFT is odd. For complex
% X, Pxx always has length NFFT. If NFFT is specified as empty, the
% default NFFT -the maximum of 256 or the next power of two
% greater than the length of each section of X- is used.
%
% W is the vector of normalized frequencies at which the PSD is
% estimated. W has units of rad/sample. For real signals, W spans the
% interval [0,Pi] when NFFT is even and [0,Pi) when NFFT is odd. For
% complex signals, W always spans the interval [0,2*Pi).
%
% [Pxx,F] = PWELCH(X,WINDOW,NOVERLAP,NFFT,Fs) returns a PSD computed as
% a function of physical frequency (Hz). Fs is the sampling frequency
% specified in Hz. If Fs is empty, it defaults to 1 Hz.
%
% F is the vector of frequencies at which the PSD is estimated and has
% units of Hz. For real signals, F spans the interval [0,Fs/2] when NFFT
% is even and [0,Fs/2) when NFFT is odd. For complex signals, F always
% spans the interval [0,Fs).
%
% [...] = PWELCH(...,'twosided') returns a two-sided PSD of a real signal
% X. In this case, Pxx will have length NFFT and will be computed over
% the interval [0,2*Pi) if Fs is not specified and over the interval
% [0,Fs) if Fs is specified. Alternatively, the string 'twosided' can be
% replaced with the string 'onesided' for a real signal X. This would
% result in the default behavior. The string 'twosided' or 'onesided'
% may be placed in any position in the input argument list after NOVERLAP.
%
% PWELCH(...) with no output arguments by default plots the PSD
% estimate in dB per unit frequency in the current figure window.
%
% EXAMPLE:
%

Fs = 1000; t = 0:1/Fs:.296;

x = cos(2*pi*t*200)+randn(size(t)); % A cosine of 200Hz plus noise

pwelch(x,[],[],[],Fs,'twosided'); % Uses default window, overlap & NFFT.

%
% See also PERIODOGRAM, PCOV, PMCOV, PBURG, PYULEAR, PEIG, PMTM, PMUSIC
% and PSDPLOT.

DSP

% Author(s): R. Losada
% Copyright 1988-2001 The MathWorks, Inc.
% $Revision: 1.27 $ $Date: 2001/04/02 20:21:06 $
% References:
%

[1] Petre Stoica and Randolph Moses, Introduction To Spectral

%
%

Analysis, Prentice-Hall, 1997, pg. 15


[2] Monson Hayes, Statistical Digital Signal Processing and

Modeling, John Wiley & Sons, 1996.

error(nargchk(1,6,nargin));
error(nargoutchk(0,2,nargout));
x = x(:);
isreal_x = isreal(x);
M = length(x);
if nargin < 3,
noverlap = [];
if nargin < 2,
win = [];
end
end
% Obtain the necessary information to segment X
[L,noverlap,win,msg] = segment_info(M,win,noverlap);
error(msg);
% Parse optional args nfft, fs
[options,msg] = pwelch_options(isreal_x,L,varargin{:});
% Compute the number of segments
k = (M-noverlap)./(L-noverlap);
% Uncomment the following line to produce a warning each time the data
% segmentation does not produce an integer number of segements.
%if fix(k) ~= k),
% warning('The number of segments is not an integer, truncating data.');
%end
k = fix(k);

287

Matlab/Simulink

288

% Compute the periodogram power spectrum of each segment and average


% always compute the twosided power spectrum, we force Fs = 1 to get
% a spectrum not a spectral density
Sxx = zeros(options.nfft,1); % Initialize
xindx = 1;
for i = 1:k,
Sxx = Sxx + periodogram(x(xindx:xindx+L-1),win,options.nfft,1,'twosided');
xindx = xindx + L - noverlap;
end
Sxx = Sxx./k; % Average the sum of the periodograms
% Generate the frequency vector in [rad/sample] at which Sxx was computed
% If Fs is not empty, w will be converted to Hz in computepsd below
w = 2.*pi.*(0:options.nfft-1)./options.nfft;

% Compute the one-sided or two-sided PSD [Power/freq].


% Also compute the corresponding one-sided or two-sided power spectrum [Power],
% the frequency at which the psd is computed and the corresponding frequency units
[Pxx,Sxx,w,units] = computepsd(Sxx,w,options.range,options.nfft,options.Fs);
if nargout==0, % Plot when no output arguments are specified
yscale = 'db';
titlestring = 'Welch PSD Estimate';
psdplot(Pxx,w,units,yscale,titlestring);
elseif nargout == 1,
varargout = {Pxx};
elseif nargout == 2,
varargout = {Pxx,w};
end
%-------------------------------------------------------------------------------------function [L,noverlap,win,msg] = segment_info(M,win,noverlap)
%SEGMENT_INFO Determine the information necessary to segment the input data.
%
% Inputs:
%

WIN

- An integer containing the length of the data to be segmented


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

DSP

% Outputs:
%

NOVERLAP - An integer containing the number of samples to overlap

- An integer containing the length of the segments

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

- Number of segments

- Length of the input data X

NOVERLAP - Desired overlap

- Length of the segments

%
% The segmentation of X is based on the fact that we always know M and two of the set
% {K,NOVERLAP,L}, hence determining the unknown quantity is trivial from the above
% formula.
% Initialize outputs
L = [];
msg = '';
% Check that noverlap is a scalar
if any(size(noverlap) > 1),
msg = 'You must specify an integer number of samples to overlap.';
return
end
if isempty(win),
% Use 8 sections, determine their length
if isempty(noverlap),
% Use 50% overlap
L = fix(M./4.5);
noverlap = fix(0.5.*L);
else
L = fix((M+7.*noverlap)./8);
end
% Use a default window

289

Matlab/Simulink

290
win = hamming(L);
else

% Determine the window and its length (equal to the length of the segments)
if ~any(size(win) <= 1) | ischar(win),
msg = 'The WINDOW argument must be a vector or a scalar.';
return
elseif length(win) > 1,
% WIN is a vector
L = length(win);
elseif length(win) == 1,
L = win;
win = hamming(win);
end
if isempty(noverlap),
% Use 50% overlap
noverlap = fix(0.5.*L);
end
end
% Do some argument validation
if L > M,
msg = 'The length of the segments cannot be greater than the length of the input signal.';
return
end
if noverlap >= L,
msg = 'The number of samples to overlap must be less than the length of the segments.';
return
end
%-----------------------------------------------------------------------------function [options,msg] = pwelch_options(isreal_x,N,varargin)
%PWELCH_OPTIONS Parse the optional inputs to the PWELCH function.
% PWELCH_OPTIONS returns a structure, OPTIONS, with following fields:
%
% options.nfft

- number of freq. points at which the psd is estimated

% options.Fs

- sampling freq. if any

% options.range

- 'onesided' or 'twosided' psd

% Generate defaults
options.nfft = max(256,2^nextpow2(N));
options.Fs = []; % Work in rad/sample

DSP

291

if isreal_x,
options.range = 'onesided';
else
options.range = 'twosided';
end
msg = '';
[options,msg] = psdoptions(isreal_x,options,varargin{:});

% [EOF] pwelch.m

>> which e2pi


D:\MATLAB6p1\toolbox\matlab\demos\e2pi.m
>> e2pi

9.1

9.1

e2pi

>> which lorenz


D:\MATLAB6p1\toolbox\matlab\demos\lorenz.m
>> help lorenz
LORENZ Plot the orbit around the Lorenz chaotic attractor.
This demo animates the integration of the
three coupled nonlinear differential equations
that define the "Lorenz Attractor", a chaotic

Matlab/Simulink

292

system first described by Edward Lorenz of


the Massachusetts Institute of Technology.
As the integration proceeds you will see a
point moving around in a curious orbit in
3-D space known as a strange attractor. The
orbit is bounded, but not periodic and not
convergent (hence the word "strange").
Use the "Start" and "Stop" buttons to control
the animation.
>> Lorenz

9.2

9.2

lorenz

>> which wrldtrv


D:\MATLAB6p1\toolbox\matlab\demos\wrldtrv.m
>> wrldtrv
>> which wrldtrv
D:\MATLAB6p1\toolbox\matlab\demos\wrldtrv.m
>> help wrldtrv
WRLDTRV Show great circle flight routes around the globe.
This demonstration illustrates the Great

DSP

293

Circle flight paths and distances between a


number of cities around the world.
Use the popup menus to select your city of
origin and your city of destination. Then by
pushing the "Fly" button, you can watch an
animation of the flight between the two cities.
The distance between the two cities is also
calculated.
Use the "W. Hemisphere" and "E. Hemisphere"
radio buttons to choose which hemisphere you
want to view.
>> wrldtrv

9.3

9.3 wrldtrv
:

9.4

Communications Toolbox

/ MATLAB

Matlab/Simulink

294

>> randint(8,8,[0 1])


ans =
1

>> Y = wgn(1, 10, 3, 75, 'linear', 'complex')


Y=
Columns 1 through 3
3.1227 - 4.2414i -14.1723 + 7.3185i 7.5766 + 8.6510i
Columns 4 through 6
17.2205 + 7.5509i -7.3374 +13.6852i 9.1004 + 7.0916i
Columns 7 through 9
13.3007 +12.6307i -16.9041 -12.7540i -15.2837 - 0.2099i
Column 10
6.0579 - 1.6622i
z

9.4 9.5

>>x = 4*(rand(1000,2)-1/2);
>>y = demodmap(x,1,1,'psk',4);
>>red = find(y==0);
>>h = scatterplot(x(red,:),1,0,'r.');

DSP

295

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

9.5 2
z

9.6

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


partition = [-1:.1:.9];

: ScaTTER Plot

Matlab/Simulink

296
codebook = [-1:.1:1];
t = [0:pi/50:2*pi];

x = sawtooth(3*t); % Original signal


% Quantize x using DPCM.
encodedx = dpcmenco(x,codebook,partition,predictor);
% Try to recover x from the modulated signal.
decodedx = dpcmdeco(encodedx,codebook,predictor);
plot(t,x,t,decodedx,'--')

9.6 DPCM
z

>> t = poly2trellis([3 3],[4 5 7;7 4 2]);


msg = [1 1 0 1 0 0 1 1];
[code1 state1]=convenc([msg(1:end/2)],t);
[code2 state2]=convenc([msg(end/2+1:end)],t,state1);
[codeA stateA]=convenc(msg,t);
>> code1
code1 =
0

>> code2
code2 =
0

DSP

297

>> codeA
codeA =
Columns 1 through 8
0

Columns 9 through 12
0
z

1
:

>> modmap('qam',16)

9.7

9.7
z

16QAM

Matlab/Simulink

298

9.5

Filter Design Toolbox

MATLAB
/Filter Design Toolbox
9.1 9.2
9.1

Filter Design Toolbox FIR

:
: 9.1
9.2

.doc

antisymmetricfir

fir

firt

latticema

Lattice MA

symmetricfir

9.2

Filter Design Toolbox IIR

df1

df1t

df2

II

df2t

II

latticeca

Lattice

latticecapc

Lattice

latticear

Lattice AR

latticearma

Lattice ARMA

statespace

: 9.1 Filter
Design Toolbox
FIR

: 9.2 Filter
Design Toolbox IIR

9.6

Image Processing Toolbox

z /
z /
z
z
z

9
z
z

DSP

299

9.7

Matlab C/C++ Math/Graphics Library

MATLAB C/C++ Math/Graphics Library C/C++


/ MATLAB /MATLAB Compiler m
C/C++C/C++
MATLAB C/C++Math Library MATLAB

9.8

Signal Processing Toolbox

MATLAB

: 9.8

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

9.8

9.8

Matlab/Simulink

300
z

/ 9.9

fdatool

:
:

>>fdatool

9.9

sptool 9.10

>>sptool

9.10 sptool

z
z

DSP

301

IIR
FIR

>> which specgramdemo


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

9.11
: 9.11

:
:
:

9.11

specgramdemo

>> help specgramdemo


SPECGRAMDEMO Spectrogram Demo
SPECGRAMDEMO(y,Fs) displays a spectrogram of signal y, assuming

a sample rate of Fs Hz. If y is specified but Fs is not,

: n

Matlab/Simulink

302

a sample rate of 1 Hz is assumed. If no input arguments


are supplied, y and Fs are taken from the default data file
"mtlb.mat."
Context menus and context-sensitive help are enabled throughout
the GUI. Explore the visualization options by right-clicking
on various GUI items including the spectrogram, the colorbar,
etc. For example, the panner may be zoomed by dragging the
mouse on the left- and right-hand edges of the highlighted
zoom region. Right-clicking the highlighted zoom area brings
up a menu for focusing in on the zoom region, and provides
a link to context help.
See also SPECGRAM, SPTOOL, FDATOOL.

9.9

Wavelet Toolbox

MATLAB

9.10

Simulink

Simulink 9.12

z /
z /
z

Simulink Simulink
Simulink
Simulink Matlab
Matlab/Simulink

DSP

303

9.12 Simulink

9.11

Stateflow

Stateflow
Matlab/Simulink Stateflow Simulink

z
z
z
z Stateflow / C
9.13 Stateflow

Matlab/Simulink

304

1
:

9.13

9.12

CDMA Reference Blockset

CDMA Reference Blockset IS-95A CDMA Simulink


9.14 9.15 9.16 IS-95A

9.14 CDMA Reference Blockset(a)

: 15

DSP

305

: 9.14
CDMA Reference Blockset(a)

: 9.14
CDMA Reference Blockset(a)

:
:

9.15 CDMA Reference Blockset(b)

: 14

Matlab/Simulink

306

9.16 %MATLABROOT%\toolbox\cdma\cdmademos\is95fwdchendtoend2.mdl

9.13

: 15

Communications Blockset

Communications Blockset Simulink


9.17
Communications Blockset
z /
z
z
z /
z
z

: 16
:
:
:

DSP

307

9.17 Communications Blockset

9.14

: 16

DSP Blockset

DSP Blockset Simulink 9.18


DSP /

9.18 DSP Blockset

: 17
:

: 17

Matlab/Simulink

308

DSP Blockset
>> demo blocksets dsp
: 18

9.19

9.19 MATLAB

: 18
: Demos

9.15 Motorola DSP Developers Kit


Motorola DSP Developers Kit Matlab/Simulink Motorola
DSP56300/56600 Motorola Suite56 DSP Simulator MEX
S- Motorola DSP Developers Kit
Motorola Suite56 DSP56300/56600 Motorola DSP Developers Kit
Motorola DSP /C Motorola Suite56 DSP
simulator Matlab/Simulink 9.20 Motorola
DSP Developers Kit Motorola DSP Blockset

:
: Developer's
:
:
:
: 19

DSP

9.20 Motorola DSP Blockset

309

: 19

>> mot_dsp563_filterdemo

9.21 9.22

: 20
: 21
:

310

Matlab/Simulink

9.21

: 20
mot_dsp563_filterdemo.mdl

9.22

: 1
: Scope

9.16

DSP

311

Xilinx Blockset

Xilinx Blockset Xilinx FPGA Simulink


Simulink Xilinx FPGA VHDL
9.23 Xilinx Blockset Costas

9.23 %MATLABROOT%\toolbox\xilinx\sysgen\examples\costas_loop\costas_tb.mdl Costas

: 22

: 22

9.17 Real-Time Workshop


Real-Time Workshop Simulink C/Ada

z
z
z S-
z C
z Ada
Real-Time Workshop 9.3

: (
: )
:
:

Matlab/Simulink

312

9.3

GRT

Static memory allocation

CMES

S-function

noninline
Any

S-functions

inlined

RTW

time

Embedded

malloc

Coder

prototyping

Tomado

S-func

Intended for production

included

TI
DSP

and Monte Carlo methods


Non real-time executable

xPC

Batch parameter tuning


Executes in hard real time

RTWin

code

RSIM

RAM/ROM usage
Intended for rapid

Ada

Optimized for min


Supports external mode

DOS

allocation
Continuous time

Real-

Dynamic memory

Real-Time Workshop

: 9.18
Developers Kit for TI DSP
Developers Kit for TI DSP
MathWorks TI

Simulink/Matlab TI
TM
eXpressDSP

Target for C6701 EVM


Link for Real-Time Data
Exchange (RTDX)
Link for Code Composer
Studio IDE

Simulink
TI DSP
: s
: C

: (

Multiple instances of one


model if no Stateflow

:
: )
: (

blocks in model

: )
: (

9.18

Developers Kit for TI DSP

: )
: (
: )

Developers Kit for TI DSP MathWorks TI


Simulink/Matlab TI eXpressDSPTM

z
z

Target for C6701 EVM


Link for Real-Time Data ExchangeRTDX

Link for Code Composer Studio IDE


Simulink TI DSP C

DSP

313

9.19 Real-Time Windows Target


Real-Time Windows Target PC RealTime Windows Target PC Simulink
Simulink

9.20

RTW Embedded Coder

RTW Embedded Coder


Embedded-C

z
z
z
z S- Simulink

9.21

Stateflow Coder

Stateflow Coder Stateflow C


>> sf_car

9.24
9.24 Build sfprj\build\sf_car\shiftlogic\src
sfprj\build\sf_car\shiftlogic\info sfprj\build\sf_car\shiftlogic\info
binfo.mat sfprj\build\sf_car\shiftlogic\src Stateflow shift_logic C

Matlab/Simulink

314

: 23

9.24 sf_car.mdl Stateflow C


sf_car_shiftlogic.h
sf_car_shiftlogic.c

: 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
sfprj\build\sf_car\shiftlogic\src
Stateflow
shift_logic C

:
:

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

#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

Matlab/Simulink

316
*/
#include "sf_car_shiftlogic.h"
#include "shift_logic.h"

#define IN_NO_ACTIVE_CHILD

(0)

#define IN_c1_s2_first

#define IN_c1_s3_fourth

#define IN_c1_s4_second

#define IN_c1_s5_third

#define IN_c1_s7_downshifting

#define IN_c1_s8_steady_state

#define IN_c1_s9_upshifting

#define TWAIT

(2)

#define event_c1_e8_DOWN

#define event_c1_e9_UP

static SFshift_logicInstanceStruct chartInstance;


void shift_logic(void);
static void c1_s1_gear_state(void);
void shift_logic(void)
{
{
/* During: shift_logic */
if(_sfEvent_sf_car_ == CALL_EVENT) {
if(chartInstance.Counters.i1<0xffU) {
chartInstance.Counters.i1++;
}
}
if(chartInstance.State.is_active_shift_logic == 0) {
/* Entry: shift_logic */
chartInstance.State.is_active_shift_logic = 1;
/* Entry: gear_state */
chartInstance.State.is_active_c1_s1_gear_state = 1;
/* Entry: first */
if(chartInstance.State.is_c1_s1_gear_state != IN_c1_s2_first) {
chartInstance.State.is_c1_s1_gear_state = IN_c1_s2_first;
gear = 1;
}
/* Entry: selection_state */
chartInstance.State.is_active_c1_s6_selection_state = 1;

DSP

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

317

Matlab/Simulink

318

/* Entry: downshifting */
chartInstance.State.is_c1_s6_selection_state =
IN_c1_s7_downshifting;
chartInstance.Counters.i1=0;
}
break;
case IN_c1_s9_upshifting:
{
/* During: upshifting */
if((_sfEvent_sf_car_ == CALL_EVENT) && (chartInstance.Counters.i1
>= (uint8_T )TWAIT) && (speed >= up_th)) {
{
int8_T previousEvent;
previousEvent = _sfEvent_sf_car_;
_sfEvent_sf_car_ = event_c1_e9_UP;
c1_s1_gear_state();
_sfEvent_sf_car_ = previousEvent;
}
/* Exit: upshifting */
/* Entry: steady_state */
chartInstance.State.is_c1_s6_selection_state =
IN_c1_s8_steady_state;
} else if(speed < up_th) {
/* Exit: upshifting */
/* Entry: steady_state */
chartInstance.State.is_c1_s6_selection_state =
IN_c1_s8_steady_state;
}
}
break;
}
}
}
}
}
}
static void c1_s1_gear_state(void)
{
{
/* During: gear_state */

DSP

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

319

Matlab/Simulink

320
/* Exit: third */
/* Entry: second */

chartInstance.State.is_c1_s1_gear_state = IN_c1_s4_second;
gear = 2;
}
break;
}
}
}
}
void initialize_shift_logic(void)
{
/* Initializing chart output data */
gear = (uint8_T)0;
/* Initialize chart's state configuration */
memset((void*)&(chartInstance.State),0,sizeof(chartInstance.State));
}

9.22

Tornado (VxWorks) Real-Time Target

Tornado(VxWorks)Real-Time Target Simulink VxWorks/Tornado

9.23

: (
: )

Xilinxs System Generator for Simulink

Xilinxs System Generator for Simulink Xilinx Blockset


Xilinx FPGA VHDL

9.24 xPC Target


xPC Target - PC PC
Matlab/Simulink/Stateflow

:
: (
: )

DSP

321

PC
9.25 9.26

9.25 xPC Target -

9.26 xPC Target - Ethernet

: 5

: 24

: 25

285:

[1]

fcr

2002-9-17 15:50:00

function varargout = pwelch(x,win,noverlap,varargin)


%PWELCH Power Spectral Density estimate via Welch's method.
% Pxx = PWELCH(X) returns the Power Spectral Density (PSD) estimate,
% Pxx, of a discrete-time signal vector X using Welch's averaged,
% modified periodogram method. By default, X is divided into eight
% sections with 50% overlap, each section is windowed with a Hamming
% window and eight modified periodograms are computed and averaged.
%
% If the length of X is such that it cannot be divided exactly into
% eight sections with 50% overlap, X will be truncated accordingly.
%
% Pxx is the distribution of power per unit frequency. For real
% signals,PWELCH returns the one-sided PSD by default; for complex
% signals, it returns the two-sided PSD. Note that a one-sided PSD
% contains the total power of the input signal.
%
% Pxx = PWELCH(X,WINDOW), when WINDOW is a vector, divides X into
% overlapping sections of length equal to the length of WINDOW, and
% then windows each section with the vector specified in WINDOW. If
% WINDOW is an integer, X is divided into sections of length equal to
% that integer value, and a Hamming window of equal length is used.
% If the length of X is such that it cannot be divided exactly into
% integer number of sections with 50% overlap, X will be truncated
% accordingly. If WINDOW is omitted or specified as empty, a default
% window is used to obtain eight sections of X.
%
% Pxx = PWELCH(X,WINDOW,NOVERLAP) uses NOVERLAP samples of overlap
% from section to section. NOVERLAP must be an integer smaller than
% the WINDOW if WINDOW is an integer. NOVERLAP must be an integer
% smaller than the length of WINDOW if WINDOW is a vector. If
% NOVERLAP is omitted or specified as empty, the default value is used
% to obtain a 50% overlap.
%
% [Pxx,W] = PWELCH(X,WINDOW,NOVERLAP,NFFT) specifies the number of FFT
% points used to calculate the PSD estimate. For real X, Pxx has
% length (NFFT/2+1) if NFFT is even, and (NFFT+1)/2 if NFFT is odd.
% For complex X, Pxx always has length NFFT. If NFFT is specified as
% empty, the default NFFT -the maximum of 256 or the next power of two
% greater than the length of each section of X- is used.
%
% W is the vector of normalized frequencies at which the PSD is
% estimated. W has units of rad/sample. For real signals, W spans
% the interval [0,Pi] when NFFT is even and [0,Pi] when NFFT is odd.
% For complex signals, W always spans the interval [0,2*Pi).
%
% [Pxx,F] = PWELCH(X,WINDOW,NOVERLAP,NFFT,Fs) returns a PSD computed
% as a function of physical frequency (Hz). Fs is the sampling
% frequency specified in Hz. If Fs is empty, it defaults to 1 Hz.

%
% F is the vector of frequencies at which the PSD is estimated and has
% units of Hz. For real signals, F spans the interval [0,Fs/2] when
% NFFT is even and [0,Fs/2] when NFFT is odd. For complex signals, F
% always spans the interval [0,Fs).
%
% [...] = PWELCH(...,'twosided') returns a two-sided PSD of a real
% signal X. In this case, Pxx will have length NFFT and will be
% computed over the interval [0,2*Pi] if Fs is not specified and over
% the interval [0,Fs] if Fs is specified. Alternatively, the string
% 'twosided' can be replaced with the string 'onesided' for a real
% signal X. This would result in the default behavior. The string
% 'twosided' or 'onesided'may be placed in any position in the input
% argument list after NOVERLAP.
%
% PWELCH(...) with no output arguments by default plots the PSD
% estimate in dB per unit frequency in the current figure window.
%
% EXAMPLE:
%

Fs = 1000; t = 0:1/Fs:.296;

x = cos(2*pi*t*200)+randn(size(t)); % A cosine of 200Hz plus

noise pwelch(x,[],[],[],Fs,'twosided'); % Uses default window,

overlap & NFFT.

%
% See also PERIODOGRAM, PCOV, PMCOV, PBURG, PYULEAR, PEIG, PMTM,
% PMUSIC and PSDPLOT.
% Author(s): R. Losada
% Copyright 1988-2001 The MathWorks, Inc.
% $Revision: 1.27 $ $Date: 2001/04/02 20:21:06 $
% References:
%

[1] Petre Stoica and Randolph Moses, Introduction To Spectral

%
%

Analysis, Prentice-Hall, 1997, pg. 15


[2] Monson Hayes, Statistical Digital Signal Processing and

Modeling, John Wiley & Sons, 1996.

error(nargchk(1,6,nargin));
error(nargoutchk(0,2,nargout));
x = x(:);
isreal_x = isreal(x);
M = length(x);
if nargin < 3,
noverlap = [];
if nargin < 2,
win = [];
end

end
% Obtain the necessary information to segment X
[L,noverlap,win,msg] = segment_info(M,win,noverlap);
error(msg);
% Parse optional args nfft, fs
[options,msg] = pwelch_options(isreal_x,L,varargin{:});
% Compute the number of segments
k = (M-noverlap)./(L-noverlap);
% Uncomment the following line to produce a warning each time the data
% segmentation does not produce an integer number of segements.
%if fix(k) ~= k),
% warning('The number of segments is not an integer, truncating
% data.');
%end
k = fix(k);
% Compute the periodogram power spectrum of each segment and average
% always compute the twosided power spectrum, we force Fs = 1 to get
% a spectrum not a spectral density
Sxx = zeros(options.nfft,1); % Initialize
xindx = 1;
for i = 1:k,
Sxx = Sxx + periodogram(x(xindx:xindx+L-1),win,options.nfft,1,
'twosided');
xindx = xindx + L - noverlap;
end
Sxx = Sxx./k; % Average the sum of the periodograms
% Generate the frequency vector in [rad/sample] at which Sxx was
% computed If Fs is not empty, w will be converted to Hz in computepsd below
w = 2.*pi.*(0:options.nfft-1)./options.nfft;

% Compute the one-sided or two-sided PSD [Power/freq].


% Also compute the corresponding one-sided or two-sided power spectrum
% [Power],the frequency at which the psd is computed and the
corresponding frequency units [Pxx,Sxx,w,units] = computepsd(Sxx,w,
options.range,options.nfft,options.Fs);
if nargout==0, % Plot when no output arguments are specified
yscale = 'db';
titlestring = 'Welch PSD Estimate';
psdplot(Pxx,w,units,yscale,titlestring);
elseif nargout == 1,

varargout = {Pxx};
elseif nargout == 2,
varargout = {Pxx,w};
end
%---------------------------------------------------------------------function [L,noverlap,win,msg] = segment_info(M,win,noverlap)
%SEGMENT_INFO Determine the information necessary to segment the input
data.
%
% Inputs:
% M - An integer containing the length of the data to be segmented
% N - A scalar or vector containing the length of the window or the
% window respectively (Note that the length of the window determines
the length of the segments)
%

NOVERLAP - An integer containing the number of samples to overlap

(may be empty)
%
% Outputs:
% L

- An integer containing the length of the segments

% NOVERLAP - An integer containing the number of samples to overlap


% WIN - A vector containing the window to be applied to each section
% MSG - A string containing possible error messages
%
%
% The key to this function is the following equation:
%
%

K = (M-NOVERLAP)/(L-NOVERLAP)

%
% where
%
%

- Number of segments

- Length of the input data X

NOVERLAP - Desired overlap

- Length of the segments

%
% The segmentation of X is based on the fact that we always know M and
% two of the set {K,NOVERLAP,L}, hence determining the unknown
% quantity is trivial from the above formula.
% Initialize outputs
L = [];
msg = '';
% Check that noverlap is a scalar
if any(size(noverlap) > 1),
msg = 'You must specify an integer number of samples to overlap.';
return
end

if isempty(win),
% Use 8 sections, determine their length
if isempty(noverlap),
% Use 50% overlap
L = fix(M./4.5);
noverlap = fix(0.5.*L);
else
L = fix((M+7.*noverlap)./8);
end
% Use a default window
win = hamming(L);
else
% Determine the window and its length (equal to the length of the
segments)
if ~any(size(win) <= 1) | ischar(win),
msg = 'The WINDOW argument must be a vector or a scalar.';
return
elseif length(win) > 1,
% WIN is a vector
L = length(win);
elseif length(win) == 1,
L = win;
win = hamming(win);
end
if isempty(noverlap),
% Use 50% overlap
noverlap = fix(0.5.*L);
end
end
% Do some argument validation
if L > M,
msg = 'The length of the segments cannot be greater than the length
of the input signal.';
return
end
if noverlap >= L,
msg = 'The number of samples to overlap must be less than the length
of the segments.';
return
end
%---------------------------------------------------------------------function [options,msg] = pwelch_options(isreal_x,N,varargin)
%PWELCH_OPTIONS Parse the optional inputs to the PWELCH function.
% PWELCH_OPTIONS returns a structure, OPTIONS, with following fields:
%

% options.nfft - number of freq. points at which the psd is estimated


% options.Fs
% options.range

- sampling freq. if any


- 'onesided' or 'twosided' psd

% Generate defaults
options.nfft = max(256,2^nextpow2(N));
options.Fs = []; % Work in rad/sample
if isreal_x,
options.range = 'onesided';
else
options.range = 'twosided';
end
msg = '';
[options,msg] = psdoptions(isreal_x,options,varargin{:});

% [EOF] pwelch.m

: A

:
: function
commsmtr(varargin)

commsmtr.mdisphelp.m prcsofcmdline.m
>mcc B sgl commsmtr.m

commsmtr.exe
>> !commsmtr sui4bpsk.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p 0.25
**********system parameter for current simulation**********
the sampling frequency: Fs=5 (MHz)
the ratio of energy of each bit to noise power spectral density: Eb/N0= 0 5 10 15 20 25 30 35 40
the channel mode:
SUI-4 + AWGN
the mapping method:
BPSK
the size of IFFT: 256
the total bits of transmitted data: 10240
the size of cyclic prefix: 64
the simulation results will be saved in file sui4bpsk.mat
>> !commsmtr /?
A certain communications system simulator console application
commsmtr [filename] [/S Fs] [/R Eb_N0] [/C channel_model]
[/M mapping_mode] [/F points_in_a_IFFT] [/T total_transmitted_data_bits]

0 - AWGN

%% defining default system


parameters
commSys.Fs=5000000; %
sampling frquency=5MHz
commSys.Eb_N0=0:5:40; %
the ratio of Energy of each bit
to noise
power spectral density
commSys.channelType=4; %
SUI-channel type
commSys.channelMode=strvca
t('AWGN',... % channel type
'SUI-1
+ [1]
...

1 - SUI-1 + AWGN

2 - SUI-2 + AWGN

[/P cyclic_prefix_length]
filename

the Matlab MAT-file name in which the simulation results


will be saved.

Fs
Eb_N0

% COMMSMTR - simulator
console application for a
certain communications
system
% Please compile it into
windows console application
commsmtr.exe
% as the following MATLAB
commands:
% >>mex -setup
% >>mbuild -setup
% >>mcc -B sgl commsmtr.m
% then run it as a executable
program in Windows console,
just like
% >commsmtr /?
% >commsmtr sui416qam.mat
/s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t
10000 /p
0.25
% and so on.
%
% Note!!!
% This example is just for
explaining how to input
multiple command line
parameters
% not for simulation.
%
% author: YongchunChen
% date: 2002/02/08
% version: 1.0

the Sampling frequency of transmitted data(MHz).


the ratio of energy of each bit to noise power spectral
density.

channel_model the channel mode

323

: A

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

:
: A.

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:5:20 /c 4 /m 2 /F 256 /t 65536 /p [0.2,0.25]

:
A.1 DOS
commsmtr.exe

If you want to break the running of this program, please press Ctrl+C.

: (

commsmtr data.mat /s 5 /r 0:1:20 /c 4 /m 2 /F [256,512] /t 65536 /p 0.25

Windows 98/2000 DOS


1
Windows 98/2000 MATLAB
A commsmtr.exe
1. mcc B sgl commsmtr.m commsmtr.exe
bin A C:\applications
2. %MATLABROOT%\extern\lib\win32\mglinstaller.exe A
C:\matlablib Matlab
C:\matlablib\bin\win32
3. A C:\matlablib\bin\win32 PATH

: )
: ,
:

:
:
: ,
: ,

324

Matlab/Simulink

A MATLAB C:\matlablib\bin\win32
%MATLABROOT%\bin\win32
4. A DOS commsmtr.exe

: (
:
:
: )

1 DOS commsmtr.exe

322:

[1]

function commsmtr(varargin)
% COMMSMTR - simulator console application for a certain communications
system
% Please compile it into windows console application commsmtr.exe
% as the following MATLAB commands:
% >>mex -setup
% >>mbuild -setup
% >>mcc -B sgl commsmtr.m
% then run it as a executable program in Windows console, just like
% >commsmtr /?
% >commsmtr sui416qam.mat /s 5 /r 0:5:40 /c 4 /m 1 /f 256 /t 10000 /p
0.25
% and so on.
%
% Note!!!
% This example is just for explaining how to input multiple command line
parameters
% not for simulation.
%
% author: YongchunChen
% date: 2002/02/08
% version: 1.0
%% defining default system parameters
commSys.Fs=5000000; % sampling frquency=5MHz
commSys.Eb_N0=0:5:40; % the ratio of Energy of each bit to noise
power spectral density
commSys.channelType=4; % SUI-channel type
commSys.channelMode=strvcat('AWGN',... % channel type
'SUI-1 + AWGN',...
'SUI-2 + AWGN',...
'SUI-3 + AWGN',...
'SUI-4 + AWGN',...
'SUI-5 + AWGN',...
'SUI-6 + AWGN',...
'Jakes + AWGN');
commSys.ifftSize=256; % IFFT size
commSys.wordSize=1; % word size corresponding to modulation method
% 1 BPSK <==>2QAM
% 2 QPSK <==>4QAM
% 4 16QAM
% 6 64QAM
commSys.energyNormalized=[1,1/sqrt(2),1,1/sqrt(10),1,1/sqrt(42)];
commSys.mappingMode=strvcat('BPSK',... % mapping type
'QPSK ',...
' ',...
'16QAM',...

2002-9-14 9:26:00

' ',...
'64QAM');
% total transmitted data bits including data used to estimate channel
commSys.totalBits=commSys.ifftSize*commSys.wordSize*256;
commSys.cpLenRatio=1/4; % cyclic prefix length in unit:(ifftSize)
% length of CP equal to 1/4 of IFFT size
commSys.cpLen=round(commSys.ifftSize*commSys.cpLenRatio);
commSys.dataFileName='commsimulation.mat';
commSys.thirdDemension=0; % nothing as the third demension
% preamble symbol column used to estimate channel, here we assume it as 1
commSys.estimatingColumn=1;
%% end of definding default system parameters
% processing command line parameters
paramLen=length(varargin);
% display helping text for the simulator console application
if paramLen==1&strmatch('/?',varargin)
disphelp;
return;
end
if paramLen~=0
[cmdLineErr,commSys]=prcsOfCmdLine(commSys,varargin,paramLen);
if cmdLineErr
return;
end
end
% display system parameters
disp('**********system parameter for current simulation**********');
disp(['the sampling frequency: Fs=',num2str(commSys.Fs/1000000),'
(MHz)']);
disp(['the ratio of energy of each bit to noise power spectral density:
Eb/N0=', ...
num2str(commSys.Eb_N0)]);
disp('the channel mode:');
disp(cat(2,zeros(length(commSys.channelType),17),commSys.channelMode( ...
commSys.channelType+1,:)));
disp('the mapping method:');
disp(cat(2,zeros(length(commSys.wordSize),17),commSys.mappingMode( ...
commSys.wordSize,:)));
disp(['the size of IFFT: ',num2str(commSys.ifftSize)]);
disp(['the total bits of transmitted data: ',num2str (commSys.totalBits)]);
disp(['the size of cyclic prefix: ',num2str(commSys.cpLen)]);
disp(['the simulation results will be saved in file ',commSys.dataFileName]);
disp(' ');
% the processing is omitted
% ......
%

%%% end of simulator console application

disphelp.m
function disphelp
% DISPHELP - display helping text for communications simulator console
application
disp(strvcat( ...
'communications simulator console application', ...
' ',...
'commsmtr [filename] [/S Fs] [/R Eb_N0] [/C channel_model]',...
'[/M mapping_mode] [/F points_in_a_IFFT] [/T total_transmitted_
data_bits]',...
'[/P cyclic_prefix_length]',...
' ',...
'filename

the Matlab MAT-file name in which the simulation


results',...

'

will be saved.',...

'Fs
'Eb_N0
'

the Sampling frequency of transmitted data(MHz).',...


the ratio of energy of each bit to noise power
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,',...

spectral',...

'points_in_a_IFFT and cyclic_prefix_length can be a scalar or an


array,',...
'but only one of them can be an array at the same time.', ...
'The following examples are all correct using method of
commsmtr:', ...
'commsmtr /?', ...
'commsmtr', ...
'commsmtr data.mat /s [3,5] /r 0:5:40 /c 4 /m 6 /F 256 /t 65536 /p
0.25', ...
'commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m [1,2,4,6] /F 256 /t 65536
/p 0.25', ...
'commsmtr data.mat /s 5 /r 0:5:40 /c 1:4 /m 1 /F 256 /t 65536
/p 0.25', ...
'commsmtr data.mat /s 5 /r 0:5:40 /c 4 /m 1 /F 256 /t 65536
/p 0.25', ...
'commsmtr data.mat /s 5 /r 0:1:20 /c 4 /m 2 /F [256,512] /t 65536
/p 0.25', ...
'commsmtr data.mat /s 5 /r 0:5:20 /c 4 /m 2 /F 256 /t 65536
/p [0.2,0.25]', ...
'If you want to break the running of this program, please press
Ctrl+C.' ...
));

prcsofcmdline.m
function [cmdLineErr, commSysNew]=prcsofcmdline(commSysDefault,
varargin,paramLen)
% PRCSOFCMDLINE - processing command line parameters
commSysNew=commSysDefault;
cmdLineErr=0;
cmdLine=lower(varargin);
k=1;
while k<=paramLen % beginning of while
if findstr('.mat',cmdLine{k})~=[] % beginning of if
FID=fopen(cmdLine{k},'w');
if FID~=-1
commSysNew.dataFileName=cmdLine{k};
fclose(FID);
k=k+1;
else
disp('Argument filename error! The filename should be *.mat,
such as data.mat, file1.mat and so on.');
cmdLineErr=1;
end
else % else of if
switch cmdLine{k}
case '/s'

if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a
sampling frequency
if temp~=-1&isnumeric(temp)
commSysNew.Fs=temp*1000000;
k=k+2;
else
disp('Argument Fs! The Fs should be a positive
scalar or array.');
cmdLineErr=1;
end
else
disp('Argument Fs! The Fs should be a positive scalar or
array.');
cmdLineErr=1;
end
case '/r'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a Eb/N0
if temp~=-1&isnumeric(temp)
commSysNew.Eb_N0=temp;
k=k+2;
else
disp('Argument Eb_N0 error! The Eb_N0 should be a
positive scalar or array.');
cmdLineErr=1;
end
else
disp('Argument Eb_N0 error! The Eb_N0 should be a )
positive scalar or array.');
cmdLineErr=1;
end
case '/c'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a channel
type
if temp~=-1&isnumeric(temp)
commSysNew.channelType=temp;
k=k+2;
else
disp('Argument channel_model error! The channel_model is
presented by a integral scalar or array between 0-7.');
cmdLineErr=1;
end
else
disp('Argument channel_model error! The channel_model is
presented by a integral scalar or array between 0-7.');
cmdLineErr=1;
end

case '/m'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a mapping
mode
if temp~=-1&isnumeric(temp)
commSysNew.wordSize=temp;
k=k+2;
else
disp('Argument mapping_mode error! The mapping_mode is presented by a
integral scalar or array including 1,2,4 or 6.');
cmdLineErr=1;
end
else
disp('Argument mapping_mode error! The mapping_mode is presented by a
integral scalar or array including 1,2,4 or 6.');
cmdLineErr=1;
end
case '/f'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a IFFT
size
if temp~=-1&isnumeric(temp)
commSysNew.ifftSize=temp;
k=k+2;
else
disp('Argument points_in_a_IFFT IFFT size error! The points_in_a_IFFT
should be a positive integral scalar or array.');
cmdLineErr=1;
end
else
disp('Argument points_in_a_IFFT IFFT size error! The points_in_a_IFFT
should be a positive integral scalar or array.');
cmdLineErr=1;
end
case '/t'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a total
transmitted bits
if temp~=-1&isnumeric(temp)
commSysNew.totalBits=temp;
k=k+2;
if length(commSysNew.totalBits)>1|commSysNew.totalBits < 1
disp('Argument total_transmitted_data_bits error! The total_transmitted_
data_bits should be a positive integral scalar.');
cmdLineErr=1;
end
else
disp('Argument total_transmitted_data_bits error! The total_transmitted_
data_bits should be a positive integral scalar.');

cmdLineErr=1;
end
else
disp('Argument total_transmitted_data_bits error! The total_transmitted_
data_bits should be a positive integral scalar.');
cmdLineErr=1;
end
case '/p'
if k+1<=paramLen
temp=eval(cmdLine{k+1},'-1'); % -1 can not be a cyclic
prefix length
if temp~=-1&isnumeric(temp)
commSysNew.cpLenRatio=temp;
if max(commSysNew.cpLenRatio)> 1|
min(commSysNew.cpLenRatio)<0
disp('Argument cyclic_prefix_length error! The cyclic_prefix_length
should be a numeric scalar or array between 0.0-1.0.');
cmdLineErr=1;
end
k=k+2;
else
disp('Argument cyclic_prefix_length error! The cyclic_prefix_length
should be a numeric scalar or array between 0.0-1.0.');
cmdLineErr=1;
end
else
disp('Argument cyclic_prefix_length error! The cyclic_prefix_length
should be a numeric scalar or array between 0.0-1.0.');
cmdLineErr=1;
end
otherwise
disp('Command Line error!');
cmdLineErr=1;
end
end % end of if
if cmdLineErr
disphelp;
return;
end
end % end of while
% check if the input parameters is correct
% .....
%
temp=commSysNew.ifftSize*commSysNew.wordSize;
LstComMult=1;
for i=1:length(temp)
LstComMult=lcm(LstComMult,temp(i));

end
commSysNew.totalBits=max(ceil(commSysNew.totalBits/LstComMult),1)*LstCom
Mult;
commSysNew.cpLen=ceil(max(commSysNew.ifftSize)*commSysNew.cpLenRatio);

6
7


8
25
610
10
9
DOS
Windows
OS/2
Macintosh
Unix
Linux
10

11 PC

12 CD-ROM

(E-mailthjd@thjd.com.cn)
Matlab/Simulink
100084
01062791976
01062788903
www.thjd.com.cn
15%

You might also like