The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
March 2007Online onlyNew for Version 1.0 (Release 2007a)
September 2007 O nline onlyRevised for Version 2.0 (Release 2007b)
March 2008Online onlyRevised for Version 2.1 (Release 2008a)
October 2008Online onlyRevised for Version 3.0 (Release 2008b)
March 2009Online onlyRevised for Version 3.1 (Release 2009a)
September 2009 O nline onlyRevised for Version 3.2 (Release 2009b)
March 2010Online onlyRevised for Version 3.3 (Release 2010a)
Modeling Physical Systems
1
Basic Principles of Modeling Physical Networks .....1-2
Overview of the Physical Network Approach to Modeling
Physical Systems
Variable Types
Building the Mathematical Model
Direction of Variables
Connector Ports and Connection Lines
Connecting Simscape Diagrams to Simulink Sources and
Scopes
........................................ 1-10
...............................1-2
....................................1-4
....................1-5
.............................1-6
................1-8
Contents
Introducing the Simscape Block Libraries
Library Structure Overview
Using the Simulink Library Browser to Access the Block
Libraries
Using the Command Prompt to Access the Block
Libraries
Essential Steps to Building a Physical Model
Building Your Model
Using the Conserving Ports
Using the Physical Signal Ports
Creating a Simple Model
Building a Simscape Diagram
Modifying Initial Settings
Running the Simulation
Adjusting the Parameters
Assumptions and Limitations
Fundamental Equations
Network Variables
Connection Constraints
References
....................................... 1-45
................................ 1-44
....................... 1-42
............................ 1-43
............................ 1-45
Simulating Physical Models
2
How Sim scap e Simulation Works ...................2-2
Simscape Simulation Phases
Model Validation
Network Construction
Equation Construction
Computing Initial Conditions
Performing Transient Initialization
Transient Solve
..................................2-4
..............................2-4
...................................2-6
........................2-2
.............................2-5
........................2-5
...................2-6
viContents
Working with Solvers
Selecting a Solver
Input Filtering
Troubleshooting Simulation Errors
Troubleshooting Tips and Techniques
System Configuration Errors
Numerical Simulation Issues
Initial Conditions Solve Failure
Transient Simulation Issues
Finding an Operating Point
What Is an Operating Point?
How to Find Operating Points
Finding Operating Points with Simscap e, Simulink, and
Related P roducts
Linearizing at an Operating Point
What Is Linearization?
How to Linearize a Model
.................................... 2-10
..............................2-8
.................................2-8
................. 2-13
................. 2-13
........................ 2-14
........................ 2-17
...................... 2-19
........................ 2-20
........................ 2-22
........................ 2-22
....................... 2-23
................................ 2-24
.................. 2-28
............................. 2-28
........................... 2-30
Linearizing a Model with Si mscape, Simulink, and Related
Products
References
....................................... 2-30
....................................... 2-34
Generating Code
About Code Generation from Simscape Models
Related Simulink Code Generation Documentation
Reasons for Generating Code
Using Code-Related Products and Features
How Simscape Code Generation Differs from Simulink
Limitations
Sample Time and Solver Restrictions
Algebraic Loops
Restricted Simulink Tools
Unsupported Simulink Tools
Simulink Tools Not Compatible with Simscape Blocks
Code Generation
.................................. 2-35
......... 2-35
...... 2-35
........................ 2-36
............ 2-36
....................................... 2-39
................. 2-39
................................... 2-39
.......................... 2-40
........................ 2-42
.................................. 2-42
Logging Simulation Data
3
About Simulation Data Logging .....................3-2
About Affine Units
When to Apply Affine Conversion
How to Apply Affine C onversion
Angular Units
References
...................................4-4
...................4-9
.......................... 4-11
................................ 4-11
.................... 4-11
..................... 4-12
..................................... 4-14
....................................... 4-14
Using the Simscape Editing Mode
5
About the Simscape Editing Mode ...................5-2
Suggested Workflows
What You Can Do in Restricted Mode
What You Can Do in Full Mode
Switching Between Modes
Working with Block Libraries
..............................5-2
.................5-3
......................5-4
..........................5-4
.......................5-7
viiiContents
Working with Restricted and Full Modes
Setting the Model Loading Preference
Saving a Model in Restricted Mode
Working with a Model in Restricted Mode
Switching from Restricted to Full Mode
Editing Mode Information
What Is the Current Mode?
Which Licenses Are Checked Out?
.......................... 5-23
......................... 5-23
.................5-9
................... 5-10
.................... 5-23
............5-9
............. 5-13
............... 5-21
Examples
A
Getting Started ....................................A-2
Best Practices
Editing Mode
.....................................A-2
......................................A-2
Index
ix
xContents
1
Modeling Physical Systems
• “Basic Principles of Modeling Physical Networks” on page 1-2
• “Introducing the Simscape Block Libraries” on page 1-11
• “Essential Steps to Building a Physical Model” on page 1-14
• “Creating a Simple Model” on page 1-17
• “Modeling Best Practices” o n page 1-35
• “Modeling Pneumatic Systems” on page 1-42
1 Modeling Physical Systems
Basic Principles of Modeling Physical Networks
In this section...
“Overview of the Physical Network Approach to Modeling Physical Systems”
on page 1-2
“Variable Types” on page 1 -4
“Building the Mathematical Model” on page 1-5
“Direction of Variables ” on page 1-6
“Connector Ports and Connection Lines” on page 1-8
“Connecting Simscape Diagr ams to Simulink Sources a n d Scopes” on page
1-10
Overview of the Physical Network Approach to
Modeling Physical Systems
Simscape™ software is a set of block libraries and special simu lat ion features
for modeling physical systems in the Simulink
the Physical Network approach, which differs from the standard Simulink
modeling approach and is particularly suited to simulating systems that
consist of real physical components.
®
environment. It employs
1-2
Simulink blocks represent basic mathematical operations. When you
connect Simulink blocks together, the resulting diagram is equivalent to the
mathematical model, or representation, of the system under design. Simscape
technology lets you create a network representation of the system under
design, bas ed on the Physical Network approach. According to this approach,
each system is represented as consisting of functional elements that interact
with each other by exchanging energy through their ports.
These connection ports are bidirectional. They mimic physical connections
between elements. Connecting Simscape blocks together is analogous to
connecting real components, such as pumps, valves, and so on. In other words,
Simscape diagrams mimic the physical system layout. If physical components
can be connected, their models can be connected, too. You do not have to
specify flow directions and information flow when connecting Simscape
blocks, just as you do not have to specify this information when you connect
Basic Principles of Modeling Physical Networks
real physical components. The Physical Network approach, with its Through
and Across variables and bidirectional physical connections, automatically
resolves all the traditional issues with variables, directionality, and so on.
The number of connection ports for each element is determined by the number
of energy flows it exchanges with other elements in the system, and depends
on the level of idealization. For example, a fixed-displacement hydraulic
pump in its simplest form can be represented as a two-port element, with one
energy flow associated with the inlet (suction) and the other with the outlet.
In this representation, the angular velocity of the driving shaft is assumed
constant, making it possible to neglect the energy exchange between the
pump and the shaft. To account for a variable driving torque, you need a third
port associated with the driving shaft.
An energy flow is characterized by its variables. Each energy flow is
associated with two variables, one Through and one Across (see “Variable
Types” on page 1-4 for more information). Usually, these are the variables
whose product is the energy flow in w atts. They are called the basic, or
conjugate, variables. For example, the basic variables for mechanical
translational systems are force and velocity, for mechanical rotational
systems—torque and angular velocity, for hydraulic systems—flow rate and
pressure, for electrical systems—current and voltage.
The following example illustrates a Physical Network representation of a
double-acting hydraulic cylinder.
The element is represented with three energy flows: two flows of hydraulic
energy through the inlet and outlet of the cylinder and a flow of mechanical
1-3
1 Modeling Physical Systems
energy associated with the rod motion. It therefore has the following three
connector ports:
• A — Hydraulic conserving port associated with pres sure
variable) and flow rate
q
(a Through vari abl e)
1
• B — Hydraulic conserving port associated with pres sure
variable) and flow rate
q
(a Through vari abl e)
2
p
(an Across
1
p
(an Across
2
• R — Mechanical translational conserving port associated with rod velocity
v
(an A cross variable) and force F3(a Through variable)
3
See “Connector Ports and Connection Lines” on page 1-8 for more information
on connector port types.
Variable Types
Physical Network approach supports two types of variables:
• Through — Variables that are measured with a gauge connected in series
to an element.
• Across — Variables that are measured with a gauge connected in parallel
to an element.
ThefollowingtableliststheThroughand Across variables associated with
each type of physical domain in Simscape software:
Physical DomainAcross VariableThrough Variable
1-4
ElectricalVoltage
Hydraulic
Magnetic
Pressure
Magnetomotive force
(mmf)
Mechanical rotational
Mechanical
Angular velocity
Translational velocity
translational
Current
Flow rate
Flux
Torque
Force
Basic Principles of Modeling Physical Networks
Physical DomainAcross VariableThrough Variable
PneumaticPressure and
temperature
Thermal
Temperature
Mass flow rate and heat
flow
Heat flow
Note Generally, the product of each pair of Across and Through variables
associated w ith a domain is power (energy flow in watts). The exceptions are
pneumatic domain, where the product of pressure and mass flow rate is not
power, and magnetic domain, where the product of mmf and flux is not power,
but energy. These result in a pseudo-bond graph.
Building the Mathematical Model
Through and Across variables associated with all the energy flows form the
basis of the mathematical model of the block.
For example, the model of a double-acting hydraulic cylinder shown in the
previous illustration can be described with a simple set of equation s :
FpApA
=−ii
31122
=i
qAv
113
=i
qAv
223
1-5
1 Modeling Physical Systems
where
q
p
A
F
v
1,q2
1,p2
1,A2
3
3
Flow rates through ports A and B , respectively (Through variables)
Gauge pressures at ports A and B, respectively (Across variables)
Piston effective areas
Rod force (Through variable)
Rod velocity (A cross variable)
The model could be considerably more complex, for example, it could
account for friction, fluid compressibility, inertia of the moving parts, and
so on. For all these different mathematical models, however, the element
configuration (that is, the number and type of ports and the associated
Through and Across variables) would remain the same, meaning that the
Physical Network approach lets you substitute models of different levels of
complexity w ithout introducing any changes to the schematic. For example,
you can start dev eloping your s ystem by using the Resistive Tube block from
the Foundation library, which accounts only for friction losses. At a later
stage in development, you may want to account for fluid compressibility.
You can then replace it with a Hydraulic Pipeline block, available with
SimHydraulics
®
block libraries, or, depending on your application, even with
a S eg mented Pipeline block if you also need to account for fluid inertia. This
modeling principle is called incremental modeling.
1-6
Direction of Variables
Each variable is characterized by its magnitude and sign. The sign is the
result of measure ment orientation. The same variable can be positive or
negative, depending on the polarity of a measurement gauge. That is why
it is very important to apply exactly the same rule to all the variables in
the Physical Network.
Elements w ith only two ports are characterized with one pair of variables, a
Through variable and an Across variable. Since these variables are closely
related, their orientation is defined with one direction. For example, if an
element is oriented from port A to port B, it implies that the Through variable
(TV) is positive if it “flows” from A to B, and the Across variable is determined
Basic Principles of Modeling Physical Networks
as AV = AVA–AVB,whereAVAand AVBare the element node potentials or, in
other w ords, the values of this Across variable at ports A and B, respectively.
This approach to the direction of variables has the following benefits:
• Provides a simple and consiste nt way to determine whether an element is
active or passive. Energy is one of the most important characteristics to
be determined during simulation. If the variables direction, or sign, is
determined as described above, their product (that is, the energy) is positive
if the element consumes energy, and is negative if it provides energy to a
system. This rule is followed throughout the Simscape software.
• Simplifies the model description. Symbol
ABis enough to specify
variable polarity for both the Across and the Through variables.
• Lets you apply the oriented graph theory to network analysis and design.
As an example of variables direction rules, let us consider the Ideal Force
Source block. In this block, as in many other mechanical blocks, port C is
associated with the source reference point (case), and port R is asso ciated
with the rod.
1-7
1 Modeling Physical Systems
The block pos
is positive
to port R to a
determined
and C, respe
at port C. T
force and v
All the el
dependin
it. Activ
etc.) mu
that the
(damper
Connec
Simsca
• Physi
or mec
vari
• Phys
an in
if it acts in the direction from C to R, and causes bodies connected
he power generated by the source is computed as the product of
elocity, and is negative if the source provides energy to the system.
ements in a network are divided into active and passive elements,
g on whether they deliver energy to the sy stem or dissipate (or store)
e elements (force and velocity sources, flow rate and pressure sources,
st be oriented strictly in accordance with the line of action or function
y are expected to perform in the system, while passive elements
s, resis tors, springs, pipeline s, etc.) can be oriented either way.
tor Ports and Connection Lines
pe blocks may have the following types of ports:
cal Conserving ports — Bidirectional ports (for example, hydraulic
hanical) that represent physical connections and relate physical
ables based on the Physical Network approach.
ical Signal ports — Unid irectional ports transferring signals that use
ternal Simscape engine for computations.
itive direction is from port C to port R. This means that the force
ccelerate in the positive direction. The relative velocity is
as
v = v
– vR,wherevR, vCare the absolute velocities at ports R
ctively, and it is negative if velocity at port R is greater than that
C
1-8
h of these ports and connections between them are described in greater
Eac
ail below.
det
Basic Principles of Modeling Physical Networks
Physical Conserving Ports
Simscape blocks have special Conserving ports. You connect Conserving
ports with Physical connection lines, distinct from normal Simulink lines.
Physical connection lines have no inherent directionality and represent the
exchange of energy flows, according to the Physical Network approach.
• You can connect Conserving ports only to other Conserving ports of the
same type.
• The Physical connection lines that connect Conserving ports together
are bidirectional lines that carry physical variables (Across and Through
variables, as described above) rather than signals. You cannot connect
Physical lines to Simulink ports or to Physical Signal ports.
• Two directly connected Conserving ports must have the same values for all
their A cross variables (such as pressure or angular velocity).
• You can branch Physical connection lines. When you do so, components
directly connected with one another continue to share the same Across
variables. Any Through variable (such as flow rate or torque) transferred
along the Physical connection line is divided among the multiple
components connected by the branches. How the Through variable is
divided is determined by the system dynamics.
For each Through variable, the sum of all its values flowing into a branch
point equals the sum of all its values flowing out.
Each type of Physical Conserving ports used in Simscape blocks uniquely
represents a physical modeling domain. For a list of port types, along with
the T hrough and Across variables associated with each type, see the table in
“Variable Types” on p ag e 1-4.
Physical Signal Ports
Physical Signal portscarry signals between Simscape blocks. Y ou connect
them with regular connection lines, similar to Simulink signal connections.
Physical Signal ports are used in Simscape block diagrams instead of
Simulink input and output ports to increase computation speed and avoid
issues with algebra ic loops. Unlike Simulink signals, which are essentially
unitless, physical signals can have units associated with them. Y ou specify
the units along with the parameter values in the block dialogs, and Simscape
1-9
1 Modeling Physical Systems
software performs the necessary unit conversion operations when solving a
physical network.
Simscape Foundation library contains, among other sublibraries, a Physical
Signals block library. These blocks perform math operations and other
functions on physical signals, and allow you to graphically implement
equations inside the Physical Network.
Connecting Simscape Diagrams to Simulink Sources
and Scopes
Simscape block diagrams use physical signals instead of regular Simulink
signals. Therefore, you need converter blocks to connect Simscape diagrams
to Simulink sources and scopes.
Use the Simulink-PS Converter block to connect Simulink sources or other
Simulink blocks to the inputs of a Physical Network diagram. You can
also use it to specify the input signal units. For more information, see the
Simulink-PS Converter block reference page.
1-10
Use the PS-Simulink Converter block to connect outputs of a Physical
Network diagram to Simulink scopes or other Simulink blocks. You can also
use it to specify the desired output signal units. For more information, see
the PS-Simulink Converter block reference page.
For an example of using converter blocks to connect Simscape diagrams to
Simulink sources and scopes, see “Creating a Simple Model” on page 1-17.
Introducing the Simscape Block Libraries
In this section...
“Library Structure Overview” on page 1-11
“Using the Simulink Library Browser to Access the Block Libraries” on
page 1-11
“Using the Command Prompt to Access the Block Libraries” on page 1-12
Library Structure Overview
Simscape block library contains two libraries that belong to the Simscape
product:
• Foundatio n library — Contains basic hydraulic, pneumatic, mechanical,
electrical, magnetic, thermal, and physicalsignalblocks,organizedinto
sublibraries according to technical discipline and function performed
• Utilities library — Contains essential environment blocks for creating
Physical Networks models
Introducing the Simscape™ Block Libraries
In addition, if you have installed any of the add-on products of the Physical
Modeling family, you will see the corresponding libraries under the main
Simscape library.
You can combine all these blocks in your Simscape diagrams to model physical
systems. You can also use the basic Simulink blocks in your d iagrams, such as
sources or scopes. See “Connecting Simscape Diagrams to Simulink Sources
and S copes” on page 1-10 for more information on how to do this.
Using the Simulink Library Browser to Access the
Block Libraries
You can access the blocks through the Simulink Library Browser. To display
the Library Browser, click the Library Browser button in the toolbar of the
MATLAB
®
desktop or Simulink model window:
1-11
1 Modeling Physical Systems
Alternatively, you can type simulink in the MATLAB Command Window.
Then expand the Simscape entry in the contents tree.
1-12
For more information on using the Library Brow ser, see “Library Browser” in
the Simulink Graphical User Interface documentation.
Using the Command Prompt to Access the Block
Libraries
To access individual block libraries by using the command prompt:
• To open the Simscape library, type
Window.
• To open the main Simulink library (to access generic Simulink blocks), type
simulink in the MATLAB Command Window.
The Simscape library consists of two top-level libraries, Foundation and
Utilities. In addition, if you have installed any of the add-on products of the
Physical Modeling family, you will see the corresponding libraries under
Simscape library, as shown in the following illustration. Some of these
libraries contain second-level and thi rd-level sublibraries. You can expand
simscape in the MATLAB Command
Introducing the Simscape™ Block Libraries
each library by d ouble-clicking its icon. For more details on library hierarchy
and descriptions of block categories, see “Block Reference”.
1-13
1 Modeling Physical Systems
Essential Steps to Building a Physical Model
Building Your Model
The ru les that you must follow when building a physical model with Simscape
software are described in “Basic Principles of Modeling Physical Networks” on
page 1-2. This section bri efly reviews these rules.
• Build your physical model by using a combination of blocks from the
Simscape Foundation and Utilities libraries. Simscape software lets you
create a network representation of the system under design, based on the
Physical Network approach. According to this approach, each system is
represented as cons isting of functional elements that interact with e ach
other by exchanging energy through their ports.
• Each Simscape diagram (or each topologically distinct physical network in
a diagram) must contain a Solver Configuration block from the Simscape
Utilities library.
• If you have hydraulic elements in your model, the working fluid used in
the hydraulic circuit defines their globa l parameters, such as fluid density,
fluid kinematic viscosity, fluid bulk modulus, and so on. To specify the
working fluid, attach a Custom Hydraulic Fluid block (or a Hydraulic Fluid
block, available with SimHydraulics block libraries) to each topologically
distinct hydraulic circuit. If no Hydraulic Fluid block or Custom Hydraulic
Fluid block is attached to a circuit, the hydraulic blocks use the default
fluid, which is Skydrol LD-4 at 60°C and with a 0.005 ratio of entrapped air.
1-14
• If you have pneumatic elements in your model, default gas properties are
for dry air and ambient conditions of 101325 Pa and 20 degrees Celsius.
Attach a Gas Properties block to each topologically distinct pneumatic
circuit to change gas properties and ambient conditions.
• To connect regular Simulink blocks (such as sources or scopes) to your
physical network diagram, use the connector blocks, as described in “Using
the Physical Signal Ports” on page 1-16.
• Use the incremental modeling approach. Start with a simple model, run
and troubleshoo t it, then add the desired special effects. For example, you
can start developing your system by using the Resistive Tube block from
the Foundation library, which accounts only for friction losses. At a later
stage in development, you may want to account for fluid compressibility.
Essential Steps to Building a Physical Model
You can then replace it with a Hydraulic Pipeline block, available with
SimHydraulics block libraries, or, depending on your application, even with
a Segmented Pipeline block if you also need to account for fluid inertia. For
all these different mathematical models, the element configuration (that
is, the number and type of ports and the associated Through and Across
variables) would remain the same, meaning that the Physical Network
approach lets you substitute models of different levels of complexity
without introducing any changes to the schematic.
Simscape blocks, in general, feature both Conserving ports
Signal inports and outports
.
and Physical
Using the Conserving Ports
ThefollowingrulesapplytoConservingports:
• There are different types of Physical Conserving ports used in Simscape
block diagrams, such as hydraulic, pneumatic, electrical, magnetic,
thermal, mechanical translational, and mechanical rotational. Each type
has specific Through and Across variables associated with it. For more
information, see “Variable Types” on page 1-4.
• You can connect Conserving ports only to other Conserving ports of the
same type.
• The Physical connection lines that connect Conserving ports together
are bidirectional lines that carry physical variables (Across and Through
variables, as described above) rather than signals. You cannot connect
Physical lines to Simulink ports or to Physical Signal ports.
• Two directly connected Conserving ports must have the same values for all
their Across variables (such as voltage or angular velocity).
• You can branch Physical connection lines. When you do so, components
directly connected with one another continue to share the same Across
variables. Any Through variable (such as current or torque) transferred
along the Physical connection line is divided among the multiple
components connected by the branches. How the Through variable is
divided is determined by the system dynamics.
For each Through variable, the sum of all its values flowing into a branch
point equals the sum of all its values flowing out.
1-15
1 Modeling Physical Systems
Using the Physic
The following ru
• You can connect
regular connec
connection li
• You can connec
converter blo
outports to P
to connect Ph
• Unlike Simu
can have uni
the units al
converter
desired ou
For examp
see the fo
llowing section, “Creating a Simple Model” on page 1-17.
les apply to Physical Signal ports:
Physical Signal ports to other Physical Signal ports with
tion lines, similar to Simulink signal connections. These
nes ca rry physical signals between Simscape block s.
t Physical Signal ports to Simulink ports through special
cks. Use the Simulink-PS Converter block to connect Simulink
hysical Signal inports. Use the PS-Simulink Converter block
ysical Signal outports to Simulink inports.
link signals, which a re essentially unitless, Physical Signals
ts associated with them. Simscape block dialogs let you specify
ong with the parameter values, where appropriate. Use the
blocks to associate units with an input signal and to specify the
tput signal units.
les of applying these rules when creating an actual physical model,
al Signal Ports
1-16
Creating a Simple Model
In this section...
“Building a Simscape Diagram” on page 1-17
“Modifying Initial Settings” on page 1-25
“Running the Simulation” on page 1-26
“Adjusting the Parameters” on page 1-29
Building a Simscape Diagram
In this example, you are going to model a simple mechanical system and
observe its behavior under various conditions. This tutorial illustrates the
essential steps to building a physical model, described in the previous section,
and makes you familiar with using the basic Simscape blocks.
The following schematic represents a simple model of a car suspension. It
consists of a spring and damper connected to a body (represented as a mass),
which is agitated b y a force. You can vary the model parameters, such as the
stiffness of the spring, the mass of the body, or the force profile, and view the
resulting changes to the velocity and position of the body.
Creating a Simple Model
1-17
1 Modeling Physical Systems
To create an equivalent Simscape diagram, follow these steps:
1-18
1 Open the Simscape and Simulink block libraries, as described in
“Introducing the Simscape Block Libraries” on page 1-11.
2 Create a
Browse
File me
memory
Note A
promp
comm
Sims
3 Ope
Ele
4 Drag the M ass, Translational Spring, Translational Damper, and two
new model. To do this, click the New button on the Library
r’s too lbar (Windows only) or choose New from the library window’s
nu and select Model. The software creates an empty model in
and displays it in a new model editor window.
lternately, you can type
ssc_new at the M ATLA B Command
t, to create a new model prepopulated with certain required and
only-used blocks. For more information, see “Creating a New
cape Model”.
n the Simscape > Foundation Library > Mechanical > Translational
ments library.
Mechanical Translational Reference blocks into the model window.
Creating a Simple Model
5 Orient the blocks as show n in the following illustration. To rotate a block,
select it and press Ctrl+R.
6 Connect the Translational Spring, Translational Damper, and Mass blocks
to one of the Mechanical Translational Reference blocks as shown in the
next illustration.
1-19
1 Modeling Physical Systems
1-20
7 To add the representation of the f orce acting on the mass, open the
Simscape > Foundation Library > Mechanical > Mechanical Sources library
and add the Ideal Force Source block to your diagram.
To reflect the correct direction of the force shown in the original schematic,
flip the blo ck by selecting Format > Flip Block > Up-Down from the top
menu bar of the model window. Connect the block’s port C (for “case”) to
the second Mechanical Translational Reference block, and its port R (for
“rod”) to the Mass block, as shown below.
Creating a Simple Model
8 Add the sensor to measure sp eed a nd position of the mass. Place the Ideal
Translational Motion S en so r block from the Mechanical Sensors library
into your diagram and co nn ect it as shown below.
1-21
1 Modeling Physical Systems
1-22
9 Now you need to add the sources and scopes. They are found in the regular
Simulink libraries. Open the Simulink > Sources library and copy the
Signal Builder block into the model. Then open the Simulink > Sinks
library and copy two Scope blocks. Rename one of the Scope blocks to
Velocity and the other to Position.
Creating a Simple Model
10 Every time you connect a Simulink source or scope to a Simscape diagram,
you have to use an appropriate converter block, to convert Simulink signals
into p h ysical signals and vice versa. Open the Simscape > Utilities library
and copy a Simulink-PS Converter block and two PS-Simulink Converter
blocks into the model. Connect the blo cks as shown below.
1-23
1 Modeling Physical Systems
1-24
11 Each topologically distinct physical network in a diagram requires
exactly one Solver Configuration block, found in the Simscape > Utilities
library. Copy this block into your model and connect it to the circuit by
creating a branching point and connecting it to the only port of the Solver
Configuration block. Your diagram now should look like this.
Creating a Simple Model
12 Your block diagram is now complete. Save it as simple_mech1.mdl.
Modifying Initial Settings
After you have put together a block diagram of your model, as described in the
previous section, you need to select a solver and provide the correct values
for configuration param eters.
To prepare for simulating the model, follow these steps:
1 Select a Simulink solver. On the top menu bar of the model window,
select Simulation > Configuration Parameters. The Configuration
Parameters dialog box o pens, showing the Solver node.
Under Solver options,setSolver tosize to
0.2.
ode15s (Stiff/NDF) and Max step
1-25
1 Modeling Physical Systems
Also note that Simulation time is specified to be between 0 and 10
seconds. You can adjust this setting later, if needed.
1-26
Click OK to close the Configuration Parameters dialog box.
2 Save the model.
Running the Simulation
After you’ve put together a block diagram and specified the initial settings for
your model, you can run the simulation.
1 The input signal for the force is provided by the Signal Builder block. The
signal profile is shown in the illustrat ion below. It starts with a value of 0,
then at 4 seconds there is a step change to 1, and then it changes back to 0
at 6 seconds. This is the default profile.
Creating a Simple Model
The Velo
output
scopes
2 To run the simulation, clickin the model window toolbar. The Simscape
city scope outputs the mass velocity, and the Position scope
s the mass displacement as a function of time. Double-click both
to open them.
solver evaluates the model, calculates the initial conditions, and runs the
simulation. For a detailed description of this process, see “How Sim scape
Simulation Works” on page 2-2. Completion of this step may take a few
seconds. The message in the bottom-left corner of the model window
provides the status update.
3 Once the simulation starts running, the Velocity and Position scope
windows display the simulation results, as shown in the next illustration.
1-27
1 Modeling Physical Systems
1-28
In the beginning, the mass is at rest. Then at 4 seconds, as the input signal
changes abruptly, the mass velocity spikes in the positive direction and
gradually returns to zero. The mass position at the same time changes
more gradually, on account of inertia and damping, and stays at the new
value as long as the force is acting upon it. At 6 seconds, when the input
signal changes back to zero, the velocity gets a mirror spike, and the mass
gradually returns to its initial position.
Creating a Simple Model
You can now adjust various inputs and block parameters and see their effect
on the mass velocity and displacement.
Adjusting the Parameters
After running the initial simulation, you can experiment with adjusting
various inputs and block parameters.
Try the following adjustments:
1 Change the force profile.
2 Change the model parameters.
3 Change the mass position output units.
Changing the Force Profile
This example shows how a change in the input signal affects the force profile,
and therefore the mass displacement.
1 Double-click the Signal Builder block to open it.
2 Click the first vertical segment of the signal profile and drag it from 4 to 2
seconds, as shown below. Close the block dialog.
1-29
1 Modeling Physical Systems
1-30
3 Run the s
ration.
illust
imulation. The simulation results are shown in the following
Creating a Simple Model
Changing the Model Parameters
In our model, the force acts on a mass against a translational spring and
damper, connected in parallel. This example shows how changes in the spring
stiffness a nd damper viscosity affect the mass displacement.
1 Double-click the Translational Spring block. Set its Spring rate to 2000
.
N/m
1-31
1 Modeling Physical Systems
2 Run the simulation. The increase in spring stiffness results in smaller
amplitude of mass displacement, as shown in the following illustration.
3 Next, double-click the Translational Damper block. Set its Damping
coefficient to
500 N/(m/s).
1-32
4 Run the simulation. Because of the increase in viscosity, the mass is slower
both in reaching its maximum displacement and in returning to the initial
position, as shown in the following illustration.
Creating a Simple Model
Changing the Mass Position Output Units
In our model, we have used the PS-Simulink Converter block in its default
parameter configuration, which does not specify units. Therefore, the
Position scope outputs the mass displacement in the default length units,
that is, in meters. This example shows how to change the output units for the
mass displacement to millimeters.
1 Double-click the PS-Simulink Converter block. Type mm in the Output
signal unit combo box and click OK.
2 Run the
ope axes. The mass displacement is now output in millimeters, as
the sc
shown
simulation. In the
in the following illustration.
Position scope window, clickto autoscale
1-33
1 Modeling Physical Systems
1-34
Modeling Best Practices
In this section...
“Grounding Rules” on page 1-35
“Avoiding Numerical Simulation Issues” on page 1-38
Grounding Rules
This section contains guidelines for using domain-specific ref erence blocks
(such as Electrical Reference, Mechanical Translational Reference, and so
on) in Simscape diagrams, along with examples of correct and incorrect
configurations.
Add reference blocks to your models according to the following rules:
• “Each Domain Requires at Least One Reference Block” on page 1-35
• “Each Circuit Requires at Least One Reference Block” on page 1-36
Modeling Best Practices
• “Multiple Connections to the Domain Reference Are Allowed Within a
Circuit” on page 1-37
Each Domain Requires at Least One Reference Block
Within a physical network, each domain must contain at least one reference
block of the appropriate type. For example, the electromechanical model
shown in the following diagram has both Electrical Reference and Rotational
Reference blocks attached to the appropriate circuits.
1-35
1 Modeling Physical Systems
Each Circuit Requires at Least One Reference Block
Each topologically distinct circuit within a domain must contain at least one
reference block. Some blocks, such as an Ideal Transformer, interface two
parts of the network but do not convey information about signal levels relative
to the reference block. In the following diagram , there are two separate
electrical circuits, and the Electrical Reference blocks are required on both
sides of the Ideal Transformer block.
1-36
Modeling Best Practices
The next diagram would produce an error because it is lacking an electrical
reference in the circuit of the secondary winding.
The following diagram, however, will not produce an error because the
resistor defines the output voltage relative to the ground reference.
Multiple Connections to the Domain Reference Are Allowed
Within a Circuit
More that one reference block m ay be used within a circuit to define multiple
connections to the domain reference:
1-37
1 Modeling Physical Systems
• Electrical conserving ports of all the blocks that are directly connected to
• All translational ports that are rigidly clamped to the frame (ground) must
• All rotational ports that are rigidly clamped to the frame (ground) must be
• Hydraulic conserving ports of all the blocks that are referenced to
For example, the following diagram correctly indicates two separate
connections to an electrical ground.
ground must be connected to an Electrical Reference block.
be connected to a Mechanical Translational Reference block.
connected to a Mechanical Rotational Reference block.
atmosphere (for example, suction ports of hydraulic pum ps, or return ports
of valves, cylinders, pipelines, if they are considered directly connected to
atmosphere) must be connected to a Hydraulic Reference block.
1-38
Avoiding Numerical Simulation Issues
Certain configurations of physical modeling blocks can cause numerical
difficulties or slow down your simulation. When this happens, Simscape
solver issues a warning in the MATLAB workspace and, if it fails to initialize,
a Simscape error.
Modeling Best Practices
In e lectrical circuits, common examples that can cause this behavior include
voltage sources connected in parallel with capacitors, inductors connected in
series with current sources, voltage sources connected in parallel, and current
sources connected in series. Often, the cause of the numerical difficulty is
immediately apparent. For example, tw o voltage sources in parallel must
have identical voltage values; otherwise, the ports connecting them would not
be physical conserving ports. In practical circuits, topologies such as parallel
voltage sources are possible, and small difference in their instantaneous
voltages is possible due to parasitic series resistance.
Note Mathematically, these topologies result in Index-2 differential algebraic
equations (DAEs). Th e ir solu tion requires two differentiations of the
constraint equations and, as such, it is numerically better to avoid these
component topologies where possible.
Therearetwoapproachestoresolvingthesedifficulties.Thefirstistochange
the circuit to an equivalent simpler one. In the example of two parallel voltage
sources, one source can be simply deleted. The same applies to two series
current sources, the deleted one being replaced by a short circuit. For some
circuit topologies, however, it is not possibletofindanequivalentsimplerone
that resolves the problem, and the second approach is needed.
The second approach is to inclu de small parasitic resistances in the
component. In the Simscape Foundation library, the Capacitor and Inductor
blocks include such parasitic terms, so that you can connect capacitances in
parallel with voltage sources and inductors in series with current sources. If
your circuit does not have any such topologies, then you can change the default
parasitic terms to zero. Note that other blocks do not contain these parasitic
terms, for example, the Mutual Inductor block. Therefore, if you wanted to
connect a mutual inductor primary in series with a current source, you would
need to introduce your own parasitic conductance acros s the primary winding.
Example of Using a Parasitic Resistance to Avoid Numerical
Simulation Issues
The following diagram models a differentiator that might be used as part of a
Proportional-Integral-Derivative (PID ) controller. You can open this model by
typing
ssc_differentiator in the MATLAB Command Window.
1-39
1 Modeling Physical Systems
Simulate the model, a nd you will see thattheoutputisminusthederivative
of the input sinusoid.
1-40
Now open the capacitor C block dialog, and set the series resistance to zero.
The model now runs very slowly, and issues a warning:
Warning: problems possible for transient initialization, as well as stepsize control
for transient solve, due to equations of one or more components:
'ssc_differentiator/2V pk-k, 1KHz'
Modeling Best Practices
'ssc_differentiator/Op-Amp'
'ssc_differentiator/C'
The cause of the warning is that the circuit effectively connects the voltage
source in parallel with the capacitor. This is because an ideal op-amp
satisfies
V+ = V- ,whereV+ and V- are the noninverting and inverting inputs,
respectively. This is an example where it is not possible to replace the circuit
with an equivalent simpler one, and a parasitic small resistance has to be
introduced.
1-41
1 Modeling Physical Systems
Modeling Pneumatic Systems
In this section...
“Intended Applications” on page 1-42
“Assumptions and Limitations” on page 1-42
“Fundamental Equations” on page 1-43
“Network Variables” on page 1-44
“Connection Constraints” on page 1-45
“References” on page 1-45
Intended Applications
The Foundation library contains basic pneumatic elements, such as orifices,
chambers, and pneumatic-mechanical converters, as well as pneumatic
sensors and sources. Use these blocks to model p neumatic systems, for
applications such as:
You can also use these blocks to model dry air and low-pressure flows, for
example, for HVAC applications.
Assumptions and Limitations
Pneumatic block models are based on the following assumptions:
• Working fluid is an ideal gas satisfying the ideal gas law.
• Specific heats at constant pressure and constant volume, c
constant.
and cv,are
p
Modeling Pneumatic Systems
• Processes are adiabatic, that is, there is no heat transfer between
components and the environment (except for components with a separate
thermal port).
• Gravitational effects can be neglected, that is, underlying equations contain
no head pressures due to gravity.
Fundamental Equations
The energy balance for a control volume [1] is
22
⎛
i
⎜
⎜
22
⎝
⎞
⎞
⎟
i
⎟
⎠
⎛
⎛
v
⎟
⎜
−++
∑
⎟
⎠
o
⎜
⎝
⎜
oo
⎜
⎝
o
g
zz
⎞
⎞
⎟
⎟
o
⎟
⎟
⎠
⎠
dE
cv
=−+++
QW mhvgzmh
dt
cvcvii
∑
⎛
⎜
⎜
i
⎝
where
E
cv
Q
cv
W
cv
h
i,ho
v
i,vo
g
z
i,zo
m
i,mo
The
tes that the rate of energy increase or decrease within the control volume
sta
als the difference between the rates of energy transfer in and out across the
equ
ndary. The mechanisms of energy transfer are heat and work, as for closed
bou
stems, and the energy that accompanies the mass entering and exiting.
sy
Control volume total energy
Heat energy per second added to the gas through the boundary
Mechanical w ork per second performed by the gas
Inlet and outlet enthalpies
Gas inlet and outlet velocities
Acceleration due to gravity
Elevations at inlet and outlet ports
Mass flow rates in and out of the control volume
equation is an accounting balance for the energy of the control volume. It
eumatic block models make several simplifying assumptions, as described
Pn
eviously.
pr
1-43
1 Modeling Physical Systems
The ideal gas law relates pressure, density, and temperature:
where
pRT=ρ
p
ρ
R
T
Also, the specific enthalpies for an ideal gas at temperature T and constant
pressure and constant volume are given by:
hcT
hcT
The pneumatic components also use the mass continuity equation:
d
where ρ is the density of the gas within the component. For components with
no internal mass of gas, the equation simplifies to:
Gm m
Absolute pressure
Gas density
Specific gas constant
Absolute gas temperature
=
p
=
v
ρ
1
mm
=−
()
dtV
==
io
io
1-44
where G isthemassflowratethroughthecomponent.
For specific equations used in each block, see the block reference pages.
Network Variables
The Across variables are pressure and temperature, and the Through
variables are mass flow rate and heat flow. Note that these choices result in
Modeling Pneumatic Systems
a pseudo-bond graph, because the product of pressure and mass flow rate
is not power.
Connection Constraints
Every node in a pneumatic network must have a defined temperature as
well as pressure. This rule places some constraints on how you connect
the pneumatic elements. In effect, every node should have a volume of
fluid associated with it. When the ideal gas law is applied, this volume
of fluid determines the relationship between temperature and pressure.
Some elements already have a volume of fluid associated with them, and
therefore having just one of these components connected to a node satisfies
this condition. Such blocks include Constant Volume Pneumatic Chamber,
Pneumatic Piston Chamber, Rotary Pneumatic Piston Chamber, and
Pneumatic Atmospheric Reference.
Anexceptiontotheaboverule(thateverynodemusthaveavolumeoffluid
associated with it) occurs when two nodes are connected by a component for
which the heat equation says that the temperatures are equal. In this case,
just one of the nodes needs to be connected to a component with associated
volume of fluid. Such components include the pressure and flow rate sources.
For models that represent an actual pneumatic network, these constraints
should have no impact. For example, connecting two orifices in series makes
no physical sense because the underlying assumption of the orifice equation
is that gas is discharged into a volume of fluid. Therefore, modeling actual
physical systems should automatically satisfy these constraints.
References
[1] Moran M.J. and Shapiro H.N. Fundamentals of Engineering
Thermodynamics. Second edition. New York: John Wiley & Sons, 1992.
1-45
1 Modeling Physical Systems
1-46
2
Simulating Physical Models
• “How Simscape Simulation Works” on page 2-2
• “Working with Solvers” on page 2-8
• “Troubleshooting Simulation Errors” on page 2-13
• “Finding an Operating Point” on page 2-22
• “Linearizing at an Operating Point” on page 2-28
• “Generating Code” on page 2-35
• “Limitations” on page 2-39
2 Simulating Physical Models
How Simscape Simulation Works
In this section...
“Simscape Simulation Phases” on page 2-2
“Model Validation” on page 2-4
“Network Construction” on page 2-4
“Equation Construction” on page 2-5
“Computing Initial Conditions” on page 2-5
“Performing Transient Initialization” on page 2-6
“Transient Solve” on page 2-6
Simscape Simulation Phases
Simscape software gives you multiple ways to simulate and analyze physical
systems in the Simulink environment. Running a physical model simulation
is similar to running a simulation of any other Simulink model. It entails
setting various simulation options, starting the simulation, and viewing the
simulation results. See the Using Simulink documentation for a gene ral
discussion of these topics. This chapter focuses on aspects of simulation
specific to Simscape and Sim Hydraulics models. Refer to the SimMechanics™
and SimDriveline™ documentation for specifics of simu l ating and analyzing
SimMechanics and SimDriveline models.
2-2
You might find this brief overview helpful for constructing models and
understanding errors.
Simscape simulation seq uence is shown in the following flow chart.
How Simscape™ Simulation Works
It consists of the following major phases:
1 “Model Validation” on page 2-4
2 “Network Construction” on page 2-4
3 “Equation Construction” on page 2-5
4 “Computing Initial Conditions” on page 2-5
2-3
2 Simulating Physical Models
Model Validation
Simscape solver first validates the m odel configuration and checks your data
entries from the block dialogs. In particular:
• Each topologically distinct physical network in a diagram requires exactly
• If your model contains hydraulic elements, each topologically distinct
5 “Performing Transient Initialization” on page 2-6
6 “Transient Solve” on page 2-6
one Solver Configuration block.
hydraulic circuit in a diagram requires a Custom Hydraulic Fluid block
(or Hydraulic Fl u id block, available with S imHydraulics block libraries)
to be connected to it. These blocks define the fluid properties that act as
global parameters for all the blocks connected to the hydraulic circuit. If
no hydraulic fluid block is attached to a loop, the hydraulic blocks in this
loop use the default fluid. However, more than one hydraulic fluid block in
a loop generates an error.
2-4
Similarly, if your model contains pneumatic elements, default gas
properties fo r a pne umatic netw ork are for dry air and ambient conditions
of 101325 Pa and 20 degrees Celsius. Attaching a Gas Properties block to a
pneumatic circuit lets you change gas properties and ambient conditions
for all the blocks connected to the circuit. However, more than one Gas
Properties block in a pneumatic circuit generates an error.
• Signal units specified in a Simulink-PS Converter block must match
the input type expected by the Simscape block connected to it. For
example, when you provide the input signal for an Ideal Angular Velocity
Source block, specify angular velocity units, such as
Simulink-PS Converter block, or leave it unitle ss. Similarly, units specified
in a PS-Simulink Converter block must match the type of physical signal
provided by the Simscape block outport.
rad/s or rpm,inthe
Network Construction
After validating the model, Simscape solver constructs the physical network
based on the following principles:
• Two directly connected Conserving ports have the sam e values for all their
Across variables (such as voltage or angular velocity).
How Simscape™ Simulation Works
• Any Through variable (such as current or torque) transferred along
the Physical connection line is divided among the multiple components
connected by the branches. For each Through variable, the sum of all its
values flowing into a branch point equals the sum of all its values flowing
out.
Equation Construction
Based on the network configuration, the parameter value s provided in the
block dialogs, and the global parameters defined by the fluid properties, if
applicable, Simscape solver constructs the system of equations for the model.
These equations contain variables of the following types:
variables are the independent s tates for simulation.
• Algebraic — Time d erivative of this variable does not appear in equations.
Algebraic variables a re always dependent (on dynamic variables, other
algebraic variables, or inputs).
Computing Initial Conditions
Simscape solver computes the initial conditions only once, in the beginning of
simulation (t=0).
Initial conditions are computed by se tting all dynamic variables to 0, except
those corresponding to blocks that have an initial condition field in their
block dialogs, and solving for all the system variables. The blocks with initial
conditions have their dynamic variables set according to the user-provided
value in the block dialog. In itial conditions can only be set on dynamic
variables, because these are the independent states for simulation. For
example, the Translational Spring block has the Initial deformation
parameter, so the corresponding spring position state is set to the initial offset
specified in the block dialog. Refer to the block reference documentatio n to
find which blocks have initial con ditions specified through their dialogs.
It is required that the initial conditions for dependent dynamic states be set
consistently. For example, the initial voltages on two parallel capacitors must
be equal. When the solver detects dependent dynamic variables, it performs
2-5
2 Simulating Physical Models
a check and issues an error if the initial conditions on dynamic states are
not set consistently.
This concludes the initial conditions computation when the Start simulationfrom steady state check box in the Solver block dialog box is not selected
(this is the default).
When this box is selected, the solver attempts to find the steady state that
would result if the inputs to the system were held constant for a sufficiently
largetime,startingfromtheinitialstateobtainedfromtheinitialconditions
computation, described previously. Although the solver tries to find the
particular steady state resulting from the given initial conditions, it is
not guaranteed to do so. All that is guaranteed is that if the steady-state
solve succeeds, the state found is a steady state (within tolerance). Steady
state means that the system variables are no longer changing with time.
Simulation then starts from this steady state.
Note If the simulation fails at or near the start time when you use the Start
simulation from steady state option, consider clearing the check box and
simulating with the plain initial conditions computation only.
2-6
Performing Transient Initialization
After computing the initial conditions, or after a subsequent event (such as
a discontinuity resulting, for example, from a valve opening, or a hard stop
hitting the stop), Simscape solver performs transient initialization. This is
done by fixing all dynamic variables and solving for algebraic variables and
derivatives of dynamic va riables. The goal of transient initialization is to
provide a consistent set of initial conditions for the next transient solve phase.
Transient Solve
Finally, Simscape solver performs transient solve of the system of equations.
In transient solve, continuous differential equations are integrated in time
to compute all the variables as a function of time.
Simscape solver continues to perform the simulation according to the results
of the transient solve until it encounters an event, such as a zero crossing or
How Simscape™ Simulation Works
discontinuity. The event may be within the physical network or elsewhere in
the Simulink mo de l. If an event is encountered, Simscape solver returns to
the phase of transient initialization, and then back to transient solve. This
cycle continues until the end of simulation.
2-7
2 Simulating Physical Models
Working with Solvers
In this section...
“Selecting a Solver” on page 2-8
“Input Filtering” on page 2-10
Selecting a Solver
It is possible to choose any variable-step or fixed-step solver for models
containing Simscape blocks. However, implicit solvers, such as ode14x,
ode23t, and ode15s, are a better choice for a typical model. In particular,
for stiff systems, implicit solvers typically take many fewer timesteps than
explicit solvers, such as ode45, ode113, and ode1.
When you first create a m odel, the default Simulink solver is ode45. To select
a different solver, follow a procedure similar to th at in “Modifying Initial
Settings” on page 1-25.
2-8
If you do not modify the default solver and your system is stiff, your
performancemaynotbeoptimal. Toalert you to a potential issue, the system
issues a warning when you use an explicit solver in a model containing
Simscape blocks. You can turn off this default warning or changed it to an
error for a particular m odel, by following these steps:
1 From the top menu bar in the model window, select Simulation >
Configuration Parameters. The Configuration Parameters dialog box
opens.
2 In the left pane of the Configuration Parameters dialog box, select
Simscape.
Working with Solvers
3 Select the desired option from the Explicit solver used in model
warning — Makes the system issue a warning upon simulation if the
model uses an explicit solver. This is the default option, design ed to alert
you to a potential issue if you use the default solver.
•
error — Makes the system issue an error upon simulation if the model
uses an explicit solver. If your model is stiff, and the use of explicit
solvers undesirable, you may choose to select this option to avoid
troubleshooting errors in the future.
•
none — Turns off issuing a warning or error upon simulation with
explicit solver. For models that are not stiff, explicit solvers can be
effective, often taking fewer timesteps than implicit solvers. If you work
with such models and use expli c it solvers, select this option to tu rn off
the warning upon simulation.
2-9
2 Simulating Physical Models
Input Filtering
If you use an explicit solver, you may need to provide time derivatives of
some of the input signals. By default, needed input derivatives are provided
by filtering the input through a low-pass filter. The derivative of the filtered
input can then be computed by the Physical Networks simulation engine.
You can control the way you provide time derivatives for each input signal by
configuring the Simulink-PS Converter block connected to it:
4 Click OK.
1 Double-click the Simulink-PS Converter block to open its dialog box.
2 Click the Derivatives tab.
2-10
Working with Solvers
3 To avoid filtering the input signal, set Input derivatives parameter to
First derivative of input user-provided.
When you select this option, a second Simulink input port appears on the
Simulink-PS Conve rter block, to let you connect the signal providing input
derivatives. Input filtering is then turned off.
4 If you cannot provide the first derivative of the input signal as an additional
input signal to the Simulink-PS Converter block, leave the Input
derivatives parameter set to
No user-input provided derivatives.In
this case, however, it is important to set the appropriate Input filtering
time constant parametervalueforyourmodel.
The filter time constant controls the filtering of the input signal. Th e
filtered input follows the true input but is sm oothed, with a lag on the order
ofthetimeconstantchosen. Youshouldsetthetimeconstanttoavalue
no larger than the smallest time interval of interest in the system. The
trade-off in choosing a very small time constant is that the filtered input
signal will be closer to the true input signal, at the cost of increasing the
stiffness of the system and slowing down the simulation.
Because input filtering can appreciably change the input signal and
drastically affect simulation results if the time constant is too large, a
warning is issued when input filtering is u sed. Th e warning indicates w hich
Simulink-PS Conve rter blocks have their input signals filtered. You can turn
off this warning (or change it to an error) by changing the preferences on the
Simscape pane of the Configuration Parameters dialog box:
1 From the top menu bar in the model window, select Simulation >
Configuration Parameters. The Configuration Parameters dialog box
opens.
2 In the left pane of the Configuration Parameters dialog box, select
Simscape.
2-11
2 Simulating Physical Models
2-12
3 Select the desired option from the Input filtering used in model
warning — Makes the system issue a warning upon simulation if the
model uses input filtering. The warning contains a list of Simulink-PS
Converter blocks that use input filtering. This is the default option.
•
error — Makes the system issue an error upon simulation if the model
uses input filtering. If you select this option and use an explicit solver,
youhavetoprovidefirstderivativeoftheinputsignalasanadditional
input signal to each Simulink-PS Converter block. For details, see the
Simulink-PS Converter block reference page.
•
none — Turns off issuing a warning or error upon simulation when the
model uses input filtering.
4 Click OK.
Troubleshooting Simulation Errors
In this section...
“Troubleshooting Tips and Techniques” on page 2-13
“System Configuration Errors” on page 2-14
“Numerical Simulation Issues” on page 2-17
“Initial Conditions Solve Failure” on page 2-19
“Transient Simulation Issues” on page 2-20
Troubleshooting Tips and Techniques
Simscape simulations can stop before completion with one or more error
messages. This section discusses generic error types and error-fixing
strategies. You might find the previous s ection, “How Simscape Simulation
Works” on page 2-2, useful for identifying and tracing errors.
Troubleshooting Simulation E rrors
If a simulation failed:
• Review the model configuration. If your error message contains a list of
blocks, look at these blocks first. Also look for:
- Wrong connections — Verify that the model makes sense as a physical
system. For example, look for actuators connected against each other,
so that they try to move in opposite directions, or incorrect connections
to re fere nce nodes that prevent movement. In electrical circuits, verify
polarity and connections to ground.
- Wrong units — Simscape unit manager offers great flexibility in using
physical units. However, you must exercise care in specifying the
correct units, especially in the Simulink-PS Converter and PS-Simulink
Converter blocks. Start analyzing the circuit by opening all the converter
blocks and checking the correctness of specified units.
• Try to simplify the circuit. Unnecessary circuit complexity is the most
common cause of simulation errors.
• Break the system into subsystems and test e very unit until you are positive
that the unit behaves as expected.
2-13
2 Simulating Physical Models
• Build the system by gradually increasing its complexity.
The MathWorks recommends that you build, simulate, and test your model
incrementally. Start with an idealized, simplified model of your system,
simulate it, verify that it works the way you expected. Then incrementally
make your model more realistic, factoring in effects such as friction loss,
motor shaft compliance, hard stops , and the other things that describe
real-world phenomena. Simulate and test your model at every incremental
step. Use subsystems to capture the model hierarchy, and simulate and test
your subsystems separately before testing the whole model configuratio n.
This approach helps you keep your models well organized and makes it easier
to troubleshoot them.
System Configuration Errors
• “Missing Solver ConfigurationBlock”onpage2-14
• “Extra Fluid Block or Gas Properties Block” on page 2-14
• “Missing Reference Block” on page 2-15
2-14
• “Basic Errors in Physical System Representation” on page 2-15
Missing Solver Configuration Block
Each topologically distinct Simscape block diagram requires exactly one
Solver Configuration block to be connected to it. The Solver Con f ig ura t ion
block specifies the global environment information and provides parameters
for the solver that your model needs before you can begin simulation.
If you get an error message about a missing Solver Configuration block,
open the Simscape Utilities library and add the Solver Configuration block
anywhere on the circuit.
Extra Fluid Block or Gas Properties Block
If your model contains hydraulic elements, each topologically distinct
hydraulic circuit in a diagram requires a Custom Hydraulic Fluid block
(or Hydraulic Fluid block, available with SimHyd ra ul ics block libraries)
to be connected to it. These blocks define the fluid properties that act as
global param eters for all the blocks connected to the hydraulic circuit. If no
Troubleshooting Simulation E rrors
hydraulic fluid block is attached to a loop, the hydraulic blocks in this loop
use the default fluid. However, more than one hydraulic fluid block in a loop
generates an error.
Similarly, more than one Gas Properties block in a pneumatic circuit
generates an error.
If you get an error message about too many domain-specific global parameter
blocks attached to the network, look for an extra Hydraulic Fluid block,
Custom Hydraulic Fluid block, or Gas Properties block and remove it.
Missing Reference Block
Simscape libraries contain domain-specific reference blocks, which represent
reference points for the conserving ports of the appropriate type. For
example, each topologically distinct electrical circuit must contain at least
one Electrical Reference block, which represents connection to ground.
Similarly, hydraulic conserving ports of all the blocks that are referenced
to atmosphere (for example, suction ports of hydraulic pumps, or return
ports o f valves, cylinders, pipelines, if they are considered directly connected
to atmosphere) must be connected to a Hydraulic Reference block, which
represents connection to atmospheric pressure. Mechanical translational
ports that are rigidly clamped to the frame (ground) must be connected to a
Mechanical Translational Reference block, and so on.
If you get an error message about a missing reference block, or node, check
your system configuration and add the appropriate reference block based
on the rules described above. For more information and examples of best
modeling practices, see “Grounding Rules” on page 1-35.
Basic Errors in Physical System Representation
Physical systems are represented in the Simscape modeling environment
as Physical Networks according to the Kirchhoff’s generalized c i rcu it laws.
Certain model configuratio ns violate these laws and are therefore illegal.
There are tw o broad violations:
• Sources of domain-specific Across variable connected in parallel (for
example, voltage sources, hydraulic pressure sources, or velocity sources)
2-15
2 Simulating Physical Models
• Sources of domain-specific Through variable connected in series (for
These configurations are impossible in the real world and illegal theoretically.
If your model contains such a configuration, upon simulation the solver issues
an error followed by a lis t of blocks, as shown in the following ex ample.
Example. The model shown in the following illustration contains two Ideal
Translational Velocity Sources co n nected in parallel. This produces two
independent velocity loops, and the solver cannot construct a consistent
system of equations for the circuit.
example, electric current sources, hydraulic flow rate sources, force or
torque sources)
2-16
When you t ry to simulate the model, the solver issues the following error
messages:
Nonlinear solver: failed to converge, residual norm too large.
Transient initialization, solving for consistent states and modes, failed to converge.
Warning: equations of one or more components may be dependent or inconsistent. This can
cause problems in transient initialization. Here is the set of components involved:
You can simplify the system by using a single Ideal Translational Velocity
Source block, with its control signal supplied by the Sine Wave block. Add the
constant value from the second source to the bias of the sine wave.
Numerical Simulation Issues
• “Dependent Dynamic States” on page 2-17
• “Parameter Discontinuities” on page 2-19
Numerical simulation issues can be either a result of certain circuit
configurations or of parameter discontinuities.
Dependent Dynamic States
Certain circuit configurations can result in dependent dynamic states, or the
so-called higher-index differential algebraic equations (DAEs). Simscape
solver can handle dependencies among dynamic states that are linear in
the states and independent of time and inputs to the system. For example,
capacitors connected in parallel or inductors connected in series will not cause
any problems. Other circuit configurations with dependent dynamic states,
in certain cases, may slow down the simulationorleadtoanerrorwhenthe
solver fails to initialize.
In e lectrical circuits, common examples that can cause this behavior include
voltage sources connected in parallel with capacitors, inductors connected in
series with current sources, and so on. To address this issue, the Capacitor
and Inductor blocks include parasitic terms (parallel conductance and series
resistance). For other blocks that do not contain these parasitic terms, you
might need to introduce your own parasitic conductance or resistance into
the circuit. For more information on best modeling practices, as well as for
troubleshooting suggestions, see “Avoiding Numerical Simulation Issues”
on page 1-38.
Examples in other domains include direct connections between a velocity
source and a mass, a force source and a spring, a pressure source and a
2-17
2 Simulating Physical Models
hydraulic accumulator, or a flow rate source and a fluid inertia. If you
encounter this error, try to either simplify th e circuit or include addition al
blocks, such as spring-damper combinations or constant orifices, to avoid the
direct connection that results in dependent states.
Example. The model shown in the following illustration contains an Ideal
Translational Velocity Source directly connected to a Mass.
2-18
When you t ry to simulate the model, the solver issues the following error
messages:
Nonlinear solver: failed to converge, residual norm too large.
Transient initialization, solving for consistent states and modes, failed to converge.
Warning: problems possible for transient initialization, as well as stepsize control
for transient solve, due to equations of one or more components:
You can try adding a very stiff spring between the velocity source and the
mass. To avoid the possibility of high-frequency oscillations introduced by the
spring, connect it in parallel with a damper with a high damping coefficient.
Parameter Discontinuities
Nonline
to nume
issues
“Trans
Initi
The in
condi
poss
• Syst
ar parameters, dependent on time or other variables, may also lead
rical simulation issues as a result of parameter discontinuity. These
usually manifest themselves a t the transient initialization stage (see
ient Simulation Issues” on page 2-20).
al Conditions Solve Failure
itial conditions solve, which solves for all system variables (with initial
tions specified on some system variables), may fail. This has several
ible causes:
em configuration error. In this case, the Simulation Diagnostics
ow usually contains additional, more specific, error messages, such
wind
missing reference node, or a warning about the component equations,
as a
lowed by a list of components involved. See “System Configuration
fol
ors” on page 2-14 for more information.
Err
2-19
2 Simulating Physical Models
• Dependent dynamic state. In this case, the Simulation Diagnostics
• The constraint residual tolerance may be too tight to produce a consistent
If the Simulation Diagnostics window has other, more specific, error
messages, address them first and try rerunning the simulation. See also
“Troubleshooting Tips and Techniques” on page 2-13.
Transient Simulation Issues
• “Transient Initialization Not Converging” on page 2-20
• “Step-Size-Related Errors” on page 2-21
window also may contain additional, more specific, error m ess ages,
such as a warning about the component equations, followed by a list of
components involved. See “Dependent Dynamic States” on page 2-17 for
more information.
solution to the algebraic constraints at the beginning of simulation. You
can try to increase the Constraint Residual Tolerance parameter v a lue
(that is, relax the tolerance) in the Solver Configuration block.
2-20
Transient initialization h appens at the beginning of simulation (after
computing the initial conditions) or after a subsequent event, such as a
discontinuity (for example, when a hardstophitsthestop). Itisperformed
by fixing all dynamic variables and solving for algebraic variables and
derivatives of dynamic va riables. The goal of transient initialization is to
provide a consistent set of initial conditions for the next transient solve step.
Transient Initialization Not Converging
Error messages stating that transient initialization failed to converge, or that
a set of consistent initial conditions could not be generated, indicate transient
initialization issues. They can be a result of parameter discontinuity.
Review your model to find the possible sources of discontinuity. See also
“Troubleshooting Tips and Techniques” on page 2-13.
You can also try to decrease the Constraint Residual Tolerance parameter
value (that is, tighten the tolerance) i n the Solver Configuration block.
Troubleshooting Simulation E rrors
Step-Size-Related Errors
A typical step-size-related erro r message may state that the system is unable
to reduce the step size without violating the minimum step size for a certain
number of consecutive times. This error message indicates numerical
difficulties in solving the Differential Algebraic Equations (DAEs) for the
model. This might be caused by dependent dynamic states (higher-index
DAEs) or by the high stiffness of the system. You can try the following:
• Tighten the solver tolerance (decrease the Relative Tolerance parameter
value in the Configuration Parameters dialog box)
• Specify a value, other than
auto,fortheAbsolute Tolerance parameter
in the Configuration Parameters dialog box. Experiment with this
parameter value.
• Tighten the residual tolerance (decrease the Constraint Residual
Tolerance parameter value in the Solver Configuration block)
• Increase the value of the Number of consecutive min step size
violations allowed parameter in the Configuration Parameters dialog box
(set it to a value greater than the number of consecutive step size violations
given in the error message)
• Review the model configuration and try to simplify the circuit, or add small
parasitic terms to your circuit to avoid dependent dynamic states. For more
information, see “Numerical Simulation Issues” on page 2-17.
2-21
2 Simulating Physical Models
Finding an Operating Point
In this section...
“What Is an Operating Point?” on page 2-22
“How to Find Operating Points” on page 2-23
“Finding Operating Points with Simscape, Simulink, and Related Products”
on page 2-24
What Is an Operating Point?
An operating point of a sys tem is a dynamic configuration that satisfies design
and use requirements called operating specifications. You can express such
operating specifications as requirements on the system state x and inputs u.
It is not always possible t o find a dynamic state that satisfies all operating
conditions. Also, a system might have multiple operating points satisfying
thesamerequirements.
2-22
Operating points are essential for designing and implementing system
controllers. You can optimize a system at an operating point for performance,
stability, safety, and reliability.
The most important and common type of operating point is a steady state,
where some or all of the system dynamic variables are constant.
Using Operating Points for Linearization
An important motive for finding operating points is linearization,which
determines the system response to small disturbances at an operating point.
Linearization results influence the design of feedback controllers to govern
dynamic behavior near the operating point. A full linearization analysis
requires one or more system outputs, y , in addition to inputs.
See “Linearizing at an Operating Point” on page 2-28.
Example
A pilot flying an aircraft wants to find, for a given environment, a state of the
aircraft engine and control surfaces that produces level, constant-velocity, and
Finding an Operating Point
constant-altitude flight relative to the ground. The requirements of "level,"
"constant velocity," "constant altitude," and "relative to the ground" constitute
operating specifications. This operating point is a steady state of the aircraft
velocity, altitude, and orientation in space.
How to Find Operating Points
You can provide predefined state and input vectors, x0and u0,tospecify
an operating point. If you do not know an operating point in advance, you
have two methods of identifying an operating point that satisfies operating
specifications.
• “Time-Based Search” on page 2-23: Observing the actual or simulated
behavior of the system in time is more general, but less precise, and usually
requires a trial-and-error p rocess to find a precise operating point.
• “State-Based Search” on page 2-23: If you know the system dynamics, you
can solve for steady states, at least in principle.
Time-Based Search
You can sometimes find operating points and steady states by trial and error
while operating or simulating over some length of time and varying the
system parameters, inputs, and initial conditions. In such a time-based
approach, you isolate and study instants or intervals of time when a system
satisfies the operating specifications. The system state and inputs under
those conditions constitute the operating point, which you can also specify
by an operating or simulation time.
State-Based Search
The alternative to trial-and-error searching for steady states is trimming.
In this state-based approach, you bypass time-based simulation and find
solutions for inputs, outputs, states, and state derivatives satisfying an
operating specification. Trimming specifies inputs and part of a state and
solves the system dynamics for the re st of the state. The resulting full state
and input vectors, x
There is no general guarantee that such solutions, x
specifications and inputs, u
and u0, constitute the operating point.
0
, exist for given operating
.
0
0
2-23
2 Simulating Physical Models
Checking Discrete System States
An operating point includes the state of discrete system variables that
change in a discontinuous way. In general, you cannot find these states by
small, continuous changes of system variables. Such states usually require
systematic exploration of the discrete variables over the full range of their
possible values.
Finding Operating Points with Simscape, Simulink,
and Related Products
You have a number of ways to find an operating point in a Simscape model.
You can impose operating specifications a nd isolate operating points using
Simscape and Simulink features and, in some cases, with such related
products as Simulink
software. The full state vector of your model contains:
• Simulink components, which can be continuous or discrete.
• Simscape components, which are continuous.
®
Control Design™ and Control System Toolbox™
2-24
Tip Whichever m ethod that you choose to find an operating point, if you want
to use it for linearization, you must save the operating point information in
the form of a simulation time t
or an operating point object.
,astatevectorx0,andaninputvectoru0,
0
Simulating in Time to Search for an Operating Point
One way to identify operating points is to simulate your model and inspect its
state x and output y as a time series.
1 In your Simscape model, set up sensor outputs for whatever block outputs
you want to observe.
2 Connect Scope blocks, To Workspace blocks, or both, to your Simscape
block outputs to observe and record simulation behavior.
3 In the Data Import/Export pane of your model Configuration Parameters
settings, select the Time, States,andOutput check boxes to record this
simulation information in your workspace.
Finding an Operating Point
Using the Simscape Steady-State Solver
Most commonly, the operating point that you want is a steady state. You have
a precise method for identifying steady states with the Simscape steady-state
solver, which allows you to isolate steady states more exactly than you can
with ordinary simulation. It is particularly recommended for isolating steady
states of a strongly nonlinear character. You can search for multiple steady
states with the steady-state solver by varying the model inputs, parameters,
and initial conditions.
TheSimscapesteady-statesolverinitializes the system and inputs first,
then determines a steady state. In general, the system does not remain in
this initial steady state x(t=0) = x
inputs u change independently, and the system has to respond by changing
its state x(t).
To implement the steady-state solver:
1 In each, some, or all of the physical networks in your Simscape model,
open the Solver Configuration block.
during simulation, because the system
0
2 In each block dialog box, select the Start simulation from steady state
check box.
3 In the model Configuration Parameters settings, on the Data
Import/Export pane, select the States check box to record the time series
of x values in your workspace.
If you also have input signals u in the model, you can capture those inputs
by connecting To Workspace blocks to the input Simulink signal lines.
4 Close these dialog boxes and start simulation.
The first vector of values x(t=0) that you capture during simulation reflects
the steady state x
that the Simscape solver identified.
0
2-25
2 Simulating Physical Models
Using Simulink Control Design Techniques
Note The techniques described in this section require the Simulink Control
Design product. You must use the features of this product on the Simulink
lines in your model, not directly on Simscape physical network lines or blocks.
The following methods are state-based, allowing you to impose operating
specifications, and work well for simple to moderately complex Simscape
models. The MathWorks™ does not recommend these methods for highly
complex Simscape models.
To find operating points, use the
where necessary. Create an operating specification object with
then compute an operating point object with
attempts to find an operating point that satisfies the operating specifications
and reports on its success or failure. If the search is successful,
returns state values satisfying the operating specifications.
You have several choices for operating specifications for the components of
the state vector.
Assumed
Operating
Condition
Default
NondefaultRequest any value you want independently for each
Nondefault
Operating Specification
Request that all state component derivatives be zero.
This is a steady-state for the whole model, not just a
Simscape network within the model.
state component.
Request that a particular state component derivative
be zero.
This is a steady-state condition for that state
component.
operspec an d findop functions, customizing
operspec,
findop.Thefindop function
find_op
2-26
Finding an Operating Point
Additional Simulink Control Design Methods. Instead of the command
line interface, you can use the associated graphical user interface, through
the model menu bar: Tools > Control Design > Linear Analysis.Formore
details on the use of operating point specification objects, related functions,
and the graphical interface, see the Simulink Control Design documentation.
Using Sources to Find Operating Points Not Recommended
You can impose an operating specification on part of a Simscape model by
inserting source blocks from the Simscape Foundation Library. These impose
specified values of system variables in parts of the model. You can simulate
and save the state vector.
However,youcannotobtainanoperatingpointfortheoriginalsystem
(without the source blocks) by saving the state values from the model and
then remo ving the source blocks. In general, the number, order, and identity
of state components change after adding and removing Simscape blocks in
a model.
Simulink trim Function Not Supported with Simscape Models
The Simulink trim function is not supported for models containing Simscape
components.
2-27
2 Simulating Physical Models
Linearizing at an Operating Point
In this section...
“What Is Linearization?” on page 2-28
“How to Lin earize a Model” on page 2-30
“Linearizing a Model with Simscape, Simulink, and Related Products” on
page 2-30
“References” on page 2-34
What Is Linearization?
Determining the response of a system to small perturbations at an operating
point is a critical step in system and controller design. Once you find an
operating point, you can linearize the model about that operating point to
explore the response and stability of the system. To find an operating point in
a Simscape model, see “Finding an Operating Point” on page 2-22.
2-28
Choosing a Good Operating Point for Linearization
Although steady-state and other operating points (state x0and inputs u0)
might exist for your model, that is no guarantee that such operating points are
suitable for linearization. The critical question is: how good is the l inearized
approximation compared to the exact system dynamics?
• When perturbed slightly, a problematic operating point might exhibit
strong asymmetries, with strongly nonlinear behavior when perturbed in
certain ways and smoother behavior in other ways.
• Small perturbations might change discrete states in a large, discontinuous
way that violates the linear approximation.
Operating points with a strongly nonlinear or discontinuous character are not
suitable for linearization. You should analyze them in full simulation and
perturb the system by varying its inputs, parameters, and initial conditions.
Linearizing at an Operating Point
Tip A reliable way to check for such an unsuitable operating point is to
linearize a t several nearby operating points. If the results differ greatly, the
operating point is strongly nonlinear.
What Is Linear Response?
Near an operating point, you can express the system state x, inputs u,and
outputs y relative to that operating point in terms of x – x
y
. For convenience, shift the vectors by subtracting the operating point:
0
x – x
→ x,etc.
0
If the system dynamics does not explicitly depend on time and the operating
point is a steady state, the system response to state and input perturbations
near the steady state is approximately governed by a linear time-invariant
(LTI) state space model:
dx/dt = A·x + B·u
, u – u0,andy –
0
y = C·x + D·u.
The matrices A, B, C, D have components and structures that are independent
of the simulation time. A system is stable to changes in state at an operating
point if the eigenvalues of A are negative.
If the operating point is not a steady state or the system dynamics depends
explicitly on time, the linearized dynamics near the operating point is more
complicated. The matrices A, B, C, D are not constant and depend on the
simulation time t
, as well as the operating point x0and u0[1].
0
Tip While you can linearize a closed system with no inputs or outputs and
obtain a nonzero A matrix, obtaining a nontrivial linearized input-output
model requires at least one input component in u and one output component
in y.
2-29
2 Simulating Physical Models
Example
A pilot is flying, or simulating, an aircraft in level, constant-velocity, and
constant-altitude flight relative to the ground, with a known environment. A
crucial question for the aircraft pilot and designers is: will the aircraft return
to the steady state if perturbed from it by a disturbance, such as a wind
gust — in other words, is this steady state stable? If the operating point is
unstable, the aircraft trajectory can diverge from the steady state, requiring
human or automatic intervention to maintain steady flight.
How to Linearize a Model
Once you know an operating point, you have three practical methods for
investigating the system response to small disturbances.
Full Simulation- or Operation-Based Perturbations
You can experiment with the system or a system simulation by making
repeated, different, and slight changes to the system parameters, inputs,
and initial conditions, while operating at a steady state. This method
requires costly trial and error and generates uncontrolled and imprecise
approximations.
2-30
Analytic Approximations to Known State Dynamics
If you know the system state dynamics and an operating point x0and u0in
analytic form, you can apply standard approximation techniques to derive an
analytic form for the A, B, C, D matrices.
Numerical Approximations to Known State Dynamics
If you have a controlled numerical approximation to your system state
dynamics and operating point, you can apply standard computational
techniques to generate numerical approximations to the A, B, C, D matrices.
Linearizing a Model with Simscape, Simulink, and
Related Products
Use the following methods to create numerical linearized state-space models
from a model containing Simscape components .
Linearizing at an Operating Point
Independent Versus Dependent States
An important difference from normal Simulink models is that the states in a
physical network are not independent in general, because some states have
dependencies on other states through constraints.
• The independent states are a subset of system variables and consist of
Simscape dynamic variables and Simulink states.
• The dependent states consist of Simscape algebraic variables and
dependent (constrained) dynamic variables.
For more information on Simscape dyna m ic and algebraic variables, see “How
Simscape Simulation Works” on page 2-2.
The only components of the A, B, C , D matrices that can be nonzero are those
corresponding to independent states.
• The
A matrix, of size n_states by n_states,isallzerosexceptfor
asubmatrixofsize
n_ind by n_ind,wheren_ind is the number of
independent states.
• The
• The
• The
B matrix, of size n_states by n_inputs,isallzerosexceptfora
submatrix of size
C matrix, of size n_outputs by n_states,isallzerosexceptfora
submatrix of size
D ma trix, of size n_outputs by n_inputs, can be nonzeros everywhere.
n_ind by n_inputs.
n_outputs by n_ind.
Obtaining the Independent Subset of States. A complete linearized
solution uses only an independent subset of the system states. From the
matrices A, B, C, D, you can obtain a minimal input-output linearized model
with the
minreal and sminreal functions from Control System Toolbox
software.
Linearizing with the Simulink linmod and dlinmod Functions
The Simulink functions linmod and dlinmod provide a way of linearizing
a Simscape model. There are several ways that you can use
dlinmod, and the linearization results differ depending on the method chosen.
To use these functions, you do not have to open the model, just have the model
file on your MATLAB path.
linmod and
2-31
2 Simulating Physical Models
For more information about Simulink linearization, see “Linearizing Models”
in the Simulink documentation.
Note If your model has continuous states, use linmod. (Continuous states
are the Simscape default.) If your model has mixed continuous and discrete
states, or purely discrete states, use
Linearizing a model with the local solver enabled (in the Solver Configuration
block) is not supported.
Linearizing with Default State and Input. You can call linmod without
specifying state or input. Enter
dlinmod.
linmod('modelname') at the command line.
With this form of
linmod, Simulink linearization solv es for consistent initial
conditions in the same way it does on the first step of any simulation. In
particular, any initial conditions, such as initial offset from equilibrium for a
spring, are set as if the simulation were starting from the initial time.
linmod allowsyoutochangethetimeofexternally specified signals (but not
the internal system dynamics) from the default. For this and more d etails, see
the function reference page.
Linearizing with the Steady-State Solver at an Initial Steady State.
If you have previously used the Simscape steady-state solver to find an
operating point, you can linearize at that operating point:
1 Open one or more Solver Configuration blocks in your model.
2 Select the Start simulation from steady state check box for the physical
networks that you wan t to linearize.
3 Close the Solver Configuration dialog boxes and save the modified model.
4 Enter linmod('modelname') at the command line.
linmod linearizes at the first step of simulation. In this case, the initial state
is also an operating point, a steady state.
2-32
Linearizing at an Operating Point
For more about setting up the steady-state solver, see the Solver Configuration
block reference page. F or more details on its use, see “Using the Simscape
Steady-State Solver” on page 2-25.
Linearizing with Specified State and Input — Ensuring Consistency
of States. You can call
linmod('modelname',x0,u0) at the command line. The extra arguments
specify, respectively, the steady state x
the simulation. When you specify a state to
linmod and specify state and input. Enter
and inputs u0for linearizing
0
linmod, ensure that it is
self-consistent, within solver tolerance.
With this form of
linmod, Simulink linearization does not solve for initial
conditions. Because not a ll states in the model have to be independent, it is
possible, though erroneous, to provide
linmod with an inconsistent state to
linearize about.
If you specify a state that is not self-consistent (within solver tolerance), the
Simscape solver issues a warning at the command line when you attempt
linearization. The Simscape solver then a ttempts to make the specified
x0
consistent by changing some of its components, possibly by large amounts.
Tip You most easily ensure a self-consistent state by taking the state from
some simulated time. For example, by selecting the States check box on the
Data Import/Export pane of the model Configuration Parameters dialog
box, you can capture a time series of state values in a simulation run.
Linearizing with Simulink Linearization Blocks
You can generate linearized state-space models from your Simscape model by
adding a Timed-Based Linearization or Trigger-Based Linearization block to
the model and simulating. These blocks combine time-based simulation up to
specified times or internal trigger points, with state-based linearization at
those times or trigger points.
For complete details about these blocks, see their respective block reference
pages.
2-33
2 Simulating Physical Models
Linearizing with Simulink Control Design Software
Note The techniques described in this section require the Simulink Control
Design product. You must use the features of this product on the Simulink
lines in your model, not directly on Simscape physical network lines or blocks.
The following methods require that you start with an operating point object
saved from trimming the model to an operating specification, as explained in
“Using Simulink
®
Control Design Techniques” on page 2-26.
To linearize a model with an operating point object, use the
function, customizing where necessary. The resulting state-space object
contains the matrices A, B, C, D.
Additional Simulink Control Design Methods. Instead of the command
line interface, you can use the associated graphical user interface, through
the model menu bar: Tools > Control Design > Linear Analysis.Formore
details on linearization, operating points and state-space objects, related
functions, and the graphical interface, see the Simulink Control Design
documentation.
linearize
References
[1] Brogan, W. L., Modern Control Theory, 2nd Ed., Englewood Cliffs, New
Jersey, Prentice-Hall, 1985.
[2] The MathWorks, Control System Toolbox User Guide,
www.mathworks.com/access/helpdesk/help/toolbox/control/.
2-34
Generating Code
In this section...
“About Code Generation from Simscape Models” on page 2-35
“Related Simulink Code Generation Documentation” on page 2-35
“Reasons for Generating Code” on page 2-36
“Using Code-Related Products and Features” on page 2-36
“How Simscape Code Generation Differs from Simulink” on page 2-37
About Code Generation from Simscape Mo dels
You can use Real-Time Workshop®software to generate stand-alone C code
from your Physical Networks models and enhance simulation speed and
portability. Certain features of Simulink software also make use of generated
or external code. This section explains code-related tasks you can perform
with your Simscape models.
Generating Code
Code versions of Simscape models typically require fixed-step Simulink
solvers, which are discussed in the Simulink documentation. Some features of
Simscape software are restricted when you translate a model into code. See
“How Simscape Code Generation Differs from Simulink” on page 2-37, as
well as “Limitations” on page 2-39.
Note Code generated from Simscape models is intended for rapid prototyping
and hardware-in-the-loop applications. It is not intended for use as production
code in e mbedded controller applications.
Add-on products based on the Simscape platform also support code generation,
with some variations and exceptions described in their respective User’s
Guides. Consult those User’s Guides for more information.
Related Simulink Code Generation Documentation
Consult Simulink Acceleration modes, Real-Time Workshop, and xPC
Target™ documentation for general information on code generation.
2-35
2 Simulating Physical Models
Reasons for Generating Code
Code generation has many purposes and methods. There are two essential
rationales:
• Compiled code versions of Simulink and Simscape models run faster than
• An equally im portant consideration for Simscape models i s the sta nd-alone
Using Code-Related Products and Features
With Simulink, Real-Time Workshop, and xPC Target software, using several
code-related technologies, you can link existing code to your models and
generate code versions of your models.
the original block diagram models. The time savings can be dramatic.
implementation of generated and compiled code. Once you convert part
or all of your model to code, you can deploy the stand-alone executable
program on virtually any platform, independently of MATLAB application.
Converting a model or subsystem to code also hides the original m o del or
subsystem.
2-36
Code-Related Task
Link existing code written in C
or other supported languages to
Simulink models
Speed up Simulink simulationsAccelerator mode
Generate stand-alone fixed-step
code from Simulink models
Generate stand-alone
variable-step code from Simulink
models
Convert Simulink model to code
andcompileandrunitonatarget
PC
Component or Feature
Simulink S-functions to generate
customized blocks
Rapid Accelerator mode
Real-Time Workshop software
Real-Time Workshop Rapid Simulation
Target (RSim)
Real-Time Workshop and xPC Target
software
Generating Code
HowSimscapeCodeGenerationDiffersfrom
Simulink
In general, using the code generated from Simscape models is similar to using
code generated from regular Simulink models. However, there are certain
differences.
Simscape and Simulink Code Are Generated Separately
Real-Time Workshop software g enerates code from the Simscape blocks
separately from the Simulink blocks in your model. The generated Simscape
code does not pass through
the code generated from a single model resides in the same directory, however.
Compiler Support and Precompiled Libraries
Simscape software and its add-on products provide static runtime libraries
precompiled for compilers supported by Real-Time Workshop software. These
are the standard UNIX compilers for UNIX operating systems, LCC and
Microsoft
for 64-bit W indows.
®
Visual Studio®for 32-bit Windows®, and Microsoft Visual Studio
model.rtw or the Target Language Compiler. All
Forallothercompilers,thestaticruntime libraries needed by code generated
from Simscape models are compiled once per model during the code generation
build process.
Simscape Code Reuse Is Not Supported
Reusable subsyste ms in Simulink reuse code that is generated once from the
subsystem. You cannot generate reusable code from subsystems containing
Simscape blocks.
Tunable Parameters Are Not Supported
A tunable parameter is a Simulink run-time parameter that you can change
while the simulation is running. Simscape blocks do not support tunable
parameters in either simulations or generated code.
2-37
2 Simulating Physical Models
Simscape Run-Time Parameter Inlining Ignores Global
Exceptions
If you choose to enable parameter inlining for code generated from a Simscape
model, the software inlines all its run-time parameters. If you choose to make
some of the global Simscape block parameters exceptions to inlining, the
exceptions are ignored. You can change global tunable parameters only by
regenerating code from the model.
2-38
Limitations
Limitations
In this section...
“SampleTimeandSolverRestrictions”onpage2-39
“Algebraic Loops” on page 2-39
“Restricted Simulink Tools” on page 2-40
“Unsupported Simulink Tools” on page 2-42
“Simulink Tools Not Compatible with Simscape Blocks” on page 2 -4 2
“Code Generation” on page 2-42
Sample Time and Solver Restrictions
The default sample times of Simscape blocks are continuous. You cannot
simulate Simscape blocks with discrete solvers using the default sample times.
IfyouswitchtoalocalsolverintheSolverConfigurationblock,theassociated
states become discrete. If there are no continuous Simulink or Simscape
states elsewhere in the model, you should use a discrete solver to simulate
such a model.
You cannot override the sample time of a nonvirtual subsystem containing
Simscape blocks.
Algebraic Loops
A Simscape physical network should not exist within a Simulink algebraic
loop. This means that you should not directly connect an output of a
PS-Simulink Converter block to an input of a Simulink-PS Converter block of
the same physical network.
For example, the following model contains a direct feedthrough between
the PS-Simulink Converter block and the Simulink-PS Converter block
(highlighted in magenta). To avoid the algebraic loop, you can insert a
Transfer Function block anywhere along the highlighted loop.
2-39
2 Simulating Physical Models
A better way to avoid an algebraic loop without introducing additional
dynamics is shown in the modified model below.
2-40
Restricted Simulink Tools
Certain Simulink tools are restricted for use with Simscape software:
• You can use the Simulink
get Simscape block parameters. The MathWorks does not recommend that
you use these commands for this purpose.
If you make changes to block parameters at the command line, run your
model first before saving it. Otherwise, you might save invalid block
parameters. Any block p aram eter changes that you make with
are not validated unless you run the model.
set_param and get_param commands to set or
set_param
• Enabled subsystems can contain Simscape blocks . Always set the States
when enabling parameter in the Enable dialog to
Enable port.
held for the subsystem’s
Limitations
Setting States when enabling to
to fatal simulation errors.
• You can place Simscape blocks within nonvirtual subsystems that support
continuous states. Nonvirtual subsystems that support continuous states
include Enabled subsystems and Atomic subsystems. However, physical
connections and physical signals must not cross nonvirtual boundaries.
When placing Simscape blocks in a nonvirtual subsystem, make sure
to place all block s belonging to a given Physical Network in the same
nonvirtual subsystem.
• Simulink configurable subsystems work with Simscape blocks only if all of
the block choices have consistent port signatures.
• For Iterator, Function-Call, Triggered, and While Iterator nonvirtual
subsystems cannot contain Simscape blocks.
• An atomic subsystem with a user-specified (noninherited) sample time
cannot contain Simscape blocks.
• You can use the Simulink Save As command only to rename Simscape
models within the current version. Saving in a previous version format is
not supported for models containing Simscape blocks.
• Linearization with the Simulink
Simulink Control Design functions and graphical interfaces is not
supported with Simscape models if you use local solvers.
reset is not supported and can lead
linmod function or with equivalent
• Model referencing is supported, with some restrictions:
- All Physical connection lines must be contained within the referenced
model. Such lines cannot cross the boundary of the referenced model
subsystem in the referencing model.
- The referencing model and the referenced model must use the same
solver.
For further information, consult the Simulink documentation on
referencing models.
2-41
2 Simulating Physical Models
Unsupported Sim
Certain Simulin
• The Simulink Pr
• Physical sign
different fro
tool and the si
Simulink Too
Some Simulin
• Execution o
• Simscape bl
• You cannot
• Reusable s
• You canno
• The Repor
Code Gen
Code gen
family
from Si
eration is supported for Simscape physical modeling software and its
of add-on products. How ever, there are restrictions on code generated
mscape models.
k tools and features do not work with Simscape softw are:
ofiler tool does not work with Simscape models.
als and physical connection lines between conserving ports are
m Simulink signals. Therefore, the Signal and Scope Manager
gnal label functionality are not supported.
lsNotCompatiblewithSimscapeBlocks
k tools and features do not work with Simscape blocks:
rder tags do not appear on Simscape blocks.
ocks do not invoke user-defined callbacks.
set breakpoints on Simscape blocks.
ubsystems cannot contain Simscape blocks.
t use the Simulink Fixed-Point Tool with Simscape blocks.
t Generator reports Simscape block properties incompletely.
eration
ulink Tools
2-42
• Code r
• C++ co
• Tunab
• Run-
• Simu
• Blo
if y
con
• Co
S-
euse is no t supported.
de generation is not supported.
le parameters are not supported.
time parameter inlining ignores global exceptions.
lation of Simscape models on fixed-point processors is not supported.
ck diagnostics in error messages are not supported. This means that
ou get an error message from simulating generated code, it does not
tain a list of blocks involved.
nversion of models or subsystems containing Simscape blocks to
functions is not supported.
Limitations
• Simulation-in-the-loop (SIL) is not supported.
• Code generation respects the Linear Algebra setting in the Solver
Configuration block, but only when you choose the local solver option.
Otherwise, code generation uses full linear algebra.
“Generating Code” on page 2-35 describes Simscape code generation features.
“Restricted Simulink Tools” on page 2-40 describes limitations on model
referencing.
There are variations and exceptions as well in the code generation features of
the a dd-on products based on Simscape platform. For details, see the User’s
Guides for individual add-on products.
Code Generation and Fixed-Step Solvers
Most code generation options for Simscape models require the use of fixed-step
Simulink solvers. This table summarizes the available solver choices,
depending on how you generate code.
Code Generation Optio nSolver Choices
Accelerator mode
Rapid Accelerator mode
Real-Time Workshop software: RSim
Target*
Real-Time Wo rks ho p software: Targets
other than RSim
* For the R Sim Target, Simscape software supports only the Simulink
solver module. In the model Configuration Parameters dialog box, see the
Real-Time Workshop: RSim Target: Solver selection menu. T he default
is automatic selection, whichmightfailtochoosetheSimulinksolvermodule.
Variable-step o r fixed-step
Variable-step o r fixed-step
Fixed-step only
2-43
2 Simulating Physical Models
2-44
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.