matlab/simulink. preview of the tutorial introduction to matlab/simulink introduction to...

51
MATLAB/SimuLink MATLAB/SimuLink

Upload: ophelia-white

Post on 31-Dec-2015

541 views

Category:

Documents


30 download

TRANSCRIPT

MATLAB/SimuLinkMATLAB/SimuLink

Preview of The TutorialPreview of The Tutorial

Introduction to MATLAB/SimuLinkIntroduction to MATLAB/SimuLink MATLABMATLAB

• Programming in MATLABProgramming in MATLAB• MATLAB CompilerMATLAB Compiler• Some useful toolboxes in MATHLABSome useful toolboxes in MATHLAB

SimuLinkSimuLink• Block diagram model and mathematical Block diagram model and mathematical

models to depict dynamic systemmodels to depict dynamic system• Work with blocks and signalsWork with blocks and signals• Run and debugRun and debug

Preview of The TutorialPreview of The Tutorial

IntroductionIntroduction

What is MATLAB? What is MATLAB? • a high-performance language for a high-performance language for

technical computingtechnical computing• A programmer-friendly IDE supporting A programmer-friendly IDE supporting

mathematical notationmathematical notation• Libraries to support matrix software Libraries to support matrix software

developmentdevelopment• Containing useful application-specific Containing useful application-specific

toolboxtoolbox

IntroductionIntroduction

Where to use MATLABWhere to use MATLAB• Math and computation Math and computation • Algorithm development Algorithm development • Data acquisition Data acquisition • Modeling, simulation, and prototyping Modeling, simulation, and prototyping • Data analysis, exploration, and visualizationData analysis, exploration, and visualization• Scientific and engineering graphicsScientific and engineering graphics• Application development, including graphical Application development, including graphical

user interface building user interface building

IntroductionIntroduction

MATLAB system:MATLAB system:• Integrative Development Environment (IDE)Integrative Development Environment (IDE)• MATLAB Mathematical Function LibraryMATLAB Mathematical Function Library

Including Bassel functions and fast Fourier Including Bassel functions and fast Fourier TransformationTransformation

• MATLAB LanguageMATLAB Language high-level matrix/array language high-level matrix/array language object-orientedobject-oriented

• GraphicsGraphics display vectors and matrices as graphsdisplay vectors and matrices as graphs

• APIAPI C/Fortran program can interact with MATHLABC/Fortran program can interact with MATHLAB

Introduction--DesktopIntroduction--Desktop

Introduction--DesktopIntroduction--Desktop

Command WindowCommand Window• enter variablesenter variables• run functions/M-files run functions/M-files

Command HistoryCommand History• View statementsView statements• Save: Save:

diary('filename')diary('filename')

Introduction -- DesktopIntroduction -- Desktop

Editor/DebuggerEditor/Debugger

Introduction – Import/ExportIntroduction – Import/Export

Text Data Text Data • ASCIIASCII

Binary DataBinary Data• images, sounds, and other information. images, sounds, and other information.

Hierarchical Data Format Hierarchical Data Format • Scientific dataScientific data

Low-level File I/OLow-level File I/O• C-styleC-style

Introduction--MathematicsIntroduction--Mathematics

Matrix and Linear AlgebraMatrix and Linear Algebra Polynomial and InterpolationPolynomial and Interpolation Data analysis and StatisticsData analysis and Statistics FunctionFunction Differential EquationDifferential Equation Sparse MatricsSparse Matrics

Matrix and Linear AlgebraMatrix and Linear Algebra CreationCreation

• B = magic(3)B = magic(3)B = B = 8 8 1 1 66

33 55 7744 99 22

• C = fix(10*rand(3,2))C = fix(10*rand(3,2))C = C = 9 49 4

2 82 86 76 7

• column vectorcolumn vector u = [3; 1; 4] u = [3; 1; 4]

u=u= 334411

v = [2 0 -1]v = [2 0 -1]V=V= 22 00 -1-1

Matrix and Linear AlgebraMatrix and Linear Algebra

Addition and SubtractionAddition and Subtraction Vector Products and TransposeVector Products and Transpose Matrix MultiplicationMatrix Multiplication The Identity MatrixThe Identity Matrix

• eye(m,n): an m-by-n rectangular identity eye(m,n): an m-by-n rectangular identity matrixmatrix

ComputationComputation

X = A\B: X = A\B: • Denotes the solution to the matrix Denotes the solution to the matrix

equation AX = B.equation AX = B. X = B/AX = B/A

• Denotes the solution to the matrix Denotes the solution to the matrix equation XA = B.equation XA = B.

Example: Over determined SystemExample: Over determined System

Enter:Enter:• t = [0 .3 .8 1.1 1.6 2.3]';t = [0 .3 .8 1.1 1.6 2.3]';• y = [.82 .72 .63 .60 .55 .50]';y = [.82 .72 .63 .60 .55 .50]';

Try modeling the data with a Try modeling the data with a decaying exponential functionsdecaying exponential functions

Example: Over determined SystemExample: Over determined System

Minimize sum of squares of Minimize sum of squares of deviations of datadeviations of data

E = [ones(size(t)) exp(-t)]E = [ones(size(t)) exp(-t)] E =E =1.0000 1.00001.0000 1.0000

1.0000 0.74081.0000 0.7408 1.0000 0.44931.0000 0.4493

1.0000 0.33291.0000 0.3329 1.0000 0.20191.0000 0.2019 1.0000 0.10031.0000 0.1003

c = E\yc = E\yc =[0.4760, 0.3413]’ c =[0.4760, 0.3413]’ y(t)=0.4760+0.3413 exp(-t)y(t)=0.4760+0.3413 exp(-t)

PolynomialPolynomial Function Summary FunctionDescriptionFunction Summary FunctionDescription

convconv Multiply polynomialsMultiply polynomialsdeconvdeconv Divide polynomialsDivide polynomialspolypoly Polynomial with specified rootsPolynomial with specified rootspolyderpolyder Polynomial derivativePolynomial derivativepolyfitpolyfit Polynomial curve fittingPolynomial curve fittingpolyvalpolyval Polynomial evaluationPolynomial evaluationpolyvalmpolyvalm Matrix polynomial evaluationMatrix polynomial evaluationresidueresidue Partial-fraction expansion (residues)Partial-fraction expansion (residues)rootsroots Find polynomial rootsFind polynomial roots

Polynomial RepresentationPolynomial Representation

p(x)=xp(x)=x33-2x-5-2x-5 p = [1 0 -2 -5]p = [1 0 -2 -5]

Data Analysis and StatisticsData Analysis and Statistics

Fast Fourier Transform Fast Fourier Transform For length N input sequence x, the DFT is For length N input sequence x, the DFT is

a length N vector, X.fft and ifft a length N vector, X.fft and ifft implement the relationshipsimplement the relationships

Fast Fourier TransformFast Fourier Transform

Fast Fourier Transform (FFT)Fast Fourier Transform (FFT)

FFT of a column vector FFT of a column vector • x = [4 3 7 -9 1 0 0 0]' x = [4 3 7 -9 1 0 0 0]'

y = fft(x)y = fft(x) y = y =

6.00006.000011.4853 - 2.7574i11.4853 - 2.7574i-2.0000 -12.0000i-2.0000 -12.0000i-5.4853 +11.2426i-5.4853 +11.2426i18.000018.0000-5.4853 -11.2426i-5.4853 -11.2426i-2.0000 +12.0000i-2.0000 +12.0000i11.4853 + 2.7574i11.4853 + 2.7574i

MATLAB Compiler—V3.0MATLAB Compiler—V3.0

Input: M-filesInput: M-files Output: C/C++ source code or P-codeOutput: C/C++ source code or P-code

• C source code for building MEX-filesC source code for building MEX-files• stand-alone applicationsstand-alone applications• C code S-functions for use with SimulinkC code S-functions for use with Simulink• C shared libraries(DLL stdlib)C shared libraries(DLL stdlib)• Excel compatible plug-insExcel compatible plug-ins• COM (Component Object Model)COM (Component Object Model)

MATLAB Compiler includes MATLAB C/C++ MATLAB Compiler includes MATLAB C/C++ Math and Graphics Libraries. Math and Graphics Libraries.

MATLAB CompilerMATLAB Compiler

MATLAB CompilerMATLAB CompilerTable 1-1: Compiler Wrappers and Targets

Wrapper File

Target -W Setting

Main Stand-alone C or C++ program

-W main

MEX MATLAB C MEX-file

-W mex

Library C shared library or C++ static library

-W lib:libname

Simulink S-function

Simulink C MEX-file

-W simulink

COM COM object -W com:<componentname>[,<classname>[,<major>.<minor>]] -W comhg:<componentname>[,<classname>[,<major>.<minor>]]

Excel Excel Plug-in -W

MATLAB CompilerMATLAB Compiler

What is M-file?What is M-file?function f = fact(n) function f = fact(n)

%Function definition line%Function definition line

%FACT Factorial.%FACT Factorial. %H1 line%H1 line

%FACT(N) returns the factorial of N, H!%FACT(N) returns the factorial of N, H! %Help %Help texttext

%usually denoted by N! %usually denoted by N!

%Put simply, FACT(N) is PROD(1:N).%Put simply, FACT(N) is PROD(1:N).

f = prod(1:n);       f = prod(1:n);       % Function body% Function body

Use of CompilerUse of Compiler

Develop MEX-fileDevelop MEX-file

Stand-Alone ApplicationStand-Alone Application

Mix M-file and C codeMix M-file and C code #include <stdio.h> #include <math.h> #include "matlab.h" /* Prototype for mlfMrank */ extern mxArray *mlfMrank( mxArray * ); main( int argc, char **argv ){ mxArray *N; /* Matrix containing n. */ mxArray *R; /* Result matrix. */ int n; /* Integer parameter from command line. */ /* Get any command line parameter. */ if (argc >= 2) { n = atoi(argv[1]); } else { n = 12; } PkgInitialize(); /* Initialize the library of M-

Functions */ /* Create a 1-by-1 matrix containing n. */ N = mlfScalar(n); /* Call mlfMrank, the compiled version of mrank.m. */ R = mlfMrank(N); /* Print the results. */ mlfPrintMatrix(R); /* Free the matrices allocated during this computation.

*/ mxDestroyArray(N); mxDestroyArray(R); PkgTerminate(); /* Terminate the library of M-

functions */ }

M-File ProgrammingM-File Programming

Similar to C++ programmingSimilar to C++ programming• Data types, fuctions, control flow, Data types, fuctions, control flow,

operators, timer, string, array, structure, operators, timer, string, array, structure, objects, class, overloading, inheritance…objects, class, overloading, inheritance…

Function handleFunction handle• fhandle = @humps fhandle = @humps

M-File ProgrammingM-File Programming

MATLAB Data HierarchyMATLAB Data Hierarchy

M-File ProgrammingM-File Programming

Some particular featuresSome particular features• cell arraycell array

M-File ProgrammingM-File Programming

Some particular featuresSome particular features• Class Class

ConstructorConstructor DisplayDisplay Accessor (get and set)Accessor (get and set) Subsref, subasgnSubsref, subasgn EndEnd SubsindexSubsindex Converters (“double” “char”)Converters (“double” “char”)

M-File ProgrammingM-File Programming

Some particular featuresSome particular featuresclassclass

Create object or return class of objectCreate object or return class of object• SyntaxSyntax

str=class(object) str=class(object)

obj=class(s,'class_name') obj=class(s,'class_name')

obj=class(s,'class_name',parent1,parent2...) obj=class(s,'class_name',parent1,parent2...)

obj=class(struct([]),'class_name',parent1,pareobj=class(struct([]),'class_name',parent1,parent2...)nt2...)

M-File ProgrammingM-File Programming

Some particular featuresSome particular featuresInheritanceInheritance

ToolboxToolbox Communications ToolboxCommunications Toolbox Control System ToolboxControl System Toolbox Database ToolboxDatabase Toolbox Model-Based Calibration ToolboxModel-Based Calibration Toolbox Neural Network ToolboxNeural Network Toolbox Optimization ToolboxOptimization Toolbox Partial Differential Equation (PDE) ToolboxPartial Differential Equation (PDE) Toolbox Signal Processing ToolboxSignal Processing Toolbox Statistics ToolboxStatistics Toolbox Symbolic Math ToolboxSymbolic Math Toolbox System Identification ToolboxSystem Identification Toolbox Wavelet ToolboxWavelet Toolbox

SimuLinkSimuLink

What is Simulink?What is Simulink?• a software package to model, simulate, a software package to model, simulate,

and analyze dynamic systemsand analyze dynamic systems Dynamic systemDynamic system

• control system, DSP, communication control system, DSP, communication systemsystem

• Continuous and discreteContinuous and discrete Startup SimuLink in MATHLABStartup SimuLink in MATHLAB

• MATHLAB Command WindowMATHLAB Command Window

SimuLinkSimuLink

How SimuLink worksHow SimuLink works

SimuLinkSimuLink

Two steps to simulate dynamic Two steps to simulate dynamic systemsystem• Create a graphical model: Simulink Create a graphical model: Simulink

model editormodel editor• Simulate using Simulink in some time Simulate using Simulink in some time

spanspan SimuLink Block Diagram ModelSimuLink Block Diagram Model

• time-dependent mathematical time-dependent mathematical relationships among inputs, states, and relationships among inputs, states, and outputsoutputs

Model Dynamic SystemModel Dynamic System

Block diagram notationBlock diagram notation• mathematical model: a set of equationsmathematical model: a set of equations• mathematical equations: algebraic, mathematical equations: algebraic,

differential, difference differential, difference BlockBlock

Four Mathematical models Four Mathematical models

Model Dynamic SystemModel Dynamic System

SimuLink BasicsSimuLink Basics• Create/open/save a modelCreate/open/save a model• Work with blocks: collect, customize and Work with blocks: collect, customize and

connect blocksconnect blocks• Annotation diagramsAnnotation diagrams• Create subsystemsCreate subsystems• Work with DataWork with Data• Run SimulationRun Simulation

Model Dynamic SystemModel Dynamic System

Example 1:Example 1:• Converting Celsius to FahrenheitConverting Celsius to Fahrenheit

Mathematical equation: Mathematical equation:

TF = 9/5(TC) + 32TF = 9/5(TC) + 32

• Build model with SimuLink blocksBuild model with SimuLink blocks

Model Dynamic SystemModel Dynamic System

Example 2:Example 2:• Differential equation Differential equation

Mathematical equation: Mathematical equation:

• Build model with SimuLink blocksBuild model with SimuLink blocks

Work with block librariesWork with block libraries

Simulink Block LibrarySimulink Block Library• a library of standard blocks a library of standard blocks

Create a library:Create a library:• new_system('newlib', 'Library')new_system('newlib', 'Library')

Modify a LibraryModify a Library• Unlock firstUnlock first

Create a library linkCreate a library link• drag the block from Library Browserdrag the block from Library Browser

Disabling Library LinksDisabling Library Links• Link options Link options

Work with signalsWork with signals

Signal DimensionsSignal Dimensions• one- or two-dimensional one- or two-dimensional

Signal Data typeSignal Data type• Double Double by defaultby default

Complex SignalsComplex Signals• Its value is Complex numberIts value is Complex number

Work with signalsWork with signals Virtual SignalsVirtual Signals

• A signal to represent another signal graphicallyA signal to represent another signal graphically

The signals driving Gain blocks G1 and G2 are virtual The signals driving Gain blocks G1 and G2 are virtual signals corresponding to signals s2 and s1, signals corresponding to signals s2 and s1, respectively respectively

Work with signalsWork with signals

Control SignalsControl Signals• a signal used by one block to initiate a signal used by one block to initiate

execution of another blockexecution of another block

Work with signalsWork with signals

Signal busSignal bus• A virtual signal that represents a set of A virtual signal that represents a set of

signals signals

RunRun

Start buttonStart button Using sim CommandUsing sim Command

• Syntax:Syntax:[t,x,y] = sim(model, timespan, options, ut);[t,x,y] = sim(model, timespan, options, ut);

Using set_param CommandUsing set_param Command• to start, stop, pause, or continue a to start, stop, pause, or continue a

simulation, or update a block diagram. simulation, or update a block diagram. • Format:Format:

set_param('sys', 'SimulationCommand', 'cmd') set_param('sys', 'SimulationCommand', 'cmd')

DebugDebug

GUI Debugger in GUI Debugger in tooltool menu menu• Breakpoints, Simulation Loop, Outputs, Breakpoints, Simulation Loop, Outputs,

Sorted List, StatusSorted List, Status sldebugsldebug prompt in MATLAB prompt in MATLAB

• (sldebug ...) plot(tout, yout) (sldebug ...) plot(tout, yout) Step-by-stepStep-by-step

Advanced IssuesAdvanced Issues

Create a complex modelCreate a complex model• Work with signal groupsWork with signal groups• Work with masked subsystemsWork with masked subsystems

Performance toolsPerformance tools• Simulink Accelerator: speed up a simulationSimulink Accelerator: speed up a simulation• Profiler: tune the performance of your modelProfiler: tune the performance of your model• Model Coverage Tool: determine the Model Coverage Tool: determine the

effectiveness of your model tests.effectiveness of your model tests.