Anda di halaman 1dari 32

Simulink

Outline:
What & Why simulink? Components of a Model. Simulink Environment. Simulation Details. Simulink Block Libraries. Graphical User Interface. Script & Function files (*.m files). S_Function.

What is SIMULINK?
A software package for modeling, simulating, and analyzing dynamical systems, whose outputs change over time. Supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Provides a graphical user interface (GUI). No need to formulate differential equations and difference equations in a language or program. You can also customize and create your own blocks.

What is SIMULINK?
Wide range of real-world dynamic systems, including electrical circuits, reactors, braking systems, and many other electrical, mechanical, chemical and thermodynamic systems. Wide Range of Predefined Blocks in various Libraries for different applications. Simulating a dynamic system is a two-step process with Simulink: First, creating a graphical model of the system to be simulated, using Simulinks model editor. Second, using Simulink to simulate the behavior of the system over a specified time span.

Why Simulation & Modeling?


Reduce Prices. Reduce Design Time. Testing new ideas. Combining Hardware & Software. Combining different systems (mechanical, electrical and etc). Modular system design. Simplifying design of the complicated systems. Standing over Experienced Shoulders.

A Primary Example:

Components of a model:
Block Diagrams
A Simulink block diagram is a pictorial model of a dynamic system. It consists of a set of symbols, called blocks, interconnected by lines. Each block represents an elementary dynamic system that produces an output either continuously (a continuous block) or at specific points in time (a discrete block).

Blocks
A block comprises one or more of the following: a set of inputs, a set of states, and a set of outputs.

Components of a model:
States
A variable that determines a blocks output. Current value is a function of the previous values of the blocks states and/or inputs. Blocks with states are said to have memory because such blocks must store the previous values of their states and/or inputs in order to compute the current values of the states. For example Integrator block and Memory block have state. Stateless Block examples:Gain block, Sum and Product blocks.

Components of a Model:
System Functions
System functions specify the time-dependent relationships among its inputs, states, and outputs. System functions include: An output function, fo, that relates the systems outputs to its inputs, states, and time. An update function, fu, that relates the future values of the systems discrete states to the current time, inputs, and states. A derivative function, fd, that relates the derivatives of the systems continuous states to time and the present values of the blocks states and inputs.

Components of a Model:
Tunable Parameters
Many block parameters are tunable. A tunable parameter is a parameter whose value can change while Simulink is executing a model.

For example, the gain parameter of the Gain block is tunable. You can alter the blocks gain while simulation is running.

Continuous versus Discrete Blocks


Simulinks standard block set includes:
- Continuous blocks. - Discrete blocks.

Continuous blocks respond continuously to continuously changing input. Discrete blocks respond to changes in input only at integral multiples of a fixed interval called the blocks sample time. Examples of continuous blocks: The Constant block and blocks in Simulinks Continuous block library. Examples of discrete blocks: The Discrete Pulse Generator and blocks in the Discrete block library.

Components of a Model:
Subsystems
Simulink allows you to model a complex system as a set of interconnected subsystems each of which is represented by a block diagram.You create a subsystem using Simulinks Subsystem block and the Simulink model editor.

Signals
The output values of blocks. A wide range of signal attributes is supported, including signal name, data type (e.g., 8-bit, 16-bit, or 32-bit integer), numeric type (real or complex), and dimensionality (one-dimensional or two-dimensional array). Some blocks impose restrictions on the attributes of the signals they can handle.

Components of a Model:
Solvers
A variety of general-purpose numerical integration techniques exist, each having advantages in specific applications. Simulink provides implementations, called ordinary differential equation (ODE) solvers, of the most stable, efficient, and accurate of these numerical integration methods.

You can specify the solver to use in the model or when running a simulation.

Sample Time:
The sample time parameter sets the sample time at which a discrete blocks states are updated. Update time (t) t = n * Ts + offset n is an integer number. offset can be positive or negative. The offset is useful if some discrete blocks must be updated sooner or later than others. You cannot change the sample time of a block while a simulation is running. The fundamental sample time of a discrete system is the greatest common divisor of the systems actual sample times.

Simulink Environment:
The Library Browser displays a tree-structured view of the Simulink block libraries installed on your system.

Simulink Environment:
Changing the orientation of blocks:
Flip block command Rotate block command

Annotations Resizing blocks Connecting blocks Using drop shadows Assigning block priorities Setting block execution order Specifying block diagram colors

A typical System simulation:

You can specify the solver to use in the model or when running a simulation.

Creating Subsystems
Simplifying complex models by grouping blocks into subsystems. You can create a subsystem in two ways:
- Add a Subsystem block to your model, then open that block and add the blocks it contains to the subsystem window. - Add the blocks that make up the subsystem, then group those blocks into a subsystem.

Customized Blocks (Mask)


A powerful Simulink feature that enables customizing the dialog box and icon for a subsystem.

Initialization pane: Define and describe dialog box parameter prompts, name of variables associated with the parameters, and initialization commands.

Icon pane: Define the block icon.

Documentation pane: Define the mask type and specify the block description and the block help.

Callback Routines:
Defined MATLAB expressions that execute when an Event happens. Two kind of Callback parameters: - Model Callback Parameters
- StartFcn - StopFcn Before the simulation starts. After the simulation stops.

- Block Callback Parameters


OpenFcn When the block is opened. MoveFcn When block is moved or resized. StopFcn At any termination of the simulation. NameChangeFcn After a blocks name and/or path changes.

Modeling Equations:
Algebraic equations:
TF = 9/5*(TC) + 32

Differential equations:
x(t)=-2x(t)+u(t)

Simulation Parameters & solver:


Choose Simulation Parameters dialog box from the Simulation menu.
The Solver pane allows you to set the start and stop times, choose the solver and specify solver parameters, and choose some output options. The Workspace I/O pane manages input from and output to the MATLAB workspace. The Diagnostics pane allows you to select the level of warning messages displayed during a simulation.

If errors occur during a simulation, Simulink halts the simulation and displays the errors in the Simulation Diagnostics dialog box.

The Solver Pane:


Start time and Stop time fields. Variable-step and Fixed-step solvers. ode45 is an excellent general purpose continuous solver. The variable-step solver, discrete is for non_continuous. Variable-step solvers: ode45, ode23, ode113, ode15s, ode23s,
and discrete.

Fixed-step solvers: ode5, ode4, ode3, ode2, ode1, and discrete. Solver Options: Max step size, Initial step size, Min step size,
Relative tolerance, Absolute tolerance.

Output Options: Refine output, Produce additional output,


Produce specified output only.

The Workspace I/O Pane:


Loading Input from the Base Workspace. Saving Output to the Workspace.

Inport & Outport blocks are used for Interface with Workspace.

The Diagnostic Pane:


Set the events and conditions as Warnings, errors or nothing. Specify the warning or error messages. Having a User_defined S_functions Consistency and bounds check can help. The Advanced pane allows you to set various options that affect simulation performance. Inline parameters: Selecting this option makes all parameters non_tunable except those that you specify. Making parameters non_tunable enables Simulink to treat them as constants, thereby speeding up simulation.

Simulink Block Libraries:


Sources: Generate signals. Sinks: Display or write block output. Discrete: Discrete-time components. Continuous: Linear functions. Math: General mathematics functions. Functions & Tables: General functions and table look-up operations. Nonlinear: Nonlinear functions. Signal & Systems: Allow multiplexing and demultiplexing, implement external input/output, pass data, create subsystems, and other functions. Blocksets and Toolboxes: contains the Extras block library of specialized blocks.

Sources & Sinks Library:


Sources : Generate data. Sinks: Displays the result.

Continuous & Discrete Library:


Linear Continuous Components

Discrete_time components

Definition of the system:


Definition of a system is possible in different ways:
Zero_pole, State space, Transfer function, Look up table Fcn & MATLAB Fcn Blocks, Polynomial. Subsystem, S_function. Math, Nonlinear and Signal & Systems Blocks are used for combining the other parts.

Definition of the system:

Help is prepared for U. Use it.

Graphical User Interface:


A graphical user interface (GUI) is a user interface built with graphical objects, such as buttons, text fields, sliders, and menus. Applications provide GUIs are generally easier to use since the person using the application does not need to know what commands are available or how they work.

GUI Components:
A *.fig file containing a complete description of the GUI figure and all of its components (Button, Check Box,). Some *.m files containing the functions that launch and control the GUI and the callbacks.

Building a GUI:
Run Guide command in the MATLAB environment for making the *.fig file. Design the Layout of your GUI. Setting the properties of each object in the Property Inspector. Writing *.m files for callback of an Object in the callback field.

Guide Environment:

Menu Editor:

Model Execution & Control Commands:


Sim Simulate a dynamic system. Simplot Plot simulation data in a figure window. Simset Create or edit simulation parameters and solver properties for the sim command. Simget Get options structure properties & parameters. set_param Set Simulink system & block parameters. get_param Get system & block parameter values. gcb Get the pathname of the current block. gcs Get the pathname of the current system. gcbh Get the handle of the current block.

Speeding Up the Simulation:


A few causes of slow simulation speed:
Model includes a MATLAB Fcn block. Model includes an M-file S-function. Model includes a Memory block. The maximum step size is too small. Improperly selected relative tolerance. The time interval may be too long. The model contains an algebraic loop. The problem may be stiff but youre using a nonstiff solver. - The model uses sample times that are not multiples of each other.

Algebraic Loop:
An algebraic loop generally occurs when an input port with direct feedthrough is driven by the output of the same block, either directly, or by a feedback path through other blocks with direct feedthrough. Direct feedthrough block's outputs cannot be computed without knowing the values of the signals entering the blocks at input ports.

Script and Function Files


Script Files
Work as though you typed commands into MATLAB prompt Variable are stored in global work space

Function Files
Let you make your own MATLAB commands All variables within a function are local All information must be passed to functions as parameters

Script M-files
Standard ASCII Text file Executes a series of MATLAB commands on the base workspace.
% An Mfile to calculate % An Mfile to calculate % Fibonacci numbers % Fibonacci numbers f f= [1 1]; i i= 1; = [1 1]; = 1; while f(i) + f(i+1) < 1000 while f(i) + f(i+1) < 1000 f(i+2) = f(i) + f(i+1); f(i+2) = f(i) + f(i+1); i i= i i+ 1; = + 1; end end semilogy(f) semilogy(f)

Function M-file
Output Arguments Function Name Input Arguments

Online Help

function y = mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m;

Function Code

Function M-file
function r = ourrank(X,tol) function r = ourrank(X,tol) % rank of a matrix % rank of a matrix s = svd(X); s = svd(X); if (nargin == 1) if (nargin == 1) tol = max(size(X)) * s(1)* eps; tol = max(size(X)) * s(1)* eps; end end r = sum(s > tol); r = sum(s > tol);

Multiple Input Arguments use ( ) r=ourrank(rand(5),.1);

function [mean,stdev] = ourstat(x) function [mean,stdev] = ourstat(x) [m,n] = size(x); [m,n] = size(x); if m == 1 Multiple Output Arguments if m == 1 m = n; m = n; use [ ] end end mean = sum(x)/m; mean = sum(x)/m; [m,std]=ourstat(1:9); stdev = sqrt(sum(x.^2)/m mean.^2); stdev = sqrt(sum(x.^2)/m mean.^2);

Programming Features
for loops
for i= 1:10 y(i)= 3*i end

while loops
i=1; while i <= 10 y(i)=3*i i=i+1; end

Programming Features (cont)


if statement
for i = 1:41 if i <= 10 y(i)= 2*i; elseif i <=20 y(i)= 3*i; else y(i)= i-1; end end

What is S_function?
System function. A computer language description of a Simulink block. A non-graphical method of implementing a dynamic system. Can be written in MATLAB, C, C++, Ada, or Fortran. C, C++, Ada, and Fortran S-functions are compiled as MEX-files.

Simulation Procedure :
Simulation consists of 2 phases:
Initialization. Run-time.

Initialization:
All the parameters of every block are passed to MATLAB for evaluation. The resulting numbers are used as the actual parameters. The model hierarchy is flattened Each subsystem is replaced by the blocks they contain Subsystems that are triggered and/or enabled are classified as atomic units

Signal widths are checked.

Simulation Procedure: Run-Time


Simulation:
Outputs are calculated Discrete-time states are updated Continuous-time states are calculated using a 2 stage process: Each blocks output is calculated in the order determined by the sorting. Each block calculates its derivatives using the current time, block inputs and states. The derivatives are returned to the solver so that they can be integrated to form the next state.

Outputs are calculated:


Zero-crossing detection may be invoked.

Solver-System Dialogue:
time, input, states Solver Propagate block outputs Integrate state derivatives System Compute Block outputs State updates Generate State derivatives

Determine sample time

SIMULINK
Zero Crossing Events outputs, derivatives

Dialogs are governed by flags.

Control Flow of S-Functions


Set initial conditions Flag = 0 mdlInitializeConditions mdlInitializeSizes mdlInitializeSampleTimes Flag = 4 mdlGetTimeNextVarHit Flag = 3 mdlOutputs Flag = 2 mdlUpdate Integration phase Flag = 3 mdlOutputs Flag = 1 mdlDerivatives Flag = 9 mdlTerminate

Calculate time of next sample hit (only for variable sample time blocks) Calculate outputs Update discrete states Calculate outputs Calculate derivatives At termination, perform any required tasks

M-file S-Function template:


Use sfuntmpl.m Primary function: SWITCH-CASE construct based on flags directs Simulink to the correct subfunction. Subfunctions: mdlInitialize: provide number of states, inputs, outputs, sample times, initial value of states mdlDerivatives: given t,x,u, compute continuous state derivatives. mdlUpdate: given t,x,u, compute discrete state updates mdlOutputs: given t,x,u, compute outputs >>edit sfuntmpl

Creating Custom Blocks


The creation of new blocks is achieved using the S-Function block provided in the Functions and Tables library. It provides a graphical gateway to the code within the user-written S-Function. The S-Function name and any parameters should be defined within the block dialog. This block can be masked and placed within a library.

Initialization of M-File S-Functions:


Before you start, ask yourself: How many continuous states? How many discrete states? How many outputs? How many inputs? Does the S-Function have direct feedthrough? How many sample times does the S-Function have?

Simple systems w/o parameters:


Initialization

Outputs

>> edit sfun_times2

Simple Systems with Parameters:


Modify the primary function

Additional parameter(s) Modify the relevant subfunctions

Discrete Systems:
Initialize states

Model update function

Continuous Systems:
State initialization

Model derivatives function

Examples:
Continuous Discrete Hybrid Variable-step csfunc.m dsfunc.m mixedm.m vsfunc.m

Example: Integrator

>> sfun_int >> s_int

C MEX S-functions: Motivation


Speed Code generation Including existing C code Interfacing to the operating system Writing device drivers

C MEX S-Function Template:

Use the template sfuntmpl.c located in matlabroot\simulink\src directory Use macros to set and get values These two statements must be at the top of every file #include "simstruc.h" #define S_FUNCTION_NAME your_sfunction_name_here This statement must be at the end of every file #ifdef MATLAB_MEX_FILE #include "simulink.c" #else #include "cg_sfun.h" #endif

S-Function Examples
sfundemos at the MATLAB command line.

Using the S-Function Builder:


A Simulink block builds an S-function from specifications and C code that you supply. Limited to building S-functions that have a single input and output and that process data of type double.

Anda mungkin juga menyukai