Simulink Gs
Simulink Gs
R2024b
How to Contact MathWorks
Phone: 508-647-7000
Introduction
1
Simulink Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Modeling in Simulink
2
Simulink Block Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
v
Navigate a Simulink Model
4
Explore Model Hierarchy ....................................... 4-2
View Model Hierarchy ....................................... 4-2
View Signal Attributes ....................................... 4-4
Trace a Signal . . . . . . ....................................... 4-6
vi Contents
1
Introduction
Simulink is a block diagram environment for multidomain simulation and Model-Based Design. It
supports system-level design, simulation, automatic code generation, and continuous test and
verification of embedded systems. Simulink provides a graphical editor, customizable block libraries,
and solvers for modeling and simulating dynamic systems. It is integrated with MATLAB®, enabling
you to incorporate MATLAB algorithms into models and export simulation results to MATLAB for
further analysis.
Key Features
• Graphical editor for building and managing hierarchical block diagrams
• Libraries of predefined blocks for modeling continuous-time and discrete-time systems
• Simulation engine with fixed-step and variable-step ODE solvers
• Scopes and data displays for viewing simulation results
• Project and data management tools for managing model files and data
• Model analysis tools for refining model architecture and increasing simulation speed
• MATLAB Function block for importing MATLAB algorithms into models
• Legacy Code Tool for importing C and C++ code into models
1-2
Model-Based Design with Simulink
Modeling and simulation are valuable for testing conditions that are difficult to reproduce with
hardware prototypes alone. This is especially true in the early phase of the design process when
hardware is not yet available. Iterating between modeling and simulation can improve the quality of
the system design early, by reducing the number of errors found later in the design process.
You can automatically generate code from a model and, when software and hardware implementation
requirements are included, create test benches for system verification. Code generation saves time
and prevents the introduction of manually coded errors.
In Model-Based Design, a system model is at the center of the workflow. Model-Based Design enables
fast and cost-effective development of dynamic systems, including control systems, signal processing
systems, and communications systems.
1-3
1 Introduction
1-4
Model-Based Design with Simulink
The workflow in this tutorial focuses on fundamental Simulink tasks as they relate to Model-Based
Design.
• “System Definition and Layout” on page 1-7 — Identify modeling goals, determine components,
model system layout.
• “Model and Validate a System” on page 1-13 — Model and test components, integrate
components, test system.
• “Design a System in Simulink” on page 1-24 — Design and test new components.
The first two tasks in this workflow model an existing system and establish the context for designing
a component. The next step in this workflow would be to implement the new component. You can use
rapid prototyping and embedded code generation products, such as Simulink Real-Time™ and
Embedded Coder®, to generate code and use the design with a real, physical system.
See Also
Related Examples
• “System Definition and Layout” on page 1-7
• “Model and Validate a System” on page 1-13
• “Design a System in Simulink” on page 1-24
• “Organize Large Modeling Projects”
1-5
1 Introduction
External Websites
• Simulink Overview
• Model-Based Design with MATLAB and Simulink
1-6
System Definition and Layout
In this section...
“Determine Modeling Objectives” on page 1-7
“Identify System Components and Interfaces” on page 1-8
The top-level system layout of a Simulink model is a common context that many engineering teams
can use and is the basis for many tasks in the Model-Based Design paradigm: analysis, design, test,
and implementation. You define a system at the top level by identifying the structure and individual
components. You then organize your model in a hierarchical manner that corresponds to the
components. Then you define interfaces for each component and the connections between
components.
The featured model in this tutorial is a flat robot that can move or rotate with the help of two wheels,
similar to a home vacuuming robot. This model assumes that the robot moves in one of two ways:
• Linear — Both wheels turn in the same direction with the same speed and the robot moves
linearly.
• Rotational — The wheels turn in opposite directions with the same speed and the robot rotates in
place.
Each type of motion starts from a resting state, that is, both rotational and linear speeds are zero.
With these assumptions, the linear and rotational motion components can be modeled separately.
1-7
1 Introduction
• Determine how quickly the robot stops when the motors stop
• Provide a series of commands for linear and rotational motion so that the robot can move in a two-
dimensional space
The first modeling objective enables you to analyze the motion so you can design the sensor. The
second objective enables you to test your design.
• What are the structural and functional components of the system? When a layout reflects the
physical and functional structure, it helps you to understand, build, communicate, and test the
system. This becomes more important when parts of the system are to be implemented in different
stages in the design process.
• What are the inputs and outputs for each component? Draw a picture showing the connections
between components. This picture helps you to visualize signal flow within the model, identify the
source and sink of each signal, and determine if all necessary components exist.
• What level of detail is necessary? Include major system parameters in your diagram. Creating a
picture of the system can help you identify and model the parts that are essential to the behaviors
you want to observe. Each component and parameter that contributes to the modeling goal must
have a representation in the model, but there is a tradeoff between complexity and readability.
Modeling can be an iterative process. You can start with a high-level model with few details and
then gradually increase complexity where required.
The system in this tutorial defines a robot that moves with two electric wheels in two dimensions. It
includes:
1-8
System Definition and Layout
The model for this system includes two identical wheels, input forces applied to the wheels, rotational
dynamics, coordinate transformation, and a sensor. The model uses a Subsystem to represent each
component:
1 Open a new Simulink model. See “Open New Model” on page 3-3.
2 Open the Library Browser. See “Open Simulink Library Browser” on page 3-5.
3 Add Subsystem blocks. Drag five Subsystem blocks from the Ports & Subsystems library to the
new model.
4 Click a subsystem. In the Format tab, click the Auto drop-down list. Clear the Hide Automatic
Block Names check box.
5 Arrange and rename the Subsystem blocks as shown. To change block names, double-click the
block name and edit the text.
Identify input and output connections between subsystems. Input and output values change
dynamically during a simulation. Lines connecting blocks represent data transfer. This table shows
the inputs and outputs for each component.
1-9
1 Introduction
Some block inputs do not exactly match block outputs. Therefore, in addition to the dynamics of the
individual components, the model must compute the following:
• Input to the rotation computation — Subtract the velocities of the two wheels and divide by two.
• Input to the coordinate transformation — Average the velocities of the two wheels.
• Input to the sensor — Integrate the outputs of the coordinate transformation.
The wheel velocities are always equal in magnitude and the computations are accurate within that
assumption.
Each new Subsystem block contains one Inport (In1) and one Outport (Out1) block. These blocks
define the signal interface with the next higher level in a model hierarchy.
Each Inport block creates an input port on the Subsystem block, and each Outport block creates
an output port. The model reflects the names of these blocks as the input/output port names. Add
more blocks for additional input and output signals. On the Simulink Editor toolbar, click the
Navigate Up To Parent button to
return to the top level.
For each block, add and rename Inport and Outport blocks.
1-10
System Definition and Layout
When copying an Inport block to create a new one, use the Paste (Ctrl+V) option.
2 Compute required inputs to the Coordinate Transform and Rotation subsystems from the left
wheel and right wheel velocities.
a Compute the Linear speed input to the Coordinate Transform subsystem. Add an Add block
from the Math Operations library and connect the outputs of the two-wheel components. Add
a Gain block and set the gain parameter to 1/2. Connect the output of the Add block to this
Gain block.
b Compute the Speed difference input to the Rotation subsystem. Add a Subtract block from
the Math Operations library. Connect the right wheel velocity to the + input and the left
wheel velocity to the - input. Connect the outputs of the two wheel components. Add a Gain
block and set the gain parameter to 1/2. Connect the output of the Subtract block to this
Gain block.
3 Compute the X and Y coordinates from the X and Y velocities. Add two Integrator blocks from the
Continuous library and connect the outputs of the Coordinate Transform block. Leave initial
conditions of the Integrator blocks set to 0.
Determine the parameters that are part of the model and their values. Use modeling goals to
determine whether these values are always fixed or change from simulation to simulation. Parameters
1-11
1 Introduction
that contribute to the modeling goal require explicit representation in the model. This table helps
determine the level of detail when modeling each component.
Right Wheel
Rolling resistance Left Wheel k_drag 30 Ns2/m Variable
Right Wheel
Robot radius Rotation r 0.15 m Variable
Initial angle Rotation None 0 rad Fixed
Initial velocities Left Wheel None 0 m/s Fixed
Simulink uses the MATLAB workspace to evaluate parameters. Set these parameters in the MATLAB
command window:
m = 2.5;
k_drag = 30;
r = 0.15;
See Also
Related Examples
• “Model and Validate a System” on page 1-13
• “Design a System in Simulink” on page 1-24
1-12
Model and Validate a System
A big-picture view of the whole system layout is useful when modeling individual components. Start
by loading the layout model. At the MATLAB® command line, enter:
open_system('system_layout.slx')
• An explicit mathematical relationship between the output and the input of a physical component —
You can compute the outputs of the component from the inputs, directly or indirectly, through
algebraic computations and integration of differential equations. For example, computation of the
water level in a tank given the inflow rate is an explicit relationship. Each Simulink block executes
based on the definition of the computations from its inputs to its outputs.
• An implicit mathematical relationship between model variables of a physical component —
Because variables are interdependent, assigning an input and an output to the component is not
straightforward. For example, the voltage at the + end of a motor connected in a circuit and the
voltage at the - end have an implicit relationship. To model such a relationship in Simulink, you
can either use physical modeling tools such as Simscape™ or model these variables as part of a
larger component that allows input/output definition. Sometimes, closer inspection of modeling
goals and component definitions helps to define input/output relationships.
• Data obtained from an actual system — You have measured input/output data from the actual
component, but a fully defined mathematical relationship does not exist. Many devices have
unmodeled components that fit this description. For example, the heat dissipated by a television.
You can use the System Identification Toolbox™ to define the input/output relationship for such a
system.
1-13
1 Introduction
• An explicit functional definition — You define the outputs of a functional component from the
inputs through algebraic and logical computations. For example, the switching logic of a
thermostat. You can model most functional relationships as Simulink blocks and subsystems.
This tutorial models physical and functional components with explicit input/output relationships. In
this tutorial, you will:
Describe the relationships between components, for example, data, energy, and force transfer. Use
the system equations to build a graphical model of the system in Simulink.
• What are the constants for each component? What values do not change unless you change them?
• What are the variables for each component? What values change over time?
• How many state variables does a component have?
Derive the equations for each component using scientific principles. Many system equations fall into
three categories:
• For continuous systems, differential equations describe the rate of change for variables with the
equations defined for all values of time. For example, a first-order differential equation gives the
velocity of a car:
dv(t) b
= − v(t) + u(t)
dt m
• For discrete systems, difference equations describe the rate of change for variables, but the
equations are defined only at specific times. For example, the control signal from a discrete
proportional-derivative controller:
It = Ia + Ib
• Force applied by the motor — The force F acts in the direction of velocity change and is an input
to the wheel subsystems.
1-14
Model and Validate a System
• Drag force — The force Fdrag acts against the direction of velocity change and is a function of
velocity.
Fdrag = kdragV V
(m/2)V̇ = F − Fdrag
(m/2)V̇ = F − kdragV V
F − kdragV V
V̇ =
(m/2)
Where kdrag is the drag coefficient and m is the mass of the robot. Each wheel carries half of this
mass.
1 In the system_layout model, double-click the subsystem named Right Wheel to display the
empty subsystem.
2 To model velocity and acceleration, add an Integrator block. Leave the initial condition set to 0.
The input of this block is the acceleration Vdot and the output is the velocity V.
3 To model the drag force, add a MATLAB Function block from the User-Defined Functions library.
The MATLAB Function block provides a quick way to implement mathematical expressions in
your model. To edit the function, double-click the block to open the MATLAB Function Block
Editor.
4 In the MATLAB Function Block Editor, enter the MATLAB code to calculate the drag force.
function Fdrag=get_fdrag(V,k_drag)
Fdrag=k_drag*V*abs(V);
5 Define arguments for the MATLAB Function block. In the MATLAB Function Block Editor, click
Edit Data . Click k_drag, set Scope to Parameter, and click Apply.
6 Subtract the drag force from the motor force using the Subtract block. Complete the force-
acceleration equation using a Gain block with the Gain parameter specified as 1/(m/2).
7 To reverse the direction of the MATLAB Function block, select the block. Then, in the Simulink
Toolstrip, on the Format tab, click Flip left-right . Connect the blocks.
1-15
1 Introduction
8 The dynamics of the two wheels are the same. Make a copy of the subsystem named Right
Wheel that you just created and paste it in the subsystem named Left Wheel.
9
To view the top level of the model, click Navigate Up To Parent .
Rotational Motion
When the two wheels turn in opposite directions, they move in a circle of radius r, causing rotational
motion of the robot. When the wheels turn in the same direction, there is no rotation. Assuming that
the wheel velocities are always equal in magnitude, you can model rotational motion as dependent on
the difference of the two wheel velocities VR and VL:
VR − VL
θ̇ =
2r
1 In the top level of the system_layout model, double-click the subsystem named Rotation to
display the empty subsystem. Delete the connection between the Inport and the Outport blocks.
2 To model angular speed and position, add an Integrator block. Leave the initial condition set to 0.
The output of this block is the rotational position theta and the input is the angular speed
theta_dot.
3 Compute angular speed from tangential speed. Add a Gain block and set the Gain parameter for
the block to 1/(2*r).
4 Connect the blocks.
5
To view the top level of the model, click Navigate Up To Parent .
Describe the function from the input of a function to its output. This description can include algebraic
equations and logical constructs, which you can use to build a graphical model of the system in
Simulink.
Coordinate Transformation
The velocity of the robot in the x and y coordinates, VX and VY, is related to the linear speed VN and
the angle theta:
1-16
Model and Validate a System
V X = V Ncos θ
V Y = V Nsin θ
1 In the top level of the system_layout model, double-click the subsystem named Coordinate
Transform to display the empty subsystem.
2 To model trigonometric functions, add a SinCos block from the Math Operations library.
3 To model multiplication, add two Product blocks from the Math Operations library.
4 Connect the blocks.
5
To view the top level of the model, click Navigate Up To Parent .
You can determine appropriate values for parameters in your model using several sources, including:
A Simulink model can access parameter values defined using variables in the MATLAB workspace.
Define these variables by entering the commands in the MATLAB Command Window.
m = 2.5;
k_drag = 30;
r = 0.15;
• When a force is applied continuously to a wheel, the velocity increases until it reaches a steady-
state velocity.
1-17
1 Introduction
• When the wheels turn in opposite directions, the rotation angle increases at a constant rate.
1
Create a new model. In the Simulation tab, click New . Copy the Subsystem block named
Right Wheel into the new model.
2 To create a test input, add a Step block from the Sources library and connect it to the input of the
subsystem named Right Wheel. Leave the Step time parameter set to 1.
3 Add a scope viewer to the output. Right-click the output port of the subsystem block named
Right Wheel and select Create & Connect Viewer > Simulink > Scope.
4
Simulate the model. In the Simulation tab, click Run .
The simulation results show that the model exhibits the general expected behavior. No motion occurs
until force is applied at the step time. When force is applied, the speed starts to increase and then
settles at a constant when the applied force and the drag force reach an equilibrium. In addition to
validation, this simulation also shows the maximum speed of the wheel for the given force.
1-18
Model and Validate a System
1
To create a new model, click New . Copy the subsystem block named Rotation into the new
model.
2 To create a test input in the new model, add a Step block from the Sources library. Leave the
Step time parameter set to 1. Connect the output of the Step block to the input of the subsystem
named Rotation. This input represents the difference of the wheel velocities when the wheels
rotate in opposite directions.
3 Add a scope viewer to the output of the subsystem named Rotation. Right-click the output port
of the subsystem and select Create & Connect Viewer > Simulink > Scope.
4
Simulate the model. In the Simulation tab, click Run .
This simulation shows that the angle increases steadily when the wheels are turning with the same
speed in opposite directions. You improve the model to make the angle output easier to interpret. For
example, you can:
• Convert the output signal units from radians to degrees by adding a Gain block with a gain of
180/pi.
• Display the output value in cycles of 360 degrees by adding a Math Function block with function
mod.
1-19
1 Introduction
• When the same force is applied to both wheels in the same direction, the robot moves in a line.
• When the same force is applied to both wheels in opposite directions, the robot rotates in place.
1 In the system_layout model, double-click the subsystem named Inputs to display the empty
subsystem.
2 Create a test input by adding a Step block. Leave the Step time parameter set to 1. Connect the
Step block output to both Outport blocks.
3 At the top level of the model, connect both output signals to the same scope viewer.
1-20
Model and Validate a System
The yellow line in the scope viewer is the X direction, and the blue line is the Y direction. Since
the angle is zero and is not changing, the vehicle moves only in the X direction, as expected.
5 Double-click the subsystem named Inputs. To reverse the direction for the left wheel, add a
Gain block between the source and the second output and set the Gain parameter to -1.
The scope viewer connected to the x and y speed signals shows that no motion occurs in the X-Y
plane.
1-21
1 Introduction
The scope viewer connected to the angle signal shows steady angular motion.
You can use this final model to answer many questions about the model by changing the input.
1-22
Model and Validate a System
• How long does it take for the motion to stop when the force drops to zero?
• What happens when the robot is heavier?
• What happens when the robot moves on a smoother surface with a smaller drag coefficient?
See Also
Related Examples
• “System Definition and Layout” on page 1-7
• “Design a System in Simulink” on page 1-24
1-23
1 Introduction
Model-Based Design paradigm is centered on models of physical components and systems as a basis
for design, testing, and implementation activities. This tutorial adds a designed component to an
existing system model.
The model is a flat robot that can move or rotate with the help of two wheels, similar to a home
vacuuming robot. Open the model by entering in the MATLAB® command line:
open_system('system_model.slx')
• Design a controller that varies the force input so that the wheels turn at a desired speed.
• Design inputs that make the device move in a predetermined path.
• Design a sensor and controller so that the device follows a line.
• Design a planning algorithm so that the device reaches a certain point using the shortest path
possible while avoiding obstacles.
• Design a sensor and algorithm so that the device moves over a certain area while avoiding
obstacles.
1-24
Design a System in Simulink
This tutorial designs an alert system. You determine the parameters for a sensor that measures the
distance from an obstacle. A perfect sensor measures the distance from an obstacle accurately. An
alert system samples those measurements at fixed intervals so that the output is always within 0.05 m
of the measurement. The system generates an alert in time for the robot to come to a stop before
hitting the obstacle.
• How far the robot can travel at the top speed when power to the wheels is cut
• The top speed of the robot
Simulate the model with a force input signal that starts motion, waits until the robot reaches a steady
velocity, and then sets the force to zero:
• Amplitude: 1
• Period: 20
• Pulse Width: 15
These parameters are designed to ensure that the top speed is reached. You can change
parameters to see their effect.
4 Simulate the model for 20 seconds.
To analyze the simulation results, view the signals connected to the floating scopes in the model.
The first scope shows that the speed of the robot rapidly decreases after the pulse that
represents the input force drops to zero at a simulation time of 3 seconds. The speed
asymptotically approaches zero but never quite reaches zero. Accurate modeling for low speed
dynamics without external forces requires a much more complex representation of the system.
For the objective here, however, this approximate representation of the system is sufficient.
1-25
1 Introduction
The second scope shows the position of the robot over the course of the simulation. At the start,
the position changes more rapidly. At about a simulation time of 3 seconds, the position changes
more slowly as the speed of the robot decreases.
1-26
Design a System in Simulink
Zoom in on the scope plot that shows the robot position. At time 3, the position of the robot is
approximately 0.55 m. At the end of the simulation, the position of the robot is approximately 0.7 m.
Because the speed of the robot is very close to zero at the end of the simulation, the results show that
the robot moves less than 0.16 m after the external force drops to zero.
1-27
1 Introduction
The Value column in the Cursor Measurements panel indicates that the top speed of the robot is
0.183 m/s. To calculate the time it takes for the robot to travel 0.05 m, divide 0.05 m by 0.183 m/s to
get the result of 0.27 sec.
• Measurement of the distance between the robot and the obstacle — This example assumes that
the measurement is perfect.
• The time interval between each distance measurement the alert system makes — To keep the
measurement error below 0.05 m, the sampling interval must be less than 0.27 sec. Use 0.25 sec.
• The distance at which the sensor produces an alert — Analysis shows that slow down must start
by the time the robot is approximately 0.16 m from the obstacle. The actual alert distance must
also take the error from discrete measurements, 0.05 m, into account.
1 Create a subsystem with four input ports and one output port. The subsystem receives inputs for
the x- and y-coordinates of the robot and for the x- and y-coordinates of the obstacle. The alert
signal produced by the sensor connects to the output port.
1-28
Design a System in Simulink
2 Construct the distance measurement subsystem. In the subsystem named Sensor model, use
the Subtract block, the Math Function block with the function magnitude^2, the Sum block, and
the Sqrt block to implement the distance calculation. Notice that within the subsystem, the
arrangement of the input ports does not need to match the arrangement of the ports on the
Subsystem block interface.
3 To model the sampling, add a Zero-Order Hold block to the subsystem from the Discrete library
and set the Sample time parameter for the block to 0.25.
4 Connect the result of the distance calculation to the input of the Zero-Order Hold block.
5 To model the alert logic, add a Compare to Constant block from the Logic and Bit Operations
library and set these block parameters:
• Operator: <=
• Constant Value: 0.21
• Output data type: boolean
With these parameter values, the block output value is 1 when the input value is less than or
equal to 0.21.
6 Connect the output of the Zero-Order Hold block to the input of the Compare to Constant block.
7 Finally, connect the output of the Compare to Constant block to the Outport block named Alert.
1-29
1 Introduction
Verify Design
Test the design with an obstacle location of X = 0.65, Y = 0 using Constant blocks as inputs to the
Sensor model subsystem. This test verifies design functionality in the X direction. You can create
similar tests for different paths. This model only generates an alert. It does not control the robot.
1 Set the obstacle location. Add two Constant blocks from the Sources library set the constant
values to 0.65 and 0. Connect the position outputs of the robot to the inputs of the sensor.
2 Add a scope to the Alert output.
The plot of the robot position in the scope looks the same as the previous run.
1-30
Design a System in Simulink
The scope connected to the alert signal shows that the alert signal value becomes 1 when the robot
comes within 0.21 m of the obstacle location, satisfying the design requirement for this component.
1-31
1 Introduction
For real-world systems with complex components and formal requirements, the Simulink product
family includes additional tools to refine and automate the design process. Requirements Toolbox™
provide tools to formally define requirements and link them to model components. Simulink Control
Design™ can facilitate the design if you want to build a controller for this robot. Simulink Verification
and Validation™ products establish a formal framework for testing components and systems.
See Also
Related Examples
• “Model-Based Design with Simulink” on page 1-3
• “System Definition and Layout” on page 1-7
• “Model and Validate a System” on page 1-13
1-32
2
Modeling in Simulink
2 Modeling in Simulink
• A faucet fills a bucket — Water goes into the bucket at a certain flow rate, and the bucket gets
heavier. A block can represent the bucket, with flow rate as the input and its weight as the output.
• You use a megaphone to make your voice heard — The sound produced at one end of the
megaphone is amplified at the other end. The megaphone is the block, the input is the sound wave
at its source, and the output is the sound wave as you hear it.
• You push a cart and it moves — The cart is the block, the force you apply is the input, and the
cart's position is the output.
The definition of a block is only complete with its inputs and outputs defined; this task relates to the
goal of the model. For example, the cart velocity may be a natural choice as an output if the modeling
goal does not involve its location.
Simulink provides block libraries that are collections of blocks grouped by functionality. For example,
to model a megaphone that multiplies its input by a constant, you use a Gain block from the Math
Operations library.
A sound wave goes into the megaphone as its input, and a louder version of the same wave comes out
as its output.
The > signs denote the inputs and outputs of a block, which can be connected to other blocks.
You can connect blocks to other blocks to form systems and represent more complex functionality. For
example, an audio player turns a digital file into sound. A digital representation is read from storage,
2-2
Simulink Block Diagrams
is interpreted mathematically, and then turned into physical sound. The software that processes the
digital file to compute the sound waveform can be one block; the speaker that takes the waveform
and turns it into sound can be another block. A component that generates the input is another block.
To model the sine wave input to the megaphone in Simulink, include a Sine Wave source.
The primary function of Simulink is to simulate behavior of system components over time. In its
simplest form, this task involves keeping a clock, determining the order in which the blocks are to be
simulated, and propagating the outputs computed in the block diagram to the next block. Consider
the megaphone. At each time step, Simulink must compute the value of the sine wave, propagate it to
the megaphone, and then compute the value of its output.
At each time step, each block computes its outputs from its inputs. Once all of the signals in a
diagram are computed at a given time step, Simulink determines the next time step (based on the
model configuration and numerical solver algorithms) and advances the simulation clock. Then each
block computes their output for this new time step.
2-3
2 Modeling in Simulink
In simulation, time progresses differently from a real clock. Each time step takes as much time as it
takes to finish the computations for that time step, whether that time step represents a fraction of a
second or a few years.
Often, the effect of a component's input on its output is not instantaneous. For example, turning on a
heater does not result in an instant change in temperature. Rather, this action provides input to a
differential equation. The history of the temperature (a state) is also a factor. When simulation
requires solving a differential or difference equation, Simulink employs memory and numerical
solvers to compute the state values for the time step.
At each time step, Simulink computes new values for signals and states. By contrast, you specify
parameters when you build the model and can occasionally change them while simulation is running.
See Also
Related Examples
• “Create a Simple Model” on page 3-2
• “Model-Based Design with Simulink” on page 1-3
2-4
3
You can use Simulink to model a system and then simulate the dynamic behavior of that system. The
basic techniques you use to create a simple model in this tutorial are the same as those you use for
more complex models. This example simulates simplified motion of a car. A car is typically in motion
while the gas pedal is pressed. After the pedal is released, the car idles and comes to a stop.
A Simulink block is a model element that defines a mathematical relationship between its input and
output. To create this simple model, you need four Simulink blocks.
3-2
Create a Simple Model
Simulating this model integrates a brief pulse twice to get a ramp. The results display in a Scope
window. The input pulse represents a press of the gas pedal — 1 when the pedal is pressed and 0
when it is not. The output ramp is the increasing distance from the starting point.
3-3
3 Simple Simulink Model
To avoid shadowing, the Simulink Editor checks loaded models and files on the path and creates
a model with the next available name untitled, untitled1, untitled2, and so on.
3-4
Create a Simple Model
3 From the Simulation tab, select Save > Save as. In the File name text box, enter a name for
your model. For example, simple_model. Click Save. The model is saved with the file
extension .slx.
To open the Library Browser, in the Simulink Toolstrip, on the Simulation tab, click Library
Browser.
3-5
3 Simple Simulink Model
To browse through the block libraries, in the library tree, expand a category and then a functional
area.
For example, find the Pulse Generator block. In the search box, enter pulse, then press Enter. The
software searches the libraries for blocks with pulse in their name or description and then displays
the blocks on the Search Results tab of the Library Browser.
Tip You can return to browsing the library tree by clicking the Library Tab.
3-6
Create a Simple Model
Get detailed information about a block. On the Search Results tab, right-click the Pulse Generator
block, then select Help for the Pulse Generator block. The documentation opens and displays the
reference page for the block.
Blocks typically have several parameters. You can access all block parameters by double-clicking the
block.
From the Sources library, drag the Pulse Generator block to the Simulink Editor. A copy of the
Pulse Generator block appears in your model with a text box for the value of the Amplitude
parameter. Enter 1.
Double-click anywhere in the model canvas. In the quick insert menu that appears, enter out. A
list of blocks appears. Verify that the Out1 block from the Simulink library is selected. Check the
3-7
3 Simple Simulink Model
library name listed under the block name and the block description in the details pane to the
right of the search results.
Tip To hide the details pane, click the arrow . To show the details pane, click the arrow again.
For more information about the quick insert menu, see “Add Blocks to Models Using Quick Insert
Menu”.
3 Add these blocks to the model using the Library Browser or the quick insert menu.
Add a second Outport block by copying the existing one and pasting it at another point using
keyboard shortcuts.
3-8
Create a Simple Model
Connect Blocks
Connect the blocks by creating lines between output ports and input ports.
1 Click the output port on the right side of the Pulse Generator block.
The output port and all input ports suitable for a connection are indicated by a blue chevron
symbol .
2
Point to to see the
connection cue.
Click the cue to connect the blocks with a line and an arrow that indicates the direction of signal
flow.
3 Connect the output port of the Gain block to the input port on the Second-Order Integrator block.
4 Connect the two outputs of the Second-Order Integrator block to the two Outport blocks.
5 Save your model. In the Simulation tab, click Save.
Click the signal. In the Simulation tab under Prepare, click Add Viewer. Select Scope. A viewer
icon appears on the signal and a scope window opens.
You can open the scope at any time by double-clicking the icon.
Run Simulation
Specify the stop time for the simulation. Then, simulate the model.
3-9
3 Simple Simulink Model
1 On the Simulation tab, set the simulation stop time. In the Simulink Toolstrip, on the
Simulation tab, enter the value in the Stop Time field.
The default stop time of 10.0 is appropriate for this model. This time value has no units. The
time unit in Simulink depends on how the equations are constructed. This example simulates the
simplified motion of a car for 10 seconds — other models could have time units in milliseconds or
years.
2
To run the simulation, click Run .
The simulation runs and produces the output in the scope viewer.
Refine Model
Change Block Parameters
This example takes an existing model, moving_car.slx, and models a proximity sensor based on
this motion model.
3-10
Create a Simple Model
In this scenario, a digital sensor measures the distance between the car and an obstacle 10 m (30 ft)
away. The model outputs the sensor measurement and the position of the car, taking these conditions
into consideration:
To start, open the moving_car model. At the MATLAB command line, enter:
open_system('moving_car.slx');
You first need to model the hard stop when the car position reaches 10. The Integrator, Second-Order
block has a parameter for that purpose.
1 Double-click the Integrator, Second-Order block. The Block Parameters dialog box appears.
2 Select Limit x and enter 10 for Upper limit x. The background color for the parameter changes
to indicate a modification that is not applied to the model. Click OK to apply the changes and
close the dialog box.
1 Modify the model. Expand the model window to accommodate the new blocks as necessary.
• Find the actual distance. To find the distance between the obstacle position and the vehicle
position, add the Subtract block from the Math Operations library. Also add the Constant
block from the Sources library to set the constant value of 10 for the position of the obstacle.
• Model the imperfect measurement that would be typical to a real sensor. Generate noise by
using the Band-Limited White Noise block from the Sources library. Set the Noise power
parameter to 0.001. Add the noise to the measurement by using an Add block from the Math
Operations library.
• Model a digital sensor that fires every 0.1 seconds. In Simulink, sampling of a signal at a
given interval requires a sample and hold. Add the Zero-Order Hold block from the Discrete
library. After you add the block to the model, change the Sample Time parameter to 0.1.
• Add another Outport to connect to the sensor output. Keep the default value of the Port
number parameter.
2 Connect the new blocks. The output of the Second-Order Integrator block is already connected to
another port. To create a branch in that signal, left-click the signal to highlight potential ports for
connection, and click the appropriate port.
3-11
3 Simple Simulink Model
Annotate Signals
Compare the actual distance signal with the measured distance signal.
1 Create and connect a Scope Viewer to the actual distance signal. Right-click the signal and
select Create & Connect Viewer > Simulink > Scope. The name of the signal appears in the
viewer title.
2 Add the measured distance signal to the same viewer. Right-click the signal and select
Connect to Viewer > Scope1. Make sure that you are connecting to the viewer you created in
the previous step.
3-12
Create a Simple Model
3 Simulate the model. The scope viewer shows the two signals, actual distance in yellow and
measured distance in blue.
3-13
3 Simple Simulink Model
4
Zoom into the graph to observe the effect of noise and sampling. Click Zoom . Left-click and
drag a box around the region you want to see more closely.
3-14
Create a Simple Model
The plot shows that the measurement can deviate from the actual value by as much as 0.3 m. This
information becomes useful when designing safety features, such as a collision warning.
See Also
Blocks
Pulse Generator | Gain | Second-Order Integrator | Sum | Constant | Zero-Order Hold | Band-Limited
White Noise
Related Examples
• “Model and Validate a System” on page 1-13
3-15
4
Simulink models can be organized into hierarchical components. In a hierarchical model, you can
choose to view the system at a high level, or navigate down the model hierarchy to see increasing
levels of model detail.
In the model:
When you build a model, you connect blocks together to model complex components that represent
system dynamics. In this model, Vehicle, Proximity sensor, and Alert system are all complex
components with multiple blocks that exist in a hierarchy of subsystems. To view the contents of a
subsystem, double-click the subsystem.
To view a representation of the complete model hierarchy, open the Model Browser.
1 Vertically expand the model window until the Hide/Show Model Browser button is visible in the
lower left corner of the Simulink Editor.
2 Click the Hide/Show Model Browser button.
4-2
Explore Model Hierarchy
The Model Browser shows that all subsystems you view at the top level have subsystems of their own.
Expand each subsystem node to see the subsystems it contains. You can navigate through the
hierarchy in the Model Browser. For example, expand the Proximity sensor node and then select the
Sensor model subsystem.
4-3
4 Navigate a Simulink Model
The address bar shows which subsystem you are viewing. To open the subsystem in a separate
window, right-click the subsystem and select Open In New Window.
Every input or output port on a subsystem has a corresponding Inport or Outport block inside the
subsystem. These blocks represent data transfer between a subsystem and its parent. When a system
contains multiple input or output ports, the number on the Inport or Outport blocks indicates the
position of the port on the subsystem interface.
To show the data type of all signals in a model, in the Debug tab, under Information Overlays, click
Base Data Types.
The model displays data types along the signal lines. Most signals are double, except the output of
the subsystem named Alert system. Double-click the subsystem to investigate.
The data type labels in this subsystem show that data type change occurs in the subsystem named
Alert device. Double-click the subsystem to investigate.
The alert device component converts the signal Alert index from a double to an integer. You can
set the data type at sources, or use a Data Type Conversion block from the Signal Attributes library.
Double, the default data type, provides the best numerical precision and is supported in all blocks.
4-4
Explore Model Hierarchy
The double data type also uses the most memory and computing power. Other numerical data types
can be used to model embedded systems where memory and computing power are limited.
To show sample times, in the Debug tab, under Information Overlays, click Colors from the
Sample Time section. The model updates to show different colors for each sample time in the model,
along with a legend.
• A block or signal with continuous dynamics is black. Signals with continuous sample time update
as often as the solver requires to satisfy specified tolerance values.
• A block or signal that is constant is magenta. They remain unchanged through simulation.
• A discrete block or signal that updates at the lowest fixed interval is red. Signals with discrete
sample time update at a fixed interval. If the model contains components with different fixed
sample times, each discrete sample time has a different color.
• Multirate subsystems, which contain a mix of discrete and continuous signals, are yellow.
4-5
4 Navigate a Simulink Model
Trace a Signal
This model has a constant input and a discrete output. To determine where the sampling scheme
changes, trace the output signal through its source blocks.
1 To open the Model Browser, vertically expand the model window until the Hide/Show Model
Browser button is visible in the lower left corner of the Simulink Editor. Then, click the
Hide/Show Model Browser button.
2 To start tracing the sources for the output signal, select the signal. Then, in the Signal tab, click
Trace to Source .
The Simulink Editor enters signal tracing mode. In signal tracing mode, the model canvas
becomes gray instead of white to help the traced path stand out.
The hints panel shows hints for actions you can take in signal tracing mode and the keyboard
shortcut that corresponds to each action. To minimize the hints panel, press ? on your keyboard.
If you want to restore the hints panel, press ? on your keyboard again.
3 To continue tracing the sources for the output signal, press the left arrow key.
4 Keep pressing the left arrow key to trace the sources for the output signal until you reach the
Subtract block inside the subsystem named Alert logic. When you reach the Subtract block in
the signal path, you must choose a path to continue tracing because the Subtract block has two
input ports. The software highlights the next segment to trace in blue to indicate the selected
path. By default, the first input port is selected for continued tracing. Select the path for the
minus input port by pressing the down arrow key.
4-6
Explore Model Hierarchy
5 To find the source of the discretization, continue pressing the left arrow and note the color of
each port name, which reflects the sample time for the port.
The Zero-Order Hold block in the Sensor model subsystem coverts the signal from continuous to
discrete.
See Also
Related Examples
• “Create a Simple Model” on page 3-2
• “Model-Based Design with Simulink” on page 1-3
4-7