Simscape Multibody User Guide
Simscape Multibody User Guide
User's Guide
R2024a
How to Contact MathWorks
Phone: 508-647-7000
Multibody Modeling
Bodies
1
Bodies Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Bodies in the Context of a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Step 1: Study the Bodies to Model . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Step 2: Model the Solids in Each Body . . . . . . . . . . . . . . . . . . . . . . . 1-2
Step 3: Connect the Solids Through Frames . . . . . . . . . . . . . . . . . . . 1-3
Step 4: Verify the Body Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
v
Creating Connection Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Frames as a Connection Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Creating and Transforming Frames . . . . . . . . . . . . . . . . . . . . . . . . 1-33
See It: Frames in a Typical Body . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-34
Planning Connection Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-35
Addressing Assembly Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36
vi Contents
Advanced Visual Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-93
Adjust Solid Opacity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-93
Adjust Highlight Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-94
Adjust Shadow Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-94
Adjust Self-Illumination Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-95
Multibody Systems
2
Multibody Assembly Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Study the Joints and Constraints to Model . . . . . . . . . . . . . . . . . . . . 2-2
Assemble Bodies Using Joints and Constraints . . . . . . . . . . . . . . . . . 2-2
Guide Model Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Verify Model Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
vii
Modeling Gear Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-27
Gear Constraints and Applications . . . . . . . . . . . . . . . . . . . . . . . . . 2-27
Gear Assemblies as Kinematic Loops . . . . . . . . . . . . . . . . . . . . . . . 2-28
Gear Assembly Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29
Gear Pitch Circles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Modeling Gear Geometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Limitations of Gear Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31
Sensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32
Sensing Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32
viii Contents
Variables You Can Sense . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32
Blocks with Sensing Capability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-33
Sensing Output Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-33
ix
Modeling Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-84
Build Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-85
Simulate Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-88
Simulation
4
Update and Simulate a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Create or Open a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Update the Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Examine the Model Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Configure the Solver Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Run Simulation and Analyze Results . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
x Contents
Visualization and Animation
5
Enable Mechanics Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
xi
Go to a Block from Mechanics Explorer . . . . . . . . . . . . . . . . . . . . . . 5-27
xii Contents
Import URDF Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-30
Supported URDF Elements and Attributes . . . . . . . . . . . . . . . . . . . 6-30
Mapping to Simscape Multibody Blocks . . . . . . . . . . . . . . . . . . . . . 6-31
Mesh Geometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-32
Physical Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-32
URDF Import Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33
Differences from CAD Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33
Import a Simple URDF Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-33
Deployment
Code Generation
7
Code Generation Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Code Generation Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Simulation Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Model Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Examples
xiii
Double Pendulum in Simulink and Simscape Multibody . . . . . . . . . 8-12
Using the Worm and Gear Constraint Block - Solar Tracker . . . . . . 8-34
xiv Contents
Double Wishbone Suspension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-56
Backhoe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-58
Pick and Place Robot Using Forward and Inverse Kinematics . . . . 8-62
Forklift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-88
Using the Reduced Order Flexible Solid Block - Flexible Dipper Arm
..................................................... 8-91
xv
Vehicle Dynamics - Car with Heave and Roll . . . . . . . . . . . . . . . . . . 8-173
xvi Contents
Multibody Modeling
17
1
Bodies
Bodies Workflow
In this section...
“Bodies in the Context of a Model” on page 1-2
“Step 1: Study the Bodies to Model” on page 1-2
“Step 2: Model the Solids in Each Body” on page 1-2
“Step 3: Connect the Solids Through Frames” on page 1-3
“Step 4: Verify the Body Subsystems” on page 1-3
Bodies are collections of solids and occasionally other body elements. Start your model by
conceptually breaking down each body into shapes that you can specify using the different solid
blocks. Obtain the dimensions, inertia, and color of each solid. For more information on bodies and
their nature as (normally rigid) collections of body elements, see:
Body elements are defined by their material attributes. Specify these attributes using solid blocks,
the inertia block, and other blocks from the Body Elements library. For more information on body
elements and their attributes, see:
1-2
Bodies Workflow
The placement of a body element in a body depends on how its frames are defined. Create and
connect the frames required to assemble the various body elements into a complete body. For more
information on frames and frame connections, see:
Visualize each body and verify its geometry, color, and frames. You can use the block visualization
pane to visualize an individual solid or Mechanics Explorer to visualize a complete body. For more
information about visualization, see:
1-3
1 Bodies
Modeling Bodies
In this section...
“Body Elements” on page 1-4
“Relevant Blocks” on page 1-6
“Body Visualization” on page 1-7
“See It: A Typical Body” on page 1-7
“Boundaries of Bodies” on page 1-9
“Bodies as Simulink Subsystems” on page 1-12
Bodies are the basic constituents of a multibody model. They are the solid components that you
connect when assembling a model and the subjects upon which all forces and torques in that model
ultimately act. The planets and the sun serve as bodies in a model of the solar system, for example,
and wings do too in a model of a flapping mechanism.
If you are familiar with CAD modeling, you can loosely think of bodies as equivalents of CAD parts,
each a modular component with geometry and material. The modeling approach may differ—for
example, there are no sketches to draw—but, conceptually, the end result is the same: something that
you can connect, constrain, act upon, and visualize.
Body Elements
A body is a collection of simpler body elements: solids with geometry and inertia and, less often, plain
inertias (without assigned geometries) and plain geometries (without associated inertias). The body
elements that you model and the ways in which you connect them determine the overall attributes of
the body.
Bodies with simple shapes often require a single solid. Those with complex shapes or inertias may
require several solids and the occasional plain inertia or plain geometry. Like bricks in a modular
build set, the properties of the various body elements can differ from each other. It is up to you to
combine them in a way that produces the desired body.
1-4
Modeling Bodies
Each body element comprises one or more frames and a set of material attributes. The frames
determine the placement of the body elements relative to each other and provide the attachment
points for joints and constraints. The attributes factor in the dynamic behavior of the body elements
and, in those with geometry, help determine their visual appearance.
Material Attributes
The attributes of solids include inertia and color. Geometry enables the automatic calculation of
inertia parameters and, in conjunction with color, visualization. Inertia quantifies the resistance to
changes in motion and factor into the calculation of the forces and torques required to induce an
acceleration.
The attributes of other body elements are more limited in scope. Those of plain inertias include only
inertia, with parameters that in the general case encompass mass, center of mass, moments of
inertia, and products of inertia.
1-5
1 Bodies
The figure summarizes the structure of a typical body (here a wing) in the context of a typical
multibody model (here a flapping wing mechanism). Multibody assemblies (1) comprise bodies (2),
bodies comprise body elements (3)—often all solids—and body elements comprise frames and any
material attributes relevant to them (4).
Relevant Blocks
You can model most bodies using the solid blocks and Rigid Transform block. The solid blocks
represent their namesake—a solid element of a certain type. The block parameters set the attributes
of the solid and a frame port, labeled R, provides a reference frame for connection to a model. You
can create additional, custom, frames and position them using a variety of solid features.
The Rigid Transform block represents a fixed spatial relationship between two frames. Whenever you
add a Rigid Transform block to a frame connection line, you replace the coincidence relationship
originally set by that line with a rotational and translational offset that you specify in the block dialog
box.
1-6
Modeling Bodies
Only rarely do bodies contain other blocks. Those that remain in the Body Elements library—Graphic,
Inertia, and all in the Variable Mass sublibrary—serve special cases. Use them, for example, to add
graphic markers, adjust inertia through compounding, or allow inertia to vary during simulation.
Body Visualization
You can visualize individual solids and complete models. The right visualization tool to use depends
on which of the two you want to visualize. You can visualize individual solids directly through their
respective solid blocks. In its dialog box, The solid blocks provide a visualization pane that shows the
geometry, frames, and color of the solid that it represents. The visualization works even if the block
diagram is incomplete or invalid.
You can visualize a model, and all the bodies within it, using the Simscape Multibody visualization
utility, Mechanics Explorer. The model must be free of kinematic conflicts, such as those due to
mutually incompatible joints and constraints. It must also contain one Solver Configuration block for
every topologically distinct multibody network—each a group of Simscape Multibody blocks that
connect without breaks in their frame connection lines.
Mechanics Explorer opens a static model visualization in its initial configuration whenever you do a
diagram update (in the Debug tab, click Update Model). The initial configuration is the aggregate
result of all initial joint positions and angles, whose values you can specify using joint state targets.
The visualization becomes dynamic when you run a simulation, although this is a task you are unlikely
to perform while still modeling bodies.
For more information about visualization, see “Visualize a Model and Its Components” on page 1-59.
1-7
1 Bodies
RightWing. You can do this by clicking the down arrow at the bottom left corner of the block. The
blocks inside the subsystem are a typical representation of a body.
The solid blocks each represent a section of the wing body. The frame connection lines between the
solid blocks, and the Rigid Transform blocks that some of the connection lines contain, define the
spatial relationships that exist between the solid sections. Open the dialog box of the Cylindrical Solid
block named CrossPin and explore its attributes:
• The Geometry parameters are by default expanded. The Cylindrical Solid block uses a shape with
its relevant dimensions (Radius, Length) parameterized in terms of MATLAB variables (Rp, Lp).
All variables are defined numerically in the subsystem mask.
• Expand the Inertia parameters. The block is configured to calculate the bulk of the inertia
parameters from geometry and a mass parameter (Density). This parameter too is parameterized
in terms of a MATLAB variable (rho).
1-8
Modeling Bodies
• Expand the Graphic parameters. The block uses a Simple color model with the visual properties
of the solid (Color, Opacity) parameterized in terms of MATLAB variables (lclr) or specified
numerically (1.0).
• In the visualization toolstrip, click the frame button. The visualization pane shows the frames
associated with the solid. This solid has a single frame, the local reference frame that by default
every solid block has. The placement of this frame relative to the geometry impacts the placement
of the geometry in the context of the model.
• Update the block diagram. Mechanics Explorer opens with a static visualization of the flapping
wing model in its initial configuration. In the tree view pane (located on the left side of Mechanics
Explorer), right-click the RightWing node and select Show Only This. The visualization pane
updates to show only the body elements that compose the selected component.
Boundaries of Bodies
Direct connection lines and Rigid Transform blocks unite body elements into a single body. Such
connections are treated as internal to the bodies they belong to. Joint and constraint blocks in turn
separate solids into different bodies. These blocks identify the boundaries of the bodies that they
connect. This distinction has practical consequences in models with Gravitational Field blocks.
The figure shows a flattened portion of the PointOnCurveExample block diagram. The joint blocks
namedRFJ and RWJ separate the blocks that compose the body to their right (identified by the shaded
area) from the neighboring bodies to which it connects (not shown).
1-9
1 Bodies
By design, the Gravitational Field block exerts a force on the center of mass of a body. The center of
mass is determined from the aggregate of all Body Elements blocks that comprise the body. If two
solid blocks connect through a Rigid Transform block, they belong to the same body. A single
gravitational force then acts at the center of mass of that body.
If, however, the Cylindrical Solid blocks connect through a Revolute Joint block, they belong to
separate bodies. Two gravitational forces then apply at the individual centers of mass of those bodies.
The same is true even if you replace the Revolute Joint block with a Weld Joint block. Regardless of its
type, every joint block separates the body elements that it connects into separate bodies.
The figure shows the effect of adding a Weld Joint block to a block network that originally composed a
single body. This joint block divides the body into two bodies, one comprising only the Cylindrical
Solid block named WingLink, the other comprising the remaining Cylindrical Solid and Rigid
Transform blocks. Gravitational Field blocks in your model, if any, would in this case exert a force at
the calculated center of mass of each body.
1-10
Modeling Bodies
The blocks that comprise a body connect rigidly and, in the ideal case, in series. The result is a tree
structure in which the path between any two frames is unique. It is technically possible, however, to
rigidly connect blocks so that they form a rigid loop, a closed structure formed by connecting the
open ends of a branch or tree.
Rigid transform loops are disallowed in a model. They contain redundant (and unnecessary) rigid
connections and these could lead to preventable numerical errors if included in a model. If your
1-11
1 Bodies
model contains a rigid kinematic loop, you must break that loop by removing of its redundant rigid
connections. The figure shows an example.
You can model a body and convert it to a Simulink subsystem at any time prior to its use in a
multibody model. For example, when modeling a piston engine, you can defer work on a piston body
until you are ready to connect the piston to the engine housing or to the connecting rod. However,
given that the shape and size of one body often depend on those of another, you should at least
consider those attributes prior to focusing on assembly.
1-12
Modeling Bodies
Double-click the subsystem block named Peg. A custom dialog box opens with the key parameters
required to completely define this body. The values specified here are used in the Cylindrical Solid
and Rigid Transform blocks that compose the subsystem block.
Right-click the subsystem block and select Mask > View Mask. The Simulink Mask Editor opens
with the parameters and code relevant to the wing body. The parameters and the MATLAB variables
associated with them are defined in the Parameters & Dialog tab. The code used to generate the
wing and spar shape profiles is defined in the Initialization tab.
Right-click the subsystem block and select Mask > Look Under Mask. The block diagram
corresponding to this subsystem opens up. Open the dialog boxes of some of the blocks and note the
MATLAB variables used to define many of their parameters. These are the variables defined in the
subsystem mask and specified in the subsystem block dialog box.
1-13
1 Bodies
See Also
More About
• “Compounding Body Elements” on page 1-15
• “Creating Connection Frames” on page 1-33
• “Representing Solid Geometry” on page 1-38
• “Representing Solid Inertia” on page 1-63
1-14
Compounding Body Elements
Start by exploring the DocCompoundLinkExample model and the geometry variables defined in its
workspace:
1 At the MATLAB command prompt, enter openExample("sm/DocCompoundLinkExample").
The model opens. In it are six unconnected blocks—three solid blocks, two Rigid Transform, and
one Solver Configuration.
The solid blocks represent the elementary sections of a binary link and the Rigid Transform
blocks the spatial relationships between the solid reference frames. The Solver Configuration
block is required only for visualization in Mechanics Explorer.
2 In the Modeling tab, click Model Explorer. Model Explorer is a Simulink tool that you can use
to explore your model workspace. All the relevant solid dimensions, including the general
Extruded Solid cross-sections, are defined there.
3 In the Model Hierarchy pane, located on the left, expand the node named after your model and
select the Model Workspace subnode. The Model Workspace pane opens on the right prefilled
with several lines of MATLAB code.
% Body Geometry Parameters
l = 20; % Hole-to-hole distance
1-15
1 Bodies
w = 2; % Link width
d = 1.2; % Hole diameter
t = 1; % Link thickness
This code defines the [x, y] coordinates of the General Extruded Solid cross-sections. The cross-
sections are parameterized in terms of the relevant solid dimensions, namely length, width, and
hole diameter. Note the link dimensions specified in the code. The distance between the link
holes (variable l), is 20 in what will later be units of cm. The link width (w) is 2 and the hole
diameter (d) 1.2 in the same units.
4 Open each solid block dialog box. The visualization pane shows the solid geometry, derived partly
from the code in the model workspace, corresponding to the respective block. Two of the solids
are general Extruded Solid blocks, and one is a Cylindrical Solid block.
On the toolstrip of the visualization pane, click the Toggle visibility of frames button. The
visualization pane displays the solid reference frame. The placement of a reference frame
relative to a solid geometry becomes important when considering the rigid transforms that you
must apply between the various solid reference frames.
Complete the model by rigidly connecting the solids and specifying their spatial relationships:
1 Connect the solid blocks as shown in the figure. The solid reference frames are, for the moment
only, coincident with each other.
1-16
Compounding Body Elements
2 Drop the Rigid Transform blocks on the connection lines as shown in the figure. Simulink
automatically connects the frame ports to the connection lines.
Pay special attention to the port positions—the B ports should both face the Extruded Solid block
named Main. Flipping the port connections would change the relative placement of the solids in
the final body.
3 In the dialog box of the Rigid Transform block named Main-to-Hole Transform, specify the
Translation parameters listed below. These parameters describe a translation of half the binary
link length along the -x axis of the base (B) frame—in this model held coincident with the
reference (B) frame of the solid named Main.
• Method: Cartesian
• Offset: [l/2 0 t], units of m
5 In the Modeling tab, select Update Model. Mechanics Explorer opens with a visualization of
the binary link model. The body is compound—it comprises multiple solids—and can therefore be
visualized in its entirety using Mechanics Explorer only. For emphasis, the solids are shown in
different shades of gray.
1-17
1 Bodies
For an example showing how to specify a General Extruded Solid cross-section, see “Try It: Define a
Simple Cross-Section” on page 1-46. The cross-section in that example is based on a similar, though
not identical, model of a binary link. That link is treated as a simple body—one modeled as a single
solid—with neither pegs nor holes. However, the strategy demonstrated there applies to other
General Extruded Solid cross-sections as well. For an extension of that example showing how to
include holes in a cross-section, see “Try It: Define a Cross-Section with Two Holes” on page 1-48.
Use this strategy to subtract the inertia associated with a bore from a cylindrical solid originally
modeled without one. Represent the dense and hollow regions using Cylindrical Solid blocks. Set the
cylinder length to 1 m and the radius to 0.25 m:
1 At the MATLAB command prompt, enter smnew. A new model based on the Simscape Multibody
template opens up. The model contains commonly used blocks and is configured with suitable
solver settings for multibody models.
2 Add two of the Cylindrical Solid blocks and connect them to the Solver Configuration blocks. The
frame connection line between the blocks make their reference frames coincident in space. You
can delete the remaining blocks.
3 In the dialog box of the leftmost Cylindrical Solid block, set the Radius parameter to 0.25 m,
and the Length parameter to 1 m. Name this block Dense.
4 In the dialog box of the rightmost Cylindrical Solid block, set the Radius parameter to 0.20 m,
and the Length parameter to 1 m. Name this block Hollow.
5 Set the Inertia > Density parameter of the Hollow block to the negative of the value used in
the Dense block: -1000 kg/m^3. The compound body represented by the Cylindrical Solid
blocks now has the inertia of a hollow cylinder with a bore 0.2 m in radius.
1-18
Compounding Body Elements
6 Expand the Inertia > Derived Values node and click the Update button to display the inertia
parameters of the Hollow solid. Do the same for the Dense solid. The mass and moments of
inertia have opposite signs, as expected from the density inputs.
See Also
More About
• “Modeling Bodies” on page 1-4
• “Representing Solid Geometry” on page 1-38
• “Representing Solid Inertia” on page 1-63
1-19
1 Bodies
The following figure shows a flexible channel beam model. In this example, the beam undergoes both
bending and torsion under an applied transverse point load. The degree to which the beam bends and
twists varies with the point of application of the force in the plane of the cross-section. Enter
smdoc_flexible_cantilever_channel at the MATLAB command prompt to open the model.
Beam Geometries
The geometry of a beam is an extrusion of its cross-section. The general cross-sections, with or
without holes, are supported by the General Flexible Beam block. Additionally, the beam cross-section
can take many standard shapes, such as channel, angle, and hollow cylindrical. For beams with
standard cross-sectional shapes, use the following flexible beam blocks:
Connection Frames
Each beam has two connection frames labeled A and B. Each connection frame has a frame port on
the block that can connect to another block. The connection frames are located at the ends of the
1-20
Overview of Flexible Beams
beam and fall on the z-axis of the local reference frame labeled R. The reference frame serves merely
as an internal reference for the beam and has no frame port.
Deformation Models
In Simscape Multibody, all the flexible beams can have elastic bending, axial, and torsional
deformations. The beams are assumed to be slender bodies whose length must far exceed its overall
cross-sectional dimensions, and all the deformations should be linear and small.
The bending and axial deformations of a beam follow classical (Euler-Bernoulli) beam theory. The
bending can be about any axis in the cross-sectional plane (xy-plane) of the beam. Cross-sectional
slices are assumed to be rigid in-plane, to stay planar during deformation, and to always be
perpendicular to the deformed neutral axis of the beam. The twisting of a beam derives from Saint-
Venant torsion theory, and the cross-sectional slices are rigid in-plane but free to warp out-of-plane.
When one or more of these assumptions are not met, the result may be inaccurate. For example, in
the figure, a cantilevered beam that is subjected to a transverse point load will get an inaccurate
result when the bending deformation, δ, is large. During the bending, the free end of the beam moves
downward perpendicularly instead of following the true physical path, which is indicated by the
dotted trajectory. The discrepancy, ε, increases as the δ increases.
Material Properties
Flexible beams in Simscape Multibody are assumed to be made of a homogeneous, isotropic, and
linearly elastic material. You can specify the material properties, such as density and Young's modulus
in the Stiffness and Inertia section of the block dialog box. The beam cross-sectional properties,
such as the axial, flexural, and torsional rigidities, are automatically calculated by the block using the
material and geometry properties that you specify. To see the computed values, in the beam block
dialog box, open Stiffness and Inertia > Derived Values and click the Update button.
Damping Methods
The beam blocks support two damping methods: uniform modal damping and proportional damping.
The uniform modal damping method applies identical damping ratios to all the vibration modes of the
beam. In the proportional damping method, the damping matrix [C] is a linear combination of the
mass matrix [M] and the stiffness matrix [K]:
1-21
1 Bodies
Discretization
The Number of Elements parameter in the Discretization section of the beam block dialog box
specifies the number of finite elements used to discretize the beam. You can select its value to obtain
a good compromise between simulation accuracy, which may require more elements, and simulation
speed, which requires fewer elements. Use the fewest elements needed to satisfy your accuracy
requirements.
For bending deformations, the beam blocks use the cubic Hermite interpolation method to compute
the displacement distributions throughout each element. The distributions of axial displacement and
torsional rotation are obtained by linear interpolation method.
Simulation Performance
When using beam blocks in a model, several factors impact the accuracy and speed of the simulation
performance. This section discusses the impact of the three most important factors: flexible beam
usage, solver selection, and damping settings.
Even though using flexible beams can increase the accuracy of a multibody simulation, the flexible
beams tend to slow it down by increasing the numerical stiffness and the number of degrees of
freedom of the system. To speed up the simulation, you should use a rigid body whenever the
deformation of the body is negligible. Moreover, the Number of Elements parameter in the
Discretization section heavily impacts the performance of the simulation. For more information, see
the “Discretization” on page 1-22 section.
The solver is critical to the performance of a multibody simulation. The stiff solvers, such as ode15s,
ode23t, or daessc, tend to work better for systems with flexible beams due to the stiff nature of these
systems. Additionally, solver tolerances and maximum order also impact the accuracy and speed of
the simulation. For more information, see “Choose a Solver”.
Note All the solvers, except ode23t, provide some level of numerical dissipation, which can be
helpful for modeling flexible multibody systems.
When modeling a flexible beam with little or no damping, undesirable high-frequency modes in the
response can slow down the simulation if the solver does not already provide adequate numerical
dissipation. In that case, adding a small amount of damping can improve the speed of the simulation
without significantly affecting the accuracy of the model.
Note Modeling gravity with both the Mechanism Configuration and Gravitational Field blocks results
in a compilation error.
1-22
Overview of Flexible Beams
Visualization
The dialog box of each flexible beam block contains a collapsible visualization pane. This pane
provides instant visual feedback on the beam you are modeling. Use it to find and fix any issues with
the cross-section, length, and color of the beam. You can examine the beam from different views by
selecting a standard view or by rotating, panning, and zooming.
In the toolstrip of the visualization pane, click the Update Visualization button to view the
latest changes to the beam. Click Apply or OK to commit any changes to the model.
Additionally, you can right-click the visualization pane for a context-sensitive menu. This menu
provides additional options to change the background color, modify the view convention setting, and
split the visualization pane into multiple windows that display different views of the beam.
1-23
1 Bodies
In this section...
“Role of Frames” on page 1-24
“Custom Solid Frames” on page 1-25
“What Are Frame Transforms?” on page 1-27
“Visualizing Frame Transforms” on page 1-27
“Try It: Specify a Frame Transform” on page 1-28
Frames are axis triads that encode position and orientation data in a 3-D multibody model. Each triad
consists of three perpendicular axes that intersect at an origin. The origin determines the frame
position and the axes determine the frame orientation. The axes are color-coded, with the x-axis in
red, the y-axis in green, and the z-axis in blue.
Role of Frames
Every solid component has one or more local frames to which it is rigidly attached. By positioning and
orienting the component frames, you position and orient the components themselves. This is the role
of frames in a model—to enable you to specify the spatial relationships between components.
A frame port identifies a local frame on a component. For example, the R frame port of a solid block
identifies the local reference frame of a solid. Every block has one or more frame ports that you
connect in order to locate the associated components in space. The figure shows the reference frame
ports on several of the Body Elements blocks.
1-24
Working with Frames
The connections between frame ports determine the spatial relationships between their frames. A
direct frame connection line makes the connected frames coincident in space. A Rigid Transform
block sets the rotational and translational offsets between the frames. The figure shows examples of
coincident and offset frame connections.
A coincident relationship between solid frames does not, by itself, constitute a coincident relationship
between solid geometries. The spatial arrangement of two solid geometries depends not only on the
spatial arrangement of the respective reference frames, but also on how the geometries are defined
relative to those frames.
If two geometries differ from each other, or if their positions and orientations relative to their
reference frames differ from each other, then making the reference frames coincident will cause the
solid geometries to be offset. In the figure, connecting the frame of Solid A to the left frame of Solid B
joins the solids such that their geometries are offset from each other.
Create a custom frame using the frame creation interface of the File Solid block. Then, place the
frame origin at the center of mass and align the frame axes with the principal axes of inertia. The
result is a frame that coincides with the principal reference frame—one in which the inertia matrix is
diagonal and the products of inertia are zero.
1 At the MATLAB command prompt, enter openExample("sm/DocLBeamInertiaExample"). A
model opens with a solid possessing the shape of an L-beam.
1-25
1 Bodies
2 In the File Solid block dialog box, click the Create Frame button. The File Solid block dialog box
switches to a frame creation view.
3 Change the Frame Name parameter to P (for “Principal Frame”). The visualization pane and the
frame port use this label to identify your new frame.
4 Under Frame Origin, select the radio button labeled At Center of Mass.
5 Under Frame Axes > Primary Axis and Frame Axes > Secondary Axis, select the radio button
labeled Along Principal Inertia Axis. Accept the default axis options (+Z and +X, respectively)
and click Save. The block dialog box switches back to the main (parameters) view.
6 In the visualization toolstrip, click the Toggle visibility of frames button. The visualization pane
shows the frames of the solid, including your new custom frame, P.
1-26
Working with Frames
You use the Rigid Transform block to specify a rotational, translational, or mixed rigid transform
between frames. The transforms are directional. They set the rotation and translation of a frame
known as follower relative to a frame known as base.
The frame port labels on the Rigid Transform block identify the base and follower frames. The frame
connected to port B serves as base. The frame connected to port F serves as follower. Reversing the
port connections reverses the direction in which the frame transform is applied.
You can specify a transform using different methods. For rotational transforms, these include axis-
angle pairs, rotation matrices, and rotation sequences. For translational transforms, they include
translational offset vectors defined in Cartesian or cylindrical coordinate systems.
If the rotational and translational transforms are both zero, the connected frames are coincident in
space. This relationship is known as identity and it is equivalent to a direct frame connection line
between frame ports—i.e., one without a Rigid Transform block.
1-27
1 Bodies
A Frame on a Solid
Use Mechanics Explorer to visualize the frames of more than a single solid element—e.g., in
compound bodies, multibody subsystems, or complete multibody models. Select View > Show
Frames in the Mechanics Explorer menu to show all frames. Select a node from the tree view pane to
show only those frames belonging to the selected component.
Frames on a Body
1 At the MATLAB command line, enter smnew. A Simscape Multibody model template with
commonly used blocks opens.
2 Delete the Simulink-PS Converter, PS-Simulink Converter, and Scope blocks because they are not
used in this example.
3 Show the names of the Rigid Transform and Brick Solid blocks. Right-click the blocks and select
Format > Show Block Name > On.
4 Make a copy of the Brick Solid block and rename the Brick Solid blocks to Base and Follower.
5 Connect the remaining blocks like the following figure.
1-28
Working with Frames
6 Run the model. Mechanics Explorer opens with a model visualization. In the Mechanics Explorer,
click the Isometric view button.
7 In the tree view pane, click the Base and Follower nodes. The visualization pane shows the
reference frames of the two Brick Solid blocks, which shows they are coincident in space.
Apply a Translation
This section shows how to apply a translation to a follower frame by using the Rigid Transform block.
1 Connect the Rigid Transform block between the two Brick Solid blocks.
1-29
1 Bodies
Apply a Rotation
This section shows how to apply a rotation about the x-axis to the follower frame by using the Rigid
Transform block.
1-30
Working with Frames
This section shows how to apply a combined transformation, which includes a translation and a
rotation to a follower frame by using the Rigid Transform block.
1-31
1 Bodies
When both rotational and translational transformations are specified in a Rigid Transform block, the
block always applies the translation to the follower frame first. The translations describe how the
follower frame is moved relative to its base frame. Any rotations about the base frame axes are
always in respect to the axes of the translated base frame.
See Also
More About
• “Modeling Bodies” on page 1-4
• “Creating Connection Frames” on page 1-33
• “Visualize Simscape Multibody Frames” on page 5-24
1-32
Creating Connection Frames
You can also create frames using the Rigid Transform block. This block enables you to define the
position and orientation of a frame numerically, in terms of rotation and translation transforms. You
can use a variety of transform parameterizations, including rotation matrices and rotation sequences
in the case of rotation transforms, and Cartesian and cylindrical offset coordinates in the case of
translation transforms. The figure shows a new frame (F) created using a Rigid Transform block from
an existing solid frame.
Frames that you create using Rigid Transform blocks are independent of any specific solid features.
You can place them anywhere relative to another frame as long as you can determine the transform
required to obtain that placement. When placing a Rigid Transform block between two frame ports,
you can more aptly think of the block as a means to offset frames that already exist. The figure shows
an offset specified through a Rigid Transform block placed between two existing frames.
For more information about frames and transforms, see “Working with Frames” on page 1-24.
1-33
1 Bodies
1 Open the dialog box of the Cylindrical Solid block named Peg.
2 In the visualization toolstrip, click the frame button. The visualization pane updates to show the
reference and custom frames of the solid.
3 In the Properties section of the dialog box, expand the Frames node and click the Edit button.
The frame creation interface opens with the current frame definition:
• The frame origin has been placed at the center of the bottom surface of the cylinder.
• The frame axes have been left in alignment with those of the local reference frame.
• The name of the frame matches the label of the corresponding frame port (B).
Note also that the frame connection lines between some of the solid blocks contain Rigid Transform
blocks, named CPXform and WingXForm. These blocks specify the rotational and translational offsets
between the solid frames that they connect. Explore the transforms specified in one of the blocks:
1 Open the property inspector of the Rigid Transform block named WingXForm. Note that the
rotation transform is set by aligning two axes of the follower frame relative to two axes of the
base frame.
2 Expand the Translation parameters. Note that the translational offset is specified along the axis
(of the base frame). The translational offset is parameterized in terms of a MATLAB variable, Ow,
whose value you specify in the WingLink subsystem block.
1-34
Creating Connection Frames
3 Update the block diagram. Mechanics Explorer opens with a static visualization of the flapping
wing model. In the tree view pane, expand the RightWing node and click the WingXForm node
to highlight the frames belonging to the Rigid Transform block.
If the target is a joint, take note of its degrees of freedom—the types of motion allowed between the
joint connection frames—and of the frame axes to which they correspond. For example, the Revolute
Joint block provides one rotational degree of freedom about the common z-axis of the connection
frames on the base and follower bodies.
To connect two bodies through a Revolute Joint block, you must then place their joint connection
frames so that their z-axes each align with the desired rotation axis on the respective body. The figure
shows an example: the Housing and RightWing bodies of the PointOnCurveExample model with
connection frames properly positioned for a Revolute Joint block.
If the target of a connection frame is a constraint, such as that characteristic of gears in mesh, take
note of the connection frame placements required for assembly. For example, the Common Gear
Constraint block requires that the connection frames on the base and follower bodies be apart by a
distance equal to the sum of their pitch radii when the meshing type is set to External. It requires
also that the z-axes be parallel, and that the x - and y-axes of one be coplanar with those of the other.
1-35
1 Bodies
The assembly requirements of constraint blocks specify how the remainder of the model must hold
the connection frames, partly through body definitions and partly through other joints and
constraints, for the constraint to apply without error. To see how to place connection frames on gear
bodies for assembly via gear constraint blocks, see “Assemble a Gear Model” on page 2-32.
This is the case in a planar four-bar mechanism, for example, when the distance between the
connection frames on any one link exceeds the sum of the equivalent distances in the remaining links
—or when the orientations of the connection frames force the rotation axes of the joints into anything
but a parallel alignment.
You can prevent many assembly errors by carefully defining the connection frames on a body with its
future connections in mind. Consider both the assembly requirements specific to a joint or constraint
block and the kinematic constraints imposed by the remainder of the model. In general, if you
encounter an assembly failure, you must:
1 Identify the unassembled joint or constraint. Use the Simscape Multibody Model Report (Tools >
Model Report in the Mechanics Explorer menu bar).
2 Examine the corresponding connection frames. Use Mechanics Explorer to visualize these
frames. Click the name of the unassembled joint or constraint in the tree view pane to highlight
its frames in the visualization pane. Compare the placement of those frames to the assembly
requirements of the joint or constraint.
1-36
Creating Connection Frames
3 Transform the connection frames to satisfy the joint or constraint assembly requirements. You
can use the Rigid Transform block to apply the required rotation and translation transforms. If a
connection frame is a custom frame belonging to a solid block, you can use that block instead to
edit the frame definition.
For an example showing how to resolve an assembly failure caused by an improperly placed
connection frame, see “Troubleshoot an Assembly Error” on page 2-21.
See Also
More About
• “Modeling Bodies” on page 1-4
• “Working with Frames” on page 1-24
• “Creating Custom Solid Frames” on page 1-83
• “Visualize Simscape Multibody Frames” on page 5-24
1-37
1 Bodies
Geometry is a key attribute of solids and of the bodies they comprise. It features in the solid
visualizations provided by Solid blocks as visual aides during modeling. It features also in the
multibody visualizations displayed in Mechanics Explorer following model assembly and during
simulation. This is one purpose of solid geometry: to enable visualization for an entire modeling
workflow, from the conception of a single solid to the simulation of a complete multibody model.
Solid geometry serves a second, less visible, purpose: to simplify the specification of inertia in the
solid blocks. The bulk of solid inertia parameters are readily computed if both geometry and mass, or,
alternatively, mass density, are known. The solid blocks provide an inertia parameterization,
Calculate from Geometry, that performs these calculations for you. You specify the solid
geometry and a measure of its mass; the block carries out the required numerical integrations to
obtain the remaining inertia parameters—the moments of inertia, products of inertia, and center of
mass.
1-38
Representing Solid Geometry
a visualization means for those geometries—but neither is an adequate replacement for an actual
solid geometry.
The Graphic block merely adds a marker to a frame, typically as a means of highlighting that frame.
The Spline block adds a plane or space curve largely intended for use with the Point on Curve
Constraint block. If you want to visualize solids and bodies, or benefit from the automatic inertia
calculations that solid geometry enables, you must use a solid block.
1 Add a Cylindrical Solid block to a new Simulink model and open the block dialog box. Note the
Geometry parameters section, which by default specifies a cylinder shape 1 m in side.
2 In the Radius parameter line, enter a value of 5 and select units of cm. You can select your units
from the dropdown list or enter them manually.
3 In the Length parameter line, enter a value of 20 and again select units of cm. Note the warning
in the visualization pane urging you to update the solid visualization.
4 In the visualization toolstrip, click the Update Visualization button. The visualization pane
refreshes with the new solid geometry but, due to its small dimensions, it is barely visible. Click
the Fit to View button to optimize the zoom level. Ensure that the solid geometry is as expected.
5 Expand the Inertia parameters section and take note of the Type parameter setting. The
automatic calculation of inertia properties from geometry is by default enabled. To complete the
model of your solid, you need only ensure that its mass or mass density is set to the correct
value. Click OK to accept the current solid settings.
1-39
1 Bodies
Specifying spatial relationships such as this is key to modeling in the Simscape Multibody
environment. You can rotate and translate two frames with respect to one another by applying
operations called rigid transforms between those frames. To learn more about frames and transforms,
see “Working with Frames” on page 1-24.
For ease of modeling, the solid blocks provide a frame creation interface. You can use this interface to
append and align new frames to select geometry features, such as vertices, edges, faces, and
volumes. To learn how to create frames using this interface, see “Creating Custom Solid Frames” on
page 1-83.
Use the Revolved Solid block to model a solid of revolution—a cone with a height of 5 ft and a base
radius also of 5 ft. Visualize the solid in the visualization pane of the Revolved Solid block. Ignore the
relative placement of the solid in the (still incomplete) model.
1 Add a Revolution Solid block to a Simulink model.
2 In the Cross-Section parameter line, enter the coordinate matrix [0 0; 5 0; 0 5] and select
units of ft. Each matrix row provides an [x z] coordinate pair, specified in that order, for a cross-
section point.
1-40
Representing Solid Geometry
3 Click the Update Visualization button and the Fit to View button. Ensure that the solid
geometry is as expected. Click OK to accept the new solid geometry and close the block dialog
box.
The Revolved Solid block generates the revolved shape by sweeping the specified xz cross-section
about the z-axis. To consistently generate a valid shape without errors, the Revolved Solid block
enforces a few rules. Foremost among these is the requirement that, as you proceed from one point in
the coordinate matrix to the next, the solid region lie to your left and the empty (or hollow) region to
your right. The same rule applies to extruded shapes, with one distinction: the cross-section
coordinates are (x, y) pairs and the cross-section lies in the xy plane.
Use the File Solid block to import a detailed bevel gear geometry. The gear geometry was created in
CAD software and subsequently exported in STEP format. Visualize the solid in the visualization pane
of the Solid block and ignore the relative placement of the solid in the model.
openExample('sm/DocImportGearSTEPExample')
addpath(genpath('DocImportGearSTEPSupport'))
• In the File Name parameter field, enter BevelC.step. Specify a desired density for the part
becasue this STEP file does not contain a density.
• Click the Update Visualization button and then the Fit to View button. Ensure that the solid
geometry is as expected. Click OK to accept the new solid geometry and close the block dialog
box.
1-41
1 Bodies
You can obtain a STEP or STL geometry file from a CAD model. Most CAD applications enable you to
export your part geometries in these (among other) formats. If you are adept at using a CAD
application, or have the support of someone who is, you can create a detailed solid geometry in CAD,
export it in a STEP or STL file, and import the final geometry file into a File Solid block.
If you lack a license to a professional CAD application, open-source software such as FreeCAD may
provide a suitable alternative. Onshape, a professional, full-cloud CAD application, provides free
subscription plans. This tool has the advantage of allowing you to import complete multibody
assemblies into the Simscape Multibody environment using the smexportonshape function. For
more information, see “Onshape Import” on page 6-14.
For an example showing how to model this compound body, see “Create a Compound Geometry” on
page 1-15.
1-42
Representing Solid Geometry
See Also
More About
• “Modeling Extrusions and Revolutions” on page 1-44
• “Representing Solid Inertia” on page 1-63
• “Manipulate the Color of a Solid” on page 1-91
• “Visualize a Model and Its Components” on page 1-59
1-43
1 Bodies
A general extrusion is a linear sweep of a custom cross-section along an axis that is normal to the
cross-section plane. The sweep spans the length specified in the Extruded Solid block dialog box. The
cross-section can have an arbitrary outline and one or more hollow sections—though the rules for
specifying cross-sections differ slightly when holes are present.
General extrusion examples include straight beams, plates, spars, struts, and rods. The figure shows
an angle beam, a general extrusion whose cross-section consists of two thin rectangles arranged in
an L shape. The Extruded Solid block sweeps the L shape linearly out of the cross-section plane to
obtain the final beam geometry.
The Extruded Solid block provides a second extrusion shape, named Regular extrusion. This shape
is a simpler version of General extrusion and is suited only for solids whose cross-sections are
regular polygons—those with sides of the same length. The cross-section outline is fixed by the
number of sides of the polygon and it cannot contain holes.
1-44
Modeling Extrusions and Revolutions
Use the Revolved Solid block to make an angular sweep of a cross-section about an axis that lies on
the same plane as the cross-section. The sweep can span a full revolution or a lesser angle between 0
and 360 degrees. As with extruded shapes, the cross-section can have an arbitrary outline with or
without holes.
Revolved examples include cones, domes, pistons, gear shafts, and pipe bends. The figure shows a
cylindrical peg, a Revolved Solid whose cross-section, like the angle beam, consists of two thin
rectangles arranged in an L shape. The Revolved Solid block sweeps the L shape about an axis lying
on the cross-section plane to obtain the final peg geometry.
The coordinate pairs are treated as (x, y) values in the case of extruded shapes and as (x, z) values—
specified in that order—in the case of revolved shapes. The coordinates are resolved in the reference
frame of the Extruded Solid or Revolved Solid block, with the (0, 0) pair coinciding with the origin of
that frame. It is common practice to parameterized the coordinates in terms of MATLAB variables
associated with key solid dimensions—for example, radius or length.
The coordinate pairs connect sequentially in the order implicit in the coordinate matrix. The
connections are by means of straight line segments. The result is a closed polyline that separates the
region to be filled with material (the solid part) from the region to be left hollow (any holes that might
be present and the empty surroundings).
1-45
1 Bodies
The boundary between the two regions is such that, as you proceed along the polyline from one point
to the next, the solid region lies to your left and the hollow region to your right. The first and last
coordinate pairs are often the same, but if they are not, a connection line is inserted between them to
ensure that the cross-section is in fact closed. The animated figure shows the drawing of a binary link
cross-section without holes.
Note that the cross-section is invalid if at any point the polyline crosses itself. However, it is okay for
two line segments to be arbitrarily close or even coincident with each other. In fact, you can exploit
this property to specify a cross-section that has one or more holes.
Revolved Solid coordinate matrices are subject to a special constraint: x-coordinates cannot be
negative. This rule follows partly from the revolution axis (z) used by the Revolved Solid block. When
sweeping the cross-section, any areas to the left of this axis (those with negative x-coordinates)
become overlapped with those to the right (positive x), resulting in an unexpected solid geometry. To
prevent this issue, an error is issued if a Revolved Solid cross-section is found with negative x-
coordinates.
Consider the cross-section shown in the figure. This cross-section belongs to a binary link with round
ends and no holes. Parameterize the cross-section in terms of the dimensions shown and specify it in
the form of a coordinate matrix.
Start by opening a new MATLAB script and save it in a convenient location under the name
modelParams. Add two variables for the dimensions shown in the figure, length (l) and width (w).
Set the length to 20 and the width to 2 (in what will later be units of cm).
l = 20;
w = 2;
Define the round ends as semicircles. First, generate two arrays with the angular spans of the left
and right ends. These arrays enable you to parameterize the (x, y) coordinates using simple
trigonometric expressions. Each array has five points, but for smoother shapes you can specify more.
The transpose symbol (') ensures that A and B are column arrays.
1-46
Modeling Extrusions and Revolutions
Define the coordinate matrices of the right end (csRight) and left end (csLeft). The first column of
each matrix corresponds to the x-coordinate. The second column corresponds to the y-coordinate. The
x-coordinates of the two ends are offset in opposite directions by l/2.
Combine the coordinate matrices into a single matrix named cs. This is the matrix that you must
specify in the Cross-Section parameter of the Revolved Solid block. Note that the straight segments
of the cross-section are automatically generated when the end points of the semicircles are
connected.
cs = [csRight; csLeft];
You can visualize the cross-section outline using the MATLAB plot command. Enter the code shown
below at the MATLAB command prompt.
The plot shows the cross-section of the binary link. The points in the coordinate matrix are shown as
red dots. The resulting cross-section outline is shown as a light gray line. Notice that the end sections
each comprise five points—the number specified in the angular span arrays.
Consider a binary link with a hole at one end. The cross-section of this body comprises two closed
paths—one for the cross-section outline, the other for the hole. The paths are physically separated.
However, you can connect them by cutting each path at a vertex and joining the cut vertices with
additional line segments. The animated figure shows the drawing of a binary link cross-section with
one hole.
1-47
1 Bodies
You can extend this approach to cross-sections with multiple holes. Note that each hole must have a
cut. There is no single best way to approach the cuts. The key is to plan them so that you can traverse
the cross-section—and all of its holes—in a single continuous path while keeping the polyline from
intersecting itself. The animated figure shows the drawing of a binary link cross-section with two
holes.
Modify the coordinate matrix in your modelParams script to include two identical holes as shown in
the figure. Save the script often as you go.
Start by adding a new variable for the hole diameter (d). Set the diameter to 1.2 (in what will later
be units of cm).
d = 1.2;
Generate a new angular span array for the left and right holes. The holes are drawn in the same
order and a single array suffices. The array elements are ordered in a clockwise direction, ensuring
that when generating the cross-section the solid region stays to the left. The number of array
elements has doubled to reflect the wider angular span of the holes (360° vs 180°).
Define the outlines of the left hole (csLeftHole), the right hole (csRightHole), and the connection
line between the two (csConnLine). The x-coordinates are shifted left by half the length (l/2) for the
left hole and right by the same distance for the right hole.
1-48
Modeling Extrusions and Revolutions
Add the new coordinate matrices to the existing cs matrix. The order of the matrices determines the
order in which the complete cross-section is drawn. The result is a variable that you can specify in the
Cross-section parameter of the Revolved Solid block.
As before, you can visualize the cross-section outline using the MATLAB plot command. Ensure that
the plotting code shown below is included in your script. Then, run the script to generate the plot.
The plot shows the cross-section of the binary link. The points in the coordinate matrix are shown as
red dots. The resulting cross-section outline is shown as a light gray line. Note that the hole sections
each comprise ten points—the number specified in the angular span arrays.
1 Open a new Simulink model and, from the Bodies library, add a Extruded Solid block. You can
click the model canvas, type the block name, and make a selection from the options shown. Save
the model in a convenient location as binaryLinkSolid.
2 In the Extruded Solid block dialog box, set the Geometry parameters as shown in the table. Set
the parameter units to cm. The Cross-Section parameter is defined in terms of the cs variable in
your modelParams script.
1-49
1 Bodies
Parameter Value
Cross-Section cs
Length 1
3 Load your modelParams script to your model workspace:
a In the Modeling tab, click Model Explorer. You use this tool to load the modelParams
script that you previously created onto your model workspace.
b In the Model Hierarchy pane, expand the node corresponding to your model
(binaryLinkSolid) and select Model Workspace.
c In the Model Workspace pane, set the Data source parameter to MATLAB File and
browse for your modelParams script. Click the Reinitialize from Source button to load
variables defined in the script.
4
In the Extruded Solid block dialog box, click the Update Visualization button, . The
visualization pane refreshes with the final solid geometry.
Click the Fit to View button to scale the binary link to the size of the visualization pane. Click
the Toggle visibility of frames button to show the solid reference frame. The reference frame
origin coincides with the [0, 0] cross-section coordinate and lies halfway between the extrusion
ends.
Note the jagged appearance of the round ends and holes. This effect results from the small
number of points used in the round portions of the coordinate matrix—csLeftEnd, csRightEnd,
csLeftHole, and csRightHole. Increase the number of elements in the angular span arrays to
obtain a smoother geometry.
See Also
More About
• “Representing Solid Geometry” on page 1-38
• “Representing Solid Inertia” on page 1-63
• “Manipulate the Color of a Solid” on page 1-91
• “Visualize a Model and Its Components” on page 1-59
1-50
Model an Excavator Dipper Arm as a Flexible Body
The Reduced Order Flexible Solid block models a deformable body based on a reduced-order model
that characterizes the geometric and mechanical properties of the body. The basic data imported
from the reduced-order model includes:
• A list of coordinate triples that specify the position of all interface frame origins relative to a
common reference frame.
• A symmetric stiffness matrix that describes the elastic properties of the flexible body.
• A symmetric mass matrix that describes the inertial properties of the flexible body.
There are several ways to generate the reduced-order data required by this block. Typically, you
generate a substructure (or superelement) by using finite-element analysis (FEA) tools.
This example uses the Partial Differential Equation Toolbox™ to create a reduced-order model for a
flexible dipper arm, such as the arm for an excavator or a backhoe. You start with the CAD geometry
of the dipper arm, generate a finite-element mesh, apply the Craig-Bampton FEA substructuring
method, and generate a reduced-order model. The model ReducedOrderFlexibleSolid uses the
reduced-order data from this example. In the model, the dipper arm is mounted on top of a rotating
tower as part of a test rig. For more information, see “Using the Reduced Order Flexible Solid Block -
Flexible Dipper Arm” on page 8-91.
Add geometry file to the search path for the current MATLAB® session:
openExample("sm/ExcavatorDipperArmAsFlexibleBodyExample");
addpath(genpath("ExcavatorDipperArmAsFlexibleBodySupport"));
Step 1: Define the Geometry and Material Properties of the Dipper Arm
The file Dipper.STL contains a triangulation that defines the CAD geometry of the dipper arm. To
view the geometry stored in this file, use the MATLAB® functions stlread and trisurf:
stlFile = 'Dipper.STL';
figure
trisurf(stlread(stlFile))
axis equal
1-51
1 Bodies
The dipper arm is constructed from steel. To represent its material properties, set these values for
Young's modulus, Poisson's ratio, and mass density:
The dipper arm has three interface frames where you can connect other Simscape™ Multibody™
elements, such as joints, constraints, forces, and sensors:
• The cylinder connection point, where the arm connects to a hydraulic cylinder that actuates the
arm vertically.
• The bucket connection point, where the arm connects to the excavator bucket.
• The fulcrum point, where the arm connects to the excavator boom.
The positions of all interface frame origins are specified in meters relative to same common reference
frame used by the CAD geometry.
1-52
Model an Excavator Dipper Arm as a Flexible Body
To generate the mesh for the dipper arm, first call the createpde (Partial Differential Equation
Toolbox) function, which creates a structural model for modal analysis of a solid (3-D) problem. After
importing the geometry and material properties of the arm, the generateMesh (Partial Differential
Equation Toolbox) function creates the mesh.
feModel = createpde('structural','modal-solid');
importGeometry(feModel,stlFile);
structuralProperties(feModel, ...
'YoungsModulus',E, ...
'PoissonsRatio',nu, ...
'MassDensity',rho);
generateMesh(feModel, ...
'GeometricOrder','quadratic', ...
'Hmax',0.2, ...
'Hmin',0.02);
Each interface frame on the block corresponds to a boundary node that contributes six degrees of
freedom to the reduced-order model. There are several ways to ensure that the FEA substructuring
method preserves the required degrees of freedom. For example, you can create a rigid constraint to
connect the boundary node to a subset of finite-element nodes on the body. You can also use
structural elements, such as beam or shell elements, to introduce nodes with six degrees of freedom.
This example uses a multipoint constraint (MPC) to preserve the six degrees of freedom at each
boundary node. To identify the geometric regions (such as faces, edges, or vertices) to associate with
each MPC, first plot the arm geometry by using the function pdegplot (Partial Differential Equation
Toolbox):
figure
pdegplot(feModel,'FaceLabels','on','FaceAlpha',0.5)
1-53
1 Bodies
You can zoom, rotate, and pan this image to determine the labels for the faces corresponding to the
boundary nodes. These faces define the MPCs associated with the boundary nodes in the dipper arm:
faceIDs = [1,27,23]; % List in the same order as the interface frame origins
To verify these values, plot the mesh and highlight the selected faces:
figure
pdemesh(feModel,'FaceAlpha',0.5)
hold on
colors = ['rgb' repmat('k',1,numFrames-3)];
assert(numel(faceIDs) == numFrames);
for k = 1:numFrames
nodeIdxs = findNodes(feModel.Mesh,'region','Face',faceIDs(k));
scatter3( ...
feModel.Mesh.Nodes(1,nodeIdxs), ...
1-54
Model an Excavator Dipper Arm as a Flexible Body
feModel.Mesh.Nodes(2,nodeIdxs), ...
feModel.Mesh.Nodes(3,nodeIdxs), ...
'ok','MarkerFaceColor',colors(k))
scatter3( ...
origins(k,1), ...
origins(k,2), ...
origins(k,3), ...
80,colors(k),'filled','s')
end
hold off
Call the function structuralBC (Partial Differential Equation Toolbox) to define the MPCs for the
boundary nodes in these faces:
for k = 1:numFrames
structuralBC(feModel, ...
'Face',faceIDs(k), ...
'Constraint','multipoint', ...
'Reference',origins(k,:));
end
1-55
1 Bodies
The function reduce (Partial Differential Equation Toolbox) applies the Craig-Bampton order
4
reduction method and retains all fixed-interface modes up to a frequency of 10 radians per second.
Store the results of the reduction in a data structure arm. Transpose the ReferenceLocations
matrix to account for the different layout conventions used by Partial Differential Equation Toolbox
and Simscape Multibody.
The function computeModalDampingMatrix, which is defined at the bottom of this page on page 1-
57, computes a reduced modal damping matrix with a damping ratio of 0.05:
dampingRatio = 0.05;
arm.C = computeModalDampingMatrix(dampingRatio,rom.K,rom.M);
The boundary nodes in the reduced-order model must be specified in the same order as the
corresponding interface frames on the block. This order is given by the rows of the array origins. If
the order of the MPCs is different than the order specified by origins, permute the rows and
columns of the various matrices so that they match the original order.
assert(size(arm.P,1) == numFrames);
for i = 1:numFrames
for j = 1:numFrames
if isequal(arm.P(j,:),origins(i,:))
frmPerm(i) = j;
dofPerm(6*(i-1)+(1:6)) = 6*(j-1)+(1:6);
continue;
end
end
end
assert(numel(frmPerm) == numFrames);
assert(numel(dofPerm) == size(arm.K,1));
arm.P = arm.P(frmPerm,:);
arm.K = arm.K(dofPerm,:);
arm.K = arm.K(:,dofPerm);
arm.M = arm.M(dofPerm,:);
arm.M = arm.M(:,dofPerm);
arm.C = arm.C(dofPerm,:);
arm.C = arm.C(:,dofPerm);
The model ReducedOrderFlexibleSolid uses the data structure arm to set up the parameters of
the Reduced Order Flexible Solid block. In the block, these parameters import the reduced-order
data:
• Origins: arm.P
1-56
Model an Excavator Dipper Arm as a Flexible Body
For more information, see “Using the Reduced Order Flexible Solid Block - Flexible Dipper Arm” on
page 8-91.
This function computes a modal damping matrix associated with the stiffness matrix K and mass
matrix M. This function applies a single scalar damping ratio to all of the flexible (non-rigid-body)
normal modes associated with K and M.
function C = computeModalDampingMatrix(dampingRatio,K,M)
[V,D] = eig(K,M);
[d,sortIdxs] = sort(diag(D));
V = V(:,sortIdxs);
% Due to small numerical errors, the six eigenvalues associated with the
% rigid-body modes may not be exactly zero. To avoid numerical issues,
% check that the first six eigenvalues are close enough to zero. Then
% replace them with exact 0 values.
MV = M*V;
generalizedMasses = diag(V'*MV);
naturalFrequencies = sqrt(d);
C = MV * diag(2*dampingRatio*naturalFrequencies./generalizedMasses) * MV';
end
See Also
Reduced Order Flexible Solid | stlread | trisurf | createpde | importGeometry |
structuralProperties | generateMesh | pdegplot | structuralBC | reduce
1-57
1 Bodies
More About
• “Using the Reduced Order Flexible Solid Block - Flexible Dipper Arm” on page 8-91
1-58
Visualize a Model and Its Components
In this section...
“Visualize a Complete Multibody Model” on page 1-59
“Visualize an Individual Solid Geometry” on page 1-60
“A Note on Imported Geometries” on page 1-61
The visualizations consist of the multibody subassemblies, compound bodies, and simple bodies
present in your models. Mechanics Explorer displays model entities such as solid geometries, spline
curves, inertia icons, and frames. You can selectively show and hide individual entities using the
context-sensitive menu of the Mechanics Explorer tree view pane. See “Selective Model
Visualization” on page 5-15.
A visualization is static when you update a model and dynamic when you simulate a model. The static
visualization in this case shows the model in its initial configuration, with the joints in their initial
states. The dynamic visualization shows a 3-D animation that you can record—using either Video
Creator or the smwritevideo function—see “Create a Model Animation Video” on page 5-28.
You can manipulate the viewpoint using the tool strip located above the visualization pane. The tool
strip enables you to rotate, roll, pan, and zoom the model view. A Camera Manager enables you to
create dynamic cameras that move with the model to keep it in view during simulation—see
“Visualization Cameras” on page 5-8.
3 Click Run. Mechanics Explorer plays an interactive 3-D animation based on the simulation
results.
1-59
1 Bodies
Equivalent inertia ellipsoids provide an intuitive means to visualize variable inertias (modeled using
the General Variable Mass block). These ellipsoids are rendered dynamically, with their dimensions
and poses obtained at each time step from the specified instantaneous inertial properties. Ellipsoid
visualization is not available on model update. Variable inertial properties are specified through
physical signals whose values are inaccessible to the blocks until the simulation begins.
The block visualizations are similar to those provided in Mechanics Explorer. You can rotate, roll, pan,
and zoom the view using a tool strip located above the visualization pane. The tool strip includes
buttons for standard views such as Front, Top, and Isometric. You can show or hide the frames of
the block.
1-60
Visualize a Model and Its Components
You can refresh block visualizations without updating or simulating a model. The visualizations
refresh the moment you click the Update Visualization button in the visualization tool strip. Using
MATLAB variables in block parameters does not affect your ability to refresh a visualization.
1 At the MATLAB command prompt, enter smnew to open the Simscape Multibody model template.
The template contains commonly used blocks, including the Brick Solid block.
2 Open the Brick Solid block dialog box. The visualization pane is by default expanded to show an
isometric view of the default solid—a gray brick.
3 Set the Graphic > Color parameter to [0.5 0 0]—an RGB vector corresponding to a dark red
color.
4 Click the Update Visualization button, located above the solid visualization pane. The
visualization updates to show what is now a red brick.
1-61
1 Bodies
See Also
Related Examples
• “Manipulate the Visualization Viewpoint” on page 5-4
• “Create a Model Animation Video” on page 5-28
• “Go to a Block from Mechanics Explorer” on page 5-27
1-62
Representing Solid Inertia
Inertia is a basic attribute of anything you might construe as a body. It is a resistance to a change in
one’s state of motion, and, equivalently, a measure of the force or torque needed to induce a certain
acceleration. Unlike other solid attributes, such as geometry or color, it is strictly required for the
simulation of a multibody dynamics model. For more information about multibody dynamics
simulations, see “Multibody Dynamics”. In particular, the ends of a joint—its frames—must each
connect to an inertia, which is to say that where motion is allowed, there must exist an inertia for an
applied force or torque to act upon.
Representing Inertias
You can model an inertia element in isolation, without the intent to represent a body. Such inertias
are useful, for example, when simulating the vibrations induced by a clump of mud on a rotating
automobile wheel. The clump is separate from the wheel body and you can model it as such. In
addition, its geometry and color are in this case trivial details and you can disregard them for
modeling purposes. In so doing, you treat the clump as a plain inertia—one lacking any attributes
other than inertia.
Isolated plain inertias are uncommon in a model. Generally, you account for inertia in the course of
modeling a complete body—something with geometry and color, like a wing in the flapping wing
mechanism discussed in “Modeling Bodies” on page 1-4. You start with a concept of the body, model
that body as a collection of solids, and specify the attributes of those solids to obtain a complete
representation of the body. Solids are the things that you model and inertia merely one of their
attributes.
Relevant Blocks
You add inertia to a model using blocks from the Body Elements library. Relevant blocks include the
solid blocks, Inertia, and those in the Variable Mass sublibrary. You can model a complete solid or a
plain inertia. Either can have fixed or variable inertia parameters, though the exact parameterization,
and therefore the type of solid or inertia, depends on the block. The term “solid” is used here to
denote an element whose attributes extend beyond merely inertia and the term “inertia,” when used
to refer to an element, one whose attributes encompass only inertia.
Fixed Solids
Use the solid blocks when modeling solids and the bodies they comprise. These blocks enable you to
specify geometry and color, key attributes if solid visualization is important to you. They also enable
you to have the less accessible parameters of rotational inertia automatically computed from the solid
1-63
1 Bodies
geometry and either mass or mass density. Even in cases where geometry and color are superfluous
details, the solid blocks are often the most convenient means of specifying inertia. Note that the
geometry and inertia parameters of the solid blocks are strictly constant. To model solids with either
as a variable attribute, you must use blocks from the Variable Mass sublibrary.
Variable Solids
Use the solid blocks in the Body Elements > Variable Mass library to model complete solids with
variable inertia parameters, such as mass, and inertia-dependent dimensions, such as length and
radius, that can vary dynamically with the inertia inputs. Blocks that represent solids are identified as
such by having the word Solid in their names—for example, Variable Cylindrical Solid and Variable
Brick Solid. These blocks differ from the solid blocks in the parent library in that one or more inertia
parameters can change, and from the General Variable Mass block in that they possess geometry and
color.
Fixed Inertias
Use the Inertia block as a means of adjusting the inertia of a solid or body. Geometry and color are
considered irrelevant for modeling purposes. You can subtract a mass to account for the existence of
a hollow region, such as an empty compartment in a vessel originally modeled without one. You can
also add a mass to account for the presence of small disturbances, such as the clumps of mud that
sometimes linger on an automobile wheel. Note that you can make the same adjustments, sometimes
more intuitively, using the more sophisticated solid blocks.
Variable Inertias
Reserve the General Variable Mass block for the special cases in which mass, center of mass, or the
inertia tensor must change in response to some input—often just time itself—without making
assumptions about solid geometry. You can model events such as the scooping of a load by a backhoe
(an example of a variable mass), the movement of an occupant on a manlift (an example of a variable
center of mass), and the sloshing of a fluid load contained in a tank truck (an example of a variable
inertia tensor).
Inertia Parameters
Solid blocks have access to geometry data and can therefore calculate inertia parameters given a
shape and a mass. This feature greatly reduces the number of parameters that you must specify in a
model. Automatic inertia calculation is always enabled in solid blocks, such as Brick Solid and
Cylindrical Solid. It is enabled by default in the solid blocks, meaning that you can change this
setting.
You can also specify the inertia parameters explicitly, for example, to precisely capture the inertia of a
body for which you have only a rough geometry. An example is an odd-shaped link, for example one
typical of a backhoe excavator arm, that you have approximated using a simple Brick Solid block
shape. The solid geometry is in this case not very accurate and you may prefer to specify the inertia
parameters using CAD (or other) data.
If you choose to specify inertia explicitly, there are two parameterizations that you can use. One
enables you to treat the solid or inertia as a point mass: the Point Mass parameterization. The other
enables you to treat the solid or inertia as a distributed mass: the Custom parameterization. You can
select the option best suited for your application using the Inertia > Type dropdown list.
1-64
Representing Solid Inertia
Note that the Point Mass and Custom parameterizations are available only in those blocks that
support the explicit specification of inertia. The variable solid blocks in the Body Elements > Variable
Mass library do not provide either. In those blocks, the center of mass and inertia tensor are strictly
constrained to the solid geometry and density and are, for this reason, always automatically
calculated during simulation.
The Point Mass Approximation
A point mass is an approximation that has as its only inertial parameters the center of mass and the
total mass—a measure of translational inertia and therefore of the resistance to a sudden change in
translational velocity. Rotational inertia is assumed negligible and is ignored. The location of the
center of mass can vary with respect to the origin of the local reference frame.
A distributed mass is a more general representation of inertia. It has among its inertial parameters
not only the total mass and center of mass, but also the moments of inertia, and products of inertia.
The moments and products of inertia comprise what is known as the inertia tensor or matrix.
Together, these parameters suffice to completely describe, from a multibody modeling perspective,
the distribution of a mass in space.
Use caution when connecting inertias with zero moments of inertia, such as point masses, to joints
with rotational degrees of freedom—those composed at least in part of revolute or spherical joint
primitives. The combined moment of inertia about the rotational axes of the joint must be nonzero on
each side. The reason for this is simple: the angular acceleration about an axis becomes infinite
regardless of the torque applied if the moment of inertia about that axis is zero. This behavior is not
physical and is disallowed in a model.
Reference Frames
Blocks in the Body Elements library have reference frame ports that you connect to resolve the
placement of the respective elements—solids, inertias—in the context of a model. The reference
1-65
1 Bodies
frames are a rigid part of those elements and naturally move with them as a unit. They are used,
directly or indirectly, to define the inertias and, in solids, the geometries of the elements.
If the concept of a frame is foreign to you, see “Working with Frames” on page 1-24. Succinctly, a
frame is an axis triad much like a Cartesian coordinate system. It has a position and orientation that
you can define using the frame creation interface of the Solid block or the parameters of the Rigid
Transform block. All positions and orientations in a model—of solids, inertias, joints and constraints,
forces and torques, sensors—are defined through frames.
Visualization Options
You can visualize solids and inertias in a model. The type of visualization that you get depends on the
block that you use. Solid blocks, including those from the Body Elements > Variable Mass library,
enable you to visualize their respective elements using the geometries that you specify. You can also
visualize the solid using a simple graphic marker such as a sphere—for example, to highlight its
position in cases where geometry is known to be inaccurate.
Inertias lack geometry and color and naturally do not support geometry-based visualization. You must
visualize such elements using alternative means. If the element is associated with a General Variable
Mass block, you can use the same graphic markers provided in the solid blocks or an equivalent
inertia ellipsoid—a shape whose dimensions depend directly on the inertia parameters that you
specify. If the element is associated with an Inertia block, you can use the markers of the solid blocks
or an inertia icon.
For more information on visualization, see “Visualize a Model and Its Components” on page 1-59.
Add a plain fixed inertia to a double-pendulum model, position it at the free end of the outer link, and
set its mass to 25 g using the Point Mass parameterization:
1-66
Representing Solid Inertia
4 Simulate the model. Mechanics Explorer opens with a dynamic visualization of your updated
double-pendulum. Notice the inertia icon used to denote the location of your inertia element.
See “Try It: Specify a Custom Inertia” for an example showing how to specify the parameters of a
Custom inertia.
When you rigidly connect the simpler elements—via frame connection lines and, if needed, Rigid
Transform blocks—you obtain an aggregate whose inertia properties mirror those of the complex
solid or inertia you intended to represent. The binary link shown in the figure serves as an example.
You can divide the link into three sections, represent each section using a separate block, and
connect the respective reference frames using appropriate rigid transforms.
For an example showing how to specify the geometry of a binary link through compounding, see
“Create a Compound Geometry” on page 1-15.
There is no requirement in the Simscape Multibody environment that the inertia parameters be
positive. This includes the mass and moments of inertia, both parameters that in the physical world
are strictly positive. Negative inertias enable you to model compound inertias with hollow sections by
subtraction and are therefore useful in certain models.
The binary link again serves as an example. You can represent the link as a single piece without holes
using one block, and subtract from its ends the inertias of the holes using additional blocks. As
before, you must use rigid transforms to properly position the inertia reference frames relative to
each other.
1-67
1 Bodies
For an example, showing how to specify an inertia by compounding, see “Create a Compound Inertia”
on page 1-18.
See Also
More About
• “Modeling Bodies” on page 1-4
• “Multibody Modeling”
• “Compounding Body Elements” on page 1-15
• “Specifying Custom Inertias” on page 1-69
• “Specifying Variable Inertias” on page 1-77
1-68
Specifying Custom Inertias
In this section...
“Key Inertia Conventions” on page 1-69
“Inertia Matrix Definitions” on page 1-69
“CAD as an Inertia Data Source” on page 1-72
“Automatic Inertia Calculation” on page 1-75
• The products of inertia are defined using a negated convention, one with a minus sign inserted,
explicitly, in the mass integrals. An alternate convention exists in which a minus sign does not
accompany the mass integrals. Recall that the products of inertia are the off-diagonal elements of
the inertia matrix.
• The center of mass is defined with respect to the local reference frame of the block. In solids with
imported CAD shapes, this frame is generally that assumed by your CAD application in its inertia
calculations. It is possible, however, to modify a solid geometry file so that the two frames no
longer match.
The inertia matrix comprises the moments and products of inertia. The moments of inertia occupy the
diagonal matrix positions and measure the dispersion, or spread, of the mass distribution about the
axes of the inertia frame of resolution. The greater the spread about an axis, the larger the moment
of inertia corresponding to that axis.
The products of inertia occupy the off-diagonal positions and measure the asymmetry of the mass
distribution with respect to the planes of the inertia frame of resolution. The greater the asymmetry
about a plane, the larger the products of inertia associated with any axis in that plane. The figure
illustrates these relationships.
1-69
1 Bodies
The matrix is symmetric with respect to the main diagonal line: off-diagonal elements whose indices
are reciprocals of each other share the same value. This constraint reduces the number of unique
products of inertia from the original six (all those in off-diagonal positions) to the three that you must
specify in a block (those with a unique combination of indices):
• Iyz = Izy
• Izx = Ixz
• Ixy = Iyx
The products of inertia, Iij, are defined using the prevalent, negated, convention adopted by a number
of CAD applications:
• I = −
yz ∫ yz ρdv
V
• I = −
zx ∫ zx ρdv
V
• I = −
xy ∫ xy ρdv
V
where ρ is mass density, v is volume, and V is the total volume of integration. The x, y, and z
coordinates are the Cartesian components of the distance vector spanning from the center of mass to
an infinitesimal element of mass ρdv. The moments of inertia, Iii, are similarly defined:
• I =
xx ∫y
V
2 + z2 ρdv
• I =
yy ∫z
V
2
+ x2 ρdv
• I =
zz
V
∫x 2 + y2 ρdv
When applied to simple shapes such as cylindrical shells and rectangular beams, these definitions
give rise to well-known algebraic equations that are often published in standard engineering tables.
1-70
Specifying Custom Inertias
You can reference such tables when specifying the inertia parameters explicitly. The complete inertia
matrix, according to the Simscape Multibody convention, is:
The moments of inertia are by definition positive numbers. However, the products of inertia can be
either positive, negative, or zero. They are zero if the axes of the inertia frame of resolution happen to
coincide with the principal axes of inertia. The moments of inertia are then called the principal
moments of inertia and the inertia matrix is said to be diagonal:
Ixx 0 0
I = 0 Iyy 0
0 0 Izz
The number of nontrivial inertia matrix elements that you must specify is in this case reduced to
three—the principal moments of inertia. For this reason, the principal axes of inertia can be a
convenient frame in which to specify the inertia matrix elements. This is the inertia frame of
resolution assumed in the highly symmetrical preset shapes of the solid blocks.
The same, however, is not generally true of Extruded Solid or Revolved Solid solid shapes, nor is it of
those imported via STEP or STL files. In Extruded Solid and Revolved Solid shapes, the frame
placement depends closely on how you define the geometrical cross-sections. In imported shapes, it
depends on how, relative to the local zero coordinate, the part geometries were modeled.
As a best practice, always consider the placement of the inertia frame of resolution when specifying
the elements of the inertia matrix explicitly, particularly when using a solid block. The frame position
is always that of the center of mass, but its orientation relative to a solid geometry, when using a solid
block, may not always coincide with the principal axes of inertia.
Consider the rectangular beam shown in the figure. Determine its mass, center of mass, moments of
inertia, and products of inertia. Specify the calculated parameters explicitly in a Brick Solid block
using a Custom inertia parameterization.
Assume a construction of aluminum and a corresponding mass density of 0.09754 lbm/in^3. Use the
beam dimensions:
1-71
1 Bodies
• Width x = 3 in
• Height y = 4 in
• Length z = 10 in
Add a Brick Solid block to a Simscape Multibody model. In the Brick Solid block dialog box, specify
the beam geometry: set the Geometry > Dimensions parameter to [3 4 10] in. This array
corresponds to the beam dimensions [x y z].
The geometry type affects the placement of the local reference frame (R) and therefore the inertia
calculations themselves. In the visualization toolstrip, click the Toggle visibility of frames button.
Frame R is located at the center of mass and its axes are parallel to the beam dimensions (x, y, and
z).
Specify the Inertia Parameters
Calculate the inertia parameters from the density and dimensions of the beam. Then, specify the
calculated values in the Inertia section of the Brick Solid block parameters:
m = ρ x · y · z = 11.7 lb
• Center of Mass — Centroid coordinates with respect to the local reference frame (R):
x, y, z = 0, 0, 0
• Moments of Inertia — From standard expressions with respect to the inertia frame of resolution
(I):
m
Ixx, Iyy, Izz = y2 + z2 , z2 + x2 , x2 + y2 = 113.1, 106.3, 24.4 lbm*in^2
12
• Products of Inertia — From symmetry with respect to the inertia frame of resolution (I):
Some CAD applications, SolidWorks among them, use an alternate inertia convention to define the
elements of the inertia matrix. This convention removes the minus sign from the product-of-inertia
definitions. The Iyz product of inertia, for example, becomes:
Iyz = ∫ yz ρdv
V
If your source of inertia data adopts this convention, you must explicitly negate the products of
inertia before specifying their values in the Simscape Multibody environment. As an example,
consider a SolidWorks inertia matrix given as:
1-72
Specifying Custom Inertias
To correctly specify the matrix elements in the Simscape Multibody environment, you must treat
them as follows:
Rather than reference the inertia data in a CAD assembly model, you can import that model into the
Simscape Multibody environment. CAD import is based on the smimport function, which parses a
multibody description file in XML format and generates an equivalent block diagram with all block
parameters prespecified—inertia parameters included.
You must export your CAD model in a valid XML format, meaning one that conforms to the Simscape
Multibody XML schema, before you can import it. This option may suit you only if you have a
complete CAD assembly model. For individual CAD parts, use the STEP file import feature of the solid
block and set the Inertia > Type parameter to Calculate from Geometry.
For more information, see “Convert CAD Assembly into Simscape Multibody Model” on page 6-2.
Determine the inertia parameters for the L-beam shape shown in the figure. Then, specify them
explicitly in a solid block by setting the inertia parameterization to Custom. Use the mass properties
data provided in this example for a SolidWorks model of the beam.
Open the Solid Model
In the visualization pane, click the Toggle visibility of frames button. The visualization pane shows
two frames, one labeled R and the other I.
1-73
1 Bodies
Frame R is the local reference frame of the solid. It coincides with what SolidWorks users refer to as
the output coordinate system of the part model. This frame is located at the lower corner of the L-
shape on one of the two longitudinal ends of the beam. You must specify the center of mass relative to
this frame.
Frame I is a custom solid frame included for your convenience. This frame coincides with the inertia
frame of resolution. Its origin is at the center of mass and its axes are parallel to those of the local
reference frame. You must specify the moments and products of inertia relative to this frame.
Review the SolidWorks Data
The SolidWorks model provides for the L-beam part the following mass properties data:
The data includes the coordinates of the center of mass with respect to the “output coordinate
system.” This coordinate system coincides with the local reference frame (R) of the corresponding
Simscape Multibody solid.
The data includes also a matrix with the moments and products of inertia “taken at the center of mass
and aligned with the output coordinate system.” This coordinate system coincides with the inertia
frame of resolution (I) of the Simscape Multibody solid.
1-74
Specifying Custom Inertias
Expand the Inertia parameters section of the File Solid block dialog box. Then, change the inertia
parameterization by setting the Inertia > Type parameter to Custom. The complete set of inertia
parameters appears for you to specify.
1 Set the Mass parameter to 2.19 lb. This is the mass corresponding to the density of aluminum.
2 Set the Center of Mass parameter to [0.58 1.08 5.00] in. These are the [x y z] coordinates
of the center of mass shown in the SolidWorks report.
3 Set the Moments of Inertia parameter to [20.10 18.89 2.49] lbm*in^2. These are the
[Lxx Lyy Lzz] moments of inertia shown in the SolidWorks report.
4 Set the Products of Inertia parameter to [0 0 0.6] lbm*in^2. These are the negated [Lyz
Lzx Lxy ] products of inertia shown in the SolidWorks report.
The block uses the geometry and mass parameters to compute the remaining inertia parameters—the
center of mass, moments of inertia, and products of inertia—relative to the appropriate frame of
reference. The calculations are based on the assumption of a mass density that is constant and
uniform.
You can view the calculation results inside the solid block, in an expandable section named Display
Inertia. The center of mass is given relative to the local reference frame (R), and the moments and
products of inertia relative to the inertia frame of resolution (I). These are the same frames relative to
which you might specify these parameters.
Configure the File Solid block of the DocLBeamInertiaExample model to calculate the inertia
parameters from the solid geometry and its mass density. Then, view the calculated parameters.
1 In the dialog box of the File Solid block, switch the Inertia > Type parameter to Calculate
from Geometry. A Display Inertia node appears below the Density parameter.
2 Set the Density parameter to 0.09754 lbm/in^2. This value corresponds to a solid of
aluminum construction and it is the same assumed in the SolidWorks data provided in “Review
the SolidWorks Data” on page 1-74.
3 Expand the Display Inertia node and click the Update button. The inertia parameters under
Display Inertia are populated with the calculated values. Compare them to the values provided
in the SolidWorks mass properties data.
1-75
1 Bodies
See Also
More About
• “Modeling Bodies” on page 1-4
• “Compounding Body Elements” on page 1-15
• “Specifying Variable Inertias” on page 1-77
1-76
Specifying Variable Inertias
You can specify your variable inputs using Simscape or Simulink blocks. You must convert any
Simulink signals into physical signals using the Simulink-PS Converter block. Avoid sudden changes
as these can increase model stiffness and slow down simulation. Ensure that the signal dimensions
agree with the ports:
1-77
1 Bodies
Variable inertia ellipsoids are shown during simulation only. The figure shows an inertia visualization
representing a fluid load carried by a tank truck.
1-78
Specifying Variable Inertias
1 At the MATLAB command prompt, enter smnew. The command opens a model template with
commonly used Simscape Multibody blocks.
2 Add the following blocks to the model canvas:
4 In the Spring and Damper Force block dialog box, set the Natural Length parameter to 0.2 m
and the Spring Stiffness parameter to 10 N/m.
5 In the Cartesian Joint block dialog box, expand the Z Prismatic Primitive (Pz) area, select the
State Targets > Specify Position Target check box, and set the Value parameter to 0.1 m.
1 In the Cartesian Joint block dialog box, expand the Z Prismatic Primitive (Pz) area and select
the Sensing > Position check box. The block exposes a physical signal output port with the
oscillator frame position.
2 Add the following blocks to the model canvas:
1-79
1 Bodies
1 In the General Variable Mass block dialog box, set the Type parameter to Custom. This option
enables you to model a variable mass distribution with rotational inertia.
2 Set the Mass, Center of Mass, and Inertia Matrix parameters to Constant and the Mass >
Value parameter to 0.2 kg.
3 Run the simulation and open the Scope block. The plot shows the position of the reference frame
of the variable mass. Note that the oscillation frequency and amplitude stay constant throughout
simulation.
Mechanics Explorer opens with a 3-D animation of the model. The visualization comprises only an
inertia ellipsoid—here a sphere due to the symmetry of the default inertia tensor used in the
model. In the menu bar, select View > Show Frames to show all the frames in the model. Note
that the ellipsoid dimensions stay constant during simulation, reflecting the constant inertial
properties specified in the model.
1-80
Specifying Variable Inertias
1 In the General Variable Mass block dialog box, set the Center of Mass and Inertia Matrix
parameters each to Constant. The physical signal ports used to vary their values during
simulation become hidden, leaving only the solid mass as a variable.
2 Add these blocks to the model canvas:
4 In the Ramp block dialog box, set the Slope parameter to 0.1 and the Initial output parameter
to 0.2. The Ramp signal is passed to the General Variable Mass block in the default Simscape
units of mass, kg. The signal corresponds to a steadily increasing mass that starts at 0.2 kg and
ends at 1.2 kg following a 10-second simulation.
5 Run the simulation and open the Scope block. The position plot shows a variable oscillation
frequency and amplitude. The increasing mass causes the oscillation frequency to increase and
the amplitude to decrease.
1-81
1 Bodies
Mechanics Explorer updates the visualization results. Note that the ellipsoid dimensions
decrease as the simulation progresses, reflecting their inverse proportionality to the variable
mass.
See Also
More About
• “Modeling Bodies” on page 1-4
• “Compounding Body Elements” on page 1-15
• “Specifying Custom Inertias” on page 1-69
1-82
Creating Custom Solid Frames
Solid Frames
By default, the Solid block provides only a reference frame port, labeled R. In simple shapes, such as
Brick Solid, Spherical Solid, and Cylindrical Solid, the reference frame origin coincides with the solid
center of mass. The same is generally not true of the more sophisticated Extruded Solid and Revolved
Solid shapes, nor is it of imported solid shapes.
In many applications, the reference frame of a solid is inadequate for connecting joints and
constraints or for applying forces and torques. In such cases, you can create new frames external to
the Solid block using the Rigid Transform block. This block enables you to define the new frame by
specifying translation and rotation transforms numerically.
An alternative approach, and one that is often more intuitive, is to create new frames directly in the
Solid block dialog box using the frame-creation interface. This interface enables you to define new
frames interactively by aligning the frame origin and axes with geometric features such as planes,
lines, and points.
1-83
1 Bodies
button .
Frames that you define by geometric features are specific to the shapes the features belong to. If you
make the frame origin coincident with the vertex of a brick, the new frame is valid only for that
particular brick shape. If you change shapes, you must edit or delete the new frame, as the geometric
features it depends on no longer exist.
The frame-creation interface has three sections for specifying the following:
• Frame origin
• Primary axis
• Secondary axis
The figure shows a top view of the three-sided extrusion you model in this tutorial. You align the
primary axis (z) with the surface normal vector nz and the secondary axis (x) with the line vector nx.
1-84
Creating Custom Solid Frames
Because nx is not normal to the primary axis, the secondary axis is the projection of nx onto the
normal plane of the primary axis.
1 From the Body Elements library, add one Extruded Solid block to a new model. The Extruded
Solid block provides its own visualization utility. You do not need to update the block diagram to
visualize the solid shape or its frames.
2 In the Extruded Solid block dialog box, specify these parameters.
Parameter Value
Geometry > Cross-section [0,0;1,0;1,0.5]
3
In the visualization toolstrip, select the Update Visualization button . The visualization pane
updates with the three-sided extrusion that you specified.
4 Select the Toggle visibility of frames button. The visualization pane shows all the frames in the
solid. At this point, the solid has a single frame—its reference frame. The reference frame origin
coincides with the [0,0] cross-section coordinate in the midplane of the extrusion.
1-85
1 Bodies
In the Frames expandable area of the Extruded Solid block dialog box, select the Create button .
The Solid block opens the frame-creation interface.
In the Frame Name parameter, enter ECF (short for Extrusion Corner Frame). The frame name
identifies the new frame in the Solid block visualization pane. It also appears as the frame port label
on the Solid block.
Under Frame Origin, select At Center of Mass. The visualization pane updates with the new frame
at the center of mass of the solid. This frame has the default frame orientation, that of the reference
frame. The label ECF identifies the new frame.
1-86
Creating Custom Solid Frames
Experiment with other frame origin locations. Define the origin location using one of the extrusion
vertices.
1 Under Frame Origin, select Based on Geometric Feature. This option enables you to select a
point or the center of a plane or line as the frame origin.
2 In the visualization pane, select the vertex shown in the figure. The vertex is in the top plane of
the extrusion. Ensure the view point is set to Isometric. In the Frame Origin area, ensure the
vertex is named Location of top point 3.
3 Under Frame Origin, select the Use Selected Feature button. The visualization pane updates
with the frame origin at the selected corner.
The primary axis constrains the remaining two axes to lie on its normal plane. In this sense, the
primary axis plays the dominant role in setting the orientation of the frame. Make the primary axis
normal to the surface that contains the cross-section hypotenuse:
1 In the Frame Axes area under Primary Axis, select Based on Geometric Feature. The
direction you specify in the next steps is that of the default primary axis, +Z.
2 In the visualization pane, rotate the solid and select the surface shown. The visualization pane
highlights the surface and shows its normal vector. In the Frame Axes area under Primary Axis,
ensure the surface is named Surface normal of side surface 3.
1-87
1 Bodies
3 In the Frame Axes area under Primary Axis, select the Use Selected Feature button. The
visualization pane updates with the z axis of the ECF frame, shown in dark blue, parallel to the
normal vector of the selected surface.
The secondary axis completes the definition of the new frame. In conjunction with the primary axis,
the secondary axis fully constrains the direction of the third axis. The secondary axis is itself
constrained to lie on the normal plane of the primary axis. To see the effects of this constraint, define
the secondary axis based on a line not normal to the primary axis:
1 In the Frame Axes area, set the Secondary Axis parameter to -X. The direction you specify in
the following steps is that of the -X axis.
2 In the Frame Axes area, under Secondary Axis, select Based on Geometric Feature.
3 In the visualization pane, rotate the solid and select the line shown. In the Frame Axes area,
under Secondary Axis, ensure this line is named Curve direction of top curve 1.
1-88
Creating Custom Solid Frames
4 Select the Use Selected Feature button. The visualization pane updates wit the x axis of the
frame, shown in red, partially aligned with the selected line.
The two are not completely aligned as the selected line does not lie on the normal plane of the
primary axis. The secondary axis is therefore the projection of the selected line onto the normal
plane of the primary axis.
1 Select the Save button. The visualization pane shows the solid with the final version of the frame
you defined.
2 In the main interface of the Solid block dialog box, select OK or Apply. The Solid block commits
the new frame to the model and exposes a new frame port labeled with the frame name you
specified.
1-89
1 Bodies
See Also
More About
• “Modeling Bodies” on page 1-4
• “Working with Frames” on page 1-24
• “Creating Connection Frames” on page 1-33
• “Visualize Simscape Multibody Frames” on page 5-24
1-90
Manipulate the Color of a Solid
You select a visual-property parameterization through the Graphic > Visual Properties block
parameter. The figure contrasts the two parameterizations. On the left is a solid with Simple visual
properties. On the right is the same solid with Advanced visual properties—including Specular
Color and Shininess parameters, which impart to the solid a slight metallic sheen.
Try It
1 Add a Spherical Solid block to a new model canvas. The block provides its own visualization
pane. You can use this pane to visualize the solid even if the model is not topologically valid. In
later examples, the curved spherical surface makes the specular highlights and ambient shadows
easier to see.
2 In the Spherical Solid block dialog box, set the Graphic > Visual Properties parameter to
Advanced. You set the visual-property parameterization individually for each solid.
1-91
1 Bodies
provides the color opacity—the degree to which the solid obstructs other components located behind
it. Omitting the A element is equivalent to setting its value to 1.
Try It
Identify the color and opacity given by the [R,G,B,A] vectors below:
• [0,0,1,1] — Denotes a solid color with no red or blue contents, maximum green content, and
maximum opacity. The solid is bright green and fully opaque.
• [1,0,0,0.5] — Denotes a solid color with maximum red content, no green or blue contents, and
partial opacity. The solid is bright red and transparent.
See It
1 In the Spherical Solid block dialog box, set the Visual Properties parameter to Simple. This
setting is the parameter default.
2 Expand the Visual Properties node. Color and Opacity appear as the active visual property
parameters.
1-92
Manipulate the Color of a Solid
See It
1 In the Spherical Solid block dialog box, set the Visual Properties parameter to Advanced.
2 Expand the Visual Properties node. The solid colors and shininess appear as the active visual
property parameters.
Try It
1 Under the Graphic > Visual Properties node, change the Diffuse Color parameter to
[1,0,0,0.5].
2
In the visualization pane, click the button to refresh the solid visualization.
Delete the fourth vector element in the Diffuse Color parameter or set its value to 1 in order to
make the solid opaque again.
1-93
1 Bodies
Try It
Give the specular highlights a bright green hue. Set the Diffuse Color vector to [1,0,0,1] in order
to make the solid opaque. Then:
1 In the Graphic > Visual Properties node, lower the Shininess parameter to 10. This value
increases the highlight size, making the specular color easier to see.
2 Change the Specular Color parameter to [0,1,0,1]. This vector sets the highlight color to
bright green.
3
In the visualization pane, click the button to refresh the solid visualization. The specular
color combines with the diffuse color to give highlight areas a green hue.
Try It
1 In the Graphic > Visual Properties node, set the Ambient Color parameter to
[0.15,0.15,0.3]. This vector sets the shadow color to dark blue.
2
In the visualization pane, click the button to refresh the solid visualization. The ambient
color combines with the diffuse color to give shadow areas a blue hue.
1-94
Manipulate the Color of a Solid
Try It
1 Under the Graphic > Visual Properties node, change the Emissive Color parameter to
[1,0,0,1].
2
In the visualization pane, click the button to refresh the solid visualization.
See Also
More About
• “Representing Solid Geometry” on page 1-38
• “Representing Solid Inertia” on page 1-63
• “Modeling Bodies” on page 1-4
1-95
2
Multibody Systems
In this section...
“Study the Joints and Constraints to Model” on page 2-2
“Assemble Bodies Using Joints and Constraints” on page 2-2
“Guide Model Assembly” on page 2-2
“Verify Model Assembly” on page 2-3
Identify the joints and constraints between the various bodies. Joints can be real, such as that
between a piston and its case, or virtual, such as that between two planets.
Model the degrees of freedom between bodies by connecting their frames through joints. You can
further constrain these degrees of freedom through specialized constraints, such as those between
gears. See “Assemble a Gear Model” on page 2-32 for an example.
2-2
Multibody Assembly Workflow
Specify the state targets of the various joints. You can specify the desired position and velocity of a
joint at time zero. If the state targets are valid and compatible, the joints assemble in the states
specified. See the “Guide Assembly and Visualize Model” on page 2-19 section of “Model a Closed-
Loop Kinematic Chain” on page 2-16 for an example.
Update the block diagram. Examine the model visualization for assembly issues. Open the Simscape
Variable Viewer or the Simscape Multibody Model Report to see if all state targets have been
satisfied. See the “Verify Model Assembly” on page 2-19 section of “Model a Closed-Loop Kinematic
Chain” on page 2-16 for an example.
2-3
2 Multibody Systems
In multibody dynamics models, joints impose the primary kinematic constraints that determine how
bodies can move relative to each other. A joint can be a physical connection, such as that between the
case and shaft of a linear hydraulic actuator, or a virtual connection, such as that between the Earth
and the moon. In Simscape Multibody, you model both connection types using joint blocks.
Gear and Constraint blocks also impose kinematic constraints between bodies. How are joint blocks
different? Gear and constraint blocks are parameterized in terms of the DOFs they remove between
bodies, and joint blocks are parameterized in terms of the DOFs they provide, through modules called
joint primitives.
Joint DOFs are a measure of joint mobility. Precluding other constraints in a model, a joint with more
DOFs allows greater freedom of motion between the adjoining bodies. Joint DOFs also have a
mathematical interpretation. They are the minimum number of state variables needed to fully
determine the configuration of a joint at each time step during simulation.
Consider a rectangular joint. This joint allows translation in a plane and it therefore has two
translational DOFs—one for each spatial dimension. At each time step, the joint configuration is fully
determined by two state variables, the position coordinates in the plane of motion [x(t), y(t)]. This
means, for example, that you can fully prescribe motion at this joint using two position input signals.
2-4
Modeling Joint Connections
The table summarizes the DOFs that the various joint blocks provide.
The actual DOFs at a joint are often fewer in number than the joint alone would allow. This happens
when kinematic constraints elsewhere in the model limit the relative motion of the adjoining bodies.
Such constraints can arise from gears in mesh, forbidden DOFs due to other joints in closed
kinematic loops, and fixed distances and angles between bodies, among other factors.
Joint Primitives
Joint blocks are assortments of joint primitives, basic yet complete joints of various kinds you cannot
decompose any further—at least without losing behavior such as the rotational-translational coupling
of the lead screw joint. Joint primitives range in number from zero in the Weld Joint block to six in the
Bushing Joint block. There are five joint primitives:
2-5
2 Multibody Systems
• Prismatic Primitive — Allows translation along a single standard axis (x, y, or z). Joint blocks can
contain up to three prismatic joint primitives, one for each translational DOF. Prismatic primitives
are labeled P*, where the asterisk denotes the axis of motion, e.g., Px, Py, or Pz.
• Revolute Primitive — Allows rotation about a single standard axis (x, y, or z). Joint blocks can
contain up to three revolute joint primitives, one for each rotational DOF. Revolute primitives are
labeled R*, where the asterisk denotes the axis of motion, e.g., Rx, Ry, or Rz.
• Spherical Primitive — Allows rotation about any 3-D axis, [x, y, z]. Joint blocks contain no more
than one spherical primitive, and never in combination with revolute primitives. Spherical
primitives are labeled S.
• Lead Screw Primitive — Allows coupled rotation and translation on a standard axis (e.g., z). This
primitive converts between rotation at one end and translation at the other. Joint blocks contain no
more than one lead screw primitive. Lead screw primitives are labeled LS*, where the asterisk
denotes the axis of motion.
• Constant Velocity Primitive — Allows rotation at constant velocity between intersecting though
arbitrarily aligned shafts. Joint blocks contain no more than one constant velocity primitive.
Constant velocity primitives are labeled CV.
The table summarizes the joint primitives and DOFs that the various Joint blocks provide.
Why use Joint blocks with spherical primitives? Those with three revolute primitives are susceptible
to gimbal lock—the natural but often undesired loss of one rotational DOF when any two rotation
axes become aligned. Gimbal lock leads to simulation errors due to numerical singularities. Spherical
primitives eliminate the risk of gimbal-lock errors by representing 3-D rotations using 4-D quantities
known as quaternions.
Joint Inertia
Simscape Multibody joints are idealized. They differ from real joints in that they have no inertia—a
suitable approximation in most models, where the impact of joint inertia on system dynamics is often
2-6
Modeling Joint Connections
negligible. This is the case, for example, in the constant-velocity joints of automobile driveline
systems, where shaft inertia can dwarf joint inertia.
If joint inertia is important in your model, you can account for it using Solid or Inertia blocks.
Connect the block reference frame ports to the appropriate joint frames and specify the joint inertial
properties in the block dialog boxes. You can specify joint mass or density, products of inertia,
moments of inertia, and center of mass. For more information on how to specify inertia, see
“Representing Solid Inertia” on page 1-63.
See Also
More About
• “Representing Solid Inertia” on page 1-63
2-7
2 Multibody Systems
In this section...
“Connecting Joints” on page 2-8
“Orienting Joints” on page 2-9
“Guiding Assembly” on page 2-9
“Verifying Model Assembly” on page 2-10
You model an articulated system by interconnecting bodies through joints and occasionally gears and
other constraints. Bodies contribute their inertias to the model, while joints, gears, and constraints
determine the relative degrees of freedom that exist between the bodies. You interconnect the two
component types by linking frame ports on joint, gear, and constraint blocks to frame ports on body
subsystems.
Simscape Multibody automatically assembles your model when you update the block diagram. During
model update, Simscape Multibody determines the initial states of joints—their positions and
velocities—so that the resulting assembly satisfies all kinematic constraints in the model. This process
occurs in two phases, with the assembly algorithm first computing the joint positions and then the
joint velocities. The complete process is called model assembly.
Connecting Joints
Joints connect to bodies through frames. Each joint block contains two frame ports, base (B) and
follower (F), identifying the connection points in the adjoining bodies and the relative directions they
can move in. When you connect these ports to frames in the body subsystems, you determine how the
bodies themselves connect upon model assembly.
Joint Frames Identifying Connection Points and Rotation Axis of Aircraft Propeller
If a joint has no actuation and no sensing outputs, its frame ports are fully interchangeable. In this
case, you can switch the bodies that the ports connect to without affecting model dynamics or joint
sensing outputs. If the joint does have actuation inputs or sensing outputs, you may need to reverse
the actuation or sensing signals to obtain the same dynamic behavior and simulation results.
To change the connection points of a joint, you must modify the connection frames in the adjoining
body subsystems. You do this by specifying a translation transform using a Rigid Transform block. You
can add new Rigid Transform blocks to the body subsystems or, if appropriate, change the translation
transforms in existing Rigid Transform subsystems.
For more information on how Simscape Multibody software interprets frame ports, nodes, and lines,
see “Working with Frames” on page 1-24.
2-8
How Multibody Assembly Works
Orienting Joints
To obtain the motion expected in a model, you must align its various joint motion axes properly. This
means aligning the joints themselves as observed or anticipated in the real system. Misaligning the
joint axes may lead to unexpected motion but it often leads to something more serious, such as a
failure to assemble and simulate.
You can specify and change joint alignment by rotating the connection frames local to the adjoining
body subsystems. For this purpose, you specify rotation transforms using Rigid Transform blocks,
either by adding new blocks to the body subsystems or, if appropriate, by changing the rotation
transforms in existing blocks within the subsystems.
Why change the orientation of joints through body subsystem frames? Each primitive in a joint block
has a predetermined motion axis, such as x or z. The axis definition is fixed and cannot be changed.
Realigning the connection frames local to the adjoining body subsystems provides a natural way to
reorient joints while avoiding confusion over which axis a particular joint uses.
Guiding Assembly
Joints can start simulation from different states. For example, the crank joint of a crank-rocker
linkage can start at any angle from 0° to 360°. As a result, during model assembly, Simscape
Multibody must choose from many equally valid states. You can guide the states chosen by specifying
state targets in the joint block dialog boxes.
State targets need not be exact values. If Simscape Multibody cannot achieve a state target exactly, it
searches for the joint state nearest to the state target. For example, if you specify a position state
target of 60° but the joint can only reach angles of 0° to 45°, Simscape Multibody attempts to
assemble the joint at 45°.
How close the actual joint state is to the state target depends on the kinematic constraints in your
model, any conflicts with other state targets, and the state target priority level—a ranking that
determines which of two state targets to satisfy if they prove to be mutually incompatible. You can set
the priority level to Low or High.
Simscape Multibody first attempts to satisfy all state targets exactly. If a state target conflict arises,
Simscape Multibody ignores the low-priority state targets and attempts to satisfy only the high-
priority state targets. If a state target conflict still exists, Simscape Multibody ignores also the high-
priority state targets and attempts to assemble the model in the nearest valid configuration.
You can specify state targets for all joints in an open kinematic chain. However, to avoid simulation
errors, every closed chain must contain at least one joint without state targets.
2-9
2 Multibody Systems
Joint Assembly Failure in Four-Bar Linkage with Exceedingly Long Ground Link
To ensure that your model has assembled correctly, use these Simscape Multibody and Simscape
utilities:
• Mechanics Explorer — Simscape Multibody visualization utility. Visually examine your model from
different points of view to ensure that its bodies connect at the expected locations and with the
proper orientations.
• Variable Viewer — Simscape state-reporting utility. Check the assembly status of individual joints
and constraints and compare your state targets to the actual joint states achieved during
assembly.
2-10
How Multibody Assembly Works
• Statistics Viewer — Simscape metrics-reporting utility. Check, among other metrics, the degrees
of freedom, number of joints, and number of constraints in your model.
See Also
More About
• “Working with Frames” on page 1-24
2-11
2 Multibody Systems
Applying this criterion to a four-bar linkage, an assembly of four bodies (n = 4) and four joints (j = 4)
with one rotational DOF each (fi = 1), yields a mobility of one DOF—indicating that a single input
variable suffices to fully control the linkage configuration. As mechanisms grow in complexity,
manually calculating total DOFs becomes more time-consuming, so Simscape Multibody
automatically computes them for you.
You can view the mechanism DOFs through the Simscape Statistics Viewer, shown below for the four-
bar featured example. You open the Statistics Viewer. In the Apps gallery, click Simscape Variable
Viewer. Enter openExample("sm/FourBarExample") at the MATLAB command prompt to open
the four-bar model and view its DOFs through the Statistics Viewer.
2-12
Model an Open-Loop Kinematic Chain
Model Overview
This example shows how to model a double pendulum—a simple kinematic chain comprising two
moving bodies connected in series via two revolute joints. A third body represents a mechanical
ground and is rigidly connected to the inertial World frame. The custom
DocCompoundRigidBodiesLibrary library provides the body subsystem blocks used in the
example.
Revolute Joint blocks enable you to model the joints connecting adjacent bodies and help set their
initial states. Simscape Multibody software satisfies a joint state target precisely if it is kinematically
valid and not in conflict with other state targets. A Priority parameter lets you specify which targets
to attempt to satisfy first.
Build Model
1 Start a new model.
2 Drag these blocks into the model. The two Revolute Joint blocks provide the double pendulum
two rotational degrees of freedom.
2-13
2 Multibody Systems
Block Quantity
Pivot Mount 1
Binary Link A 2
5 Connect the blocks as shown in the figure.
2-14
Model an Open-Loop Kinematic Chain
To check the assembly status of the revolute joints, use the Model Report utility. You can open this
utility from the Mechanics Explorer menu bar by selecting Tools > Model Report. The figure shows
the assembly information for the double pendulum.
Simulate Model
Run the simulation. Mechanics Explorer shows a 3-D animation of the double pendulum assembly.
The assembly moves due to gravity, specified in the Mechanism Configuration block.
2-15
2 Multibody Systems
This example shows how to model a four bar system, which is a closed kinematic chain that comprise
four links through revolute joints. One of the links connects to the World Frame block and acts as a
ground. Here, use two rigidly connected pivots to replace the link. The custom
DocCompoundRigidBodiesLibrary library provides the body subsystem blocks used in the
example.
Use Revolute Joint blocks to model the joints that connect adjacent links and set the initial states of
the joints. You can satisfy a joint state target precisely if the target is kinematically valid and not in
conflict with other state targets. Note that in the Z Revolute Primitive (Rz) > State Targets
section, you can use the Priority parameter to specify the priority level of a target.
Build Model
To model the four-bar linkage:
2-16
Model a Closed-Loop Kinematic Chain
3 Connect and name the blocks as shown in the figure. Make sure that the base frame ports of the
Rigid Transform blocks connect to the World Frame block.
4 From the Simscape > Multibody > Joints library, drag four Revolute Joint blocks into the
model.
5 At the MATLAB command prompt, enter openExample('sm/
DocDoublePendulumModelExample','supportingFile','DocCompoundRigidBodiesLib
rary.slx'). A custom library with compound body subsystem blocks opens up.
6 From the DocCompoundRigidBodiesLibrary library, drag the following blocks.
Block Quantity
Pivot Mount 2
Binary Link A 2
Binary Link B 1
7 Connect and name the blocks as shown in the figure. Make sure that you position the frame ports
of the custom body subsystem blocks exactly as shown.
2-17
2 Multibody Systems
2-18
Model a Closed-Loop Kinematic Chain
1 In the Base-Crank Revolute Joint block dialog box, expand State Targets and select Specify
Position Target.
2 Specify the Value parameter as -30 deg.
3 For the Coupler-Rocker Revolute Joint block, in the Z Revolute Primitive (Rz) > State Targets
section, select the Specify Position Target parameter, and specify the Value parameter as 0
deg and Priority parameter as Low (approximate).
4 On the Modeling tab of the Simulink Toolstrip, click Update Model. Mechanics Explorer opens
with a static display of the four-bar linkage in its initial configuration. The image shows the
isometric view of the four-bar linkage.
To open the Simscape Variable Viewer, on the Debug tab of the Simulink Toolstrip, in the
Diagnostics section, select Simscape > Variable Viewer. To open the Simscape Multibody Model
Report, on the Mechanics Explorer menu bar, select Tools > Model Report.
As shown in the image, the yellow marker indicates that the Base-Rocker Revolute Joint state target
was satisfied approximately only. The remaining green marker indicates that the Base-Crank Revolute
Joint state target was satisfied precisely.
2-19
2 Multibody Systems
Simulate Model
Run the simulation. Mechanics Explorer shows a 3-D animation of the four-bar assembly. The
assembly moves due to gravity.
See Also
PS-Simulink Converter | Revolute Joint
More About
• “Model an Open-Loop Kinematic Chain” on page 2-13
2-20
Troubleshoot an Assembly Error
Model Overview
In closed-loop systems, joints and constraints must be mutually compatible. For example, in a four-bar
linkage, all revolute joints must spin about parallel axes. If one of the joints spins about a different
axis, assembly fails and the model does not simulate.
To simplify the troubleshooting process, Simscape Multibody provides Model Report. This tool helps
you pinpoint the joints and constraints that caused assembly to fail. Once you identify these joints and
constraints, you can then determine which of their frames to correct—and how to correct them.
In this example, you identify the assembly error source in an aiming mechanism model using Model
Report. Then, using Mechanics Explorer, you determine how to correct that error source. The
sm_dcrankaim_assembly_with_error featured example provides the basis for this example.
Explore Model
To open the model, at the MATLAB command line, enter sm_dcrankaim_assembly_with_error.
The model opens in a new window.
The figure shows a schematic of the system that the model represents. This system contains four
bodies, labeled A-D. These bodies connect in a closed loop via four joints, labeled Ri, Ro, Rg, and Pg.
When connected to each other, these components form a system with one degree of freedom.
2-21
2 Multibody Systems
The model represents the components of this system using blocks. Each block represents a physical
component. A World Frame block provides the ultimate reference frame in the model. The figure
shows the block diagram that the model uses to represent the double-crank aiming mechanism.
2-22
Troubleshoot an Assembly Error
To represent the bodies, the model contains four subsystem blocks, labeled Rigid Body A-D. Each
subsystem contains one Cylindrical Solid block and multiple Rigid Transform blocks. The Cylindrical
Solid block provides geometry, inertia, and color to the body subsystem. The Rigid Transform blocks
provide the frames that you connect the joints to. A Reference Frame block identifies the ultimate
reference frame in the subsystem block.
The model labels the body subsystem blocks Rigid Body A-D. To examine the block diagram for a body
subsystem, right-click the subsystem block and select Mask > Look Under Mask. The figure shows
the block diagram for Rigid Body A.
To represent the joints, the model contains four joint blocks. Three joints provide one rotational
degree of freedom between a pair of bodies. You represent each of these joints with a Revolute Joint
block. A fourth joint provides one translational degree of freedom between a pair of bodies. You
represent this joint with a Prismatic Joint block. The model labels the revolute joint blocks Ro, Rg,
and Ri, and the prismatic joint block Pg.
Update Model
As the model name suggests, this model contains an error. The error prevents the model from
assembling successfully, which causes simulation to fail. To update the model and investigate the
assembly error:
Mechanics Explorer opens with a static display of your model in its initial state. Because the
model contains an assembly error, Simscape Multibody issues an error message. Ignore that
message for now.
Model Report opens in a new window. A red square indicates that the model, as expected, has failed
to assemble. A second red square indicates that an unassembled joint, Pg, is the only contributing
2-23
2 Multibody Systems
factor in the model assembly error. This information enables you to concentrate your troubleshooting
efforts on a small block diagram region—that surrounding the Pg joint block.
The error message that Simscape Multibody issued during model update identifies position violation
as the root cause of assembly failure. This suggests that the frames connected by joint Pg are
improperly aligned. To confirm this hypothesis, check the orientation of these frames in Mechanics
Explorer.
2 In the Mechanics Explorer visualization pane, examine the position and orientation of the
highlighted frames. These are the frames that appear in a light turquoise blue color.
2-24
Troubleshoot an Assembly Error
The two frames are offset along the Z axis. This offset is valid, since joint Pg contains a prismatic
primitive aligned with the Z axis, providing the frames with one translational degree of freedom along
that axis. However, the two frames are also rotated with respect to each other about the common Z
axis. This offset is invalid, since joint Pg contains no Revolute or Spherical primitives, and hence no
rotational degrees of freedom about any axis. To correct the model assembly error, you must rotate
either of the two frames so that all of their axes are parallel to each other.
1 In the tree pane of Mechanics Explorer, right-click the Pg node and select Go To Block.
Simscape Multibody brings the block diagram to the front and highlights the Pg block.
2 Right-click the Rigid Body C subsystem block and select Mask > Look Under Mask.
3 Double-click the Slide Frame Transform block and select the new parameter values that the
table provides. Select OK.
Simulate Model
You can now simulate the model. Mechanics Explorer opens with a 3-D animation of your model. The
figure shows a snapshot of the animation. Rotate, roll, pan, and zoom to explore.
2-25
2 Multibody Systems
You can use the Model Report tool to verify the assembly status. To do this, in the Mechanics Explorer
menu bar, select Tools > Model Report. In Model Report, check that the assembly status icons for
the model and its joints are green circles. The green circles indicate that the model has assembled
correctly.
See Also
Related Examples
• “Model an Open-Loop Kinematic Chain” on page 2-13
• “Model a Closed-Loop Kinematic Chain” on page 2-16
More About
• “Modeling Joint Connections” on page 2-4
2-26
Modeling Gear Constraints
The kinematics of gears in mesh arise from what are, in computational terms, algebraic constraints
between the gear rotations. Gear teeth cannot physically overlap and the gears must, at a contact
point known as the pitch point, move with the same instantaneous linear velocity.
Gear constraint blocks capture the effects of these constraints in a model. The blocks, found in the
Gears and Couplings > Gears library, include:
• Bevel Gear Constraint — Couple two gears, generally conical in cross-section, with intersecting
rotation axes meeting at a right or general angle. Bevel gear assemblies are common in the
drivetrains of rotorcraft, where they transmit torque between rotor shafts mounted at an angle.
• Common Gear Constraint — Couple two gears, generally cylindrical in cross-section, with internal
or external meshing and parallel rotation axes. Common gear assemblies appear in automotive
transmissions, often as planetary gear trains, that transmit power from engine to wheels at preset
torque ratios.
• Rack and Pinion Constraint — Couple a rotating pinion to a translating rack with the respective
motion axes facing at a right angle. Rack-and-pinion assemblies are common in power steering
systems, where they transform a rotation of the steering wheel into a translation of the tie rods,
causing the steering arms and wheels to turn.
2-27
2 Multibody Systems
• Worm and Gear Constraint — Couple a worm and a gear with nonintersecting rotation axes facing
at a right angle. Worm-and-gear assemblies form the foundation of slew drives built into solar
trackers that are designed to follow the sun and maximize the intensity of sunlight striking a solar
panel array.
The joints define the degrees of freedom available to the gears before they are brought into mesh.
The degrees of freedom encode the types of motion the gears are capable of and the respective
motion axes. The gear constraint couples the gears so that they move as though in mesh at a speed
ratio determined from the gear (pitch) radii or tooth counts.
More complex model topologies are possible. In a planetary gear train, a ring gear adds a second
kinematic loop to the model. Planet gears attached to a carrier add still more kinematic loops. Still,
no matter how unique the gear assembly, the model must by its nature comprise at least one
kinematic loop.
2-28
Modeling Gear Constraints
• The distance between the z-axes be equal to the distance between the gear centers.
• The follower frame origin lie on the xy plane of the base frame.
• The z-axes of the base and follower frames point in the same direction.
The gear constraint blocks enforce the assembly restrictions, but during model assembly only, when
the gears are first placed in mesh. Once simulation starts, it is the task of the model to ensure that
the gear placement still satisfies the assembly requirements. The gear constraint blocks then enforce
the meshing constraint but merely monitor the assembly constraints, to ensure that the gears remain
in a valid configuration.
2-29
2 Multibody Systems
For examples showing how to properly place the gear connection frames using Rigid Transform
blocks, see these sections of “Assemble a Gear Model” on page 2-32:
• Bevel Gear
• External Spur Gear
• Internal Spur Gear
• Rack and Pinion
• Worm and Gear
For more detailed geometries, use the Extruded Solid block. This shape enables you to specify the
toothed cross-sectional shapes of gears and racks. The Extruded Solid block generates 3-D extrusions
by sweeping the cross-sections along their normal axes. The figure shows an example with spur gear
2-30
Modeling Gear Constraints
geometries modeled as general extrusions. For an example showing how to model a simple body with
a Extruded Solid block, see “Modeling Extrusions and Revolutions” on page 1-44.
For precise geometries, you can load 3-D shapes into File Solid blocks using STEP or STL files. You
must obtain the STEP or STL files from external sources. If you have CAD models of gears, worms,
and racks, you may be able to export them in STEP or STL format for use in Simscape Multibody
software. The figure shows an example with spur gear geometries imported from CAD models via
STEP files.
See Also
Related Examples
• “Assemble a Gear Model” on page 2-32
2-31
2 Multibody Systems
The examples that follow show how to position and orient gear bodies so that they satisfy the
assembly requirements of the various gear constraint blocks. Each example starts with an overview of
relevant gear dimensions and frame placements. These attributes guide the selection of rigid
transforms needed to ensure that the gears assemble in mesh.
The models share the same block diagram topology, with the model components—bodies, joints, and
gear constraint—arranged in a kinematic loop in each case. The figure shows a simple loop. The
carrier body is in the examples considered to be fixed to the world frame, with its inertia
consequently reduced to a superfluous detail and the body altogether ignored.
• File Solid — Provides the gear geometries, inertias, and colors. The gear geometries, complete
with teeth or threads to more clearly show the gears in mesh, are imported from STEP files. The
poses of the gear reference frames relative to the gear geometries are obtained from the same
files.
• Joint — Provides the gear bodies with the requisite degrees of freedom. Revolute Joint blocks
enable rotation about a single axis. Prismatic Joint blocks enable translation along a single axis.
Velocity state targets specified in the joint blocks set the gears in motion.
2-32
Assemble a Gear Model
• Rigid Transform — Rotates and translates the joints and the attached gear bodies so that they are
properly placed for meshing. Rigid Transform blocks provide the means to change the gear
placements and therefore to satisfy the gear assembly requirements.
• Gear constraint — Couples the motions of the gear bodies. Gear constraint blocks eliminate one
degree of freedom between the gears, causing them to move as though in mesh. The examples
showcase, one by one, the various gear constraint blocks.
Bevel Gear
The DocBevelGearStart model provides an example of a bevel gear assembly. To open the model,
at the MATLAB command prompt, enter:
openExample('sm/DocGearModelExample','supportingFile','DocBevelGearStart.slx')
The model, based on the Bevel Gear Constraint block, is complete in every sense but one—all rigid
transforms are zero and the gear reference frames are therefore coincident in space.
2-33
2 Multibody Systems
This short tutorial shows how suitable transforms follow readily from the gear dimensions and
assembly constraints—and how, once specified in the Rigid Transform blocks, they enable the gear
model to assemble as though in mesh without error.
Gear Geometry
The bevel gears, A and B, are identical in size, with a pitch radius of 2.8 cm in each case. The gear
reference frames are placed with origins at the gear centers and z-axes aligned with the gear rotation
axes so as to face away from the gear shafts. This alignment is consistent with the Revolute Joint
blocks, which allow rotation about the z-axis only.
Gear Assembly
The gear rotation axes meet at a right angle. The reference frame of bevel gear A sits at an offset of
[2.8, 0, 0] cm, in Cartesian coordinates, relative to the world frame. The reference frame of bevel
gear B sits at an offset of [0, 0, 2.8] cm relative to the world frame and at an angle of 90 deg
about the y-axis also of the world frame.
2-34
Assemble a Gear Model
Complete the bevel gear model by specifying the rigid transforms described in the gear assembly
schematic. The conceptual animation that follows shows the incremental effects that the rigid
transforms would have were they to apply in sequence during model update.
If you have not yet done so, open the incomplete bevel gear model by entering:
openExample('sm/DocGearModelExample','supportingFile','DocBevelGearStart.slx')
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of bevel gear A relative to the world frame as described in the
Gear Assembly schematic.
• In the Rigid Transform B block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of bevel gear B relative to the world frame as described in the
Gear Assembly schematic.
• In the Rigid Transform B block dialog box, specify the Rotation parameters shown in the table.
These parameters set the orientation of bevel gear B relative to the world frame as described in
the Gear Assembly schematic.
2-35
2 Multibody Systems
• Simulate the model. Mechanics Explorer opens with the dynamic gear visualization shown at the
beginning of this example. To see a complete bevel gear model, at the MATLAB command prompt
enter:
openExample('sm/DocGearModelExample','supportingFile','DocBevelGear.slx')
Simscape Multibody opens a bevel gear model with the rigid transforms described in this example.
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearExternalStart.slx')
The model, based on the Common Gear Constraint block, is complete in every sense but one—all rigid
transforms are zero and the gear reference frames are therefore coincident in space.
2-36
Assemble a Gear Model
This short tutorial shows how suitable transforms follow readily from the gear dimensions and
assembly constraints—and how, once specified in the Rigid Transform blocks, they enable the gear
model to assemble as though in mesh without error.
Gear Geometry
The small spur gear, A, has a pitch radius of 4 cm. The large spur gear, B, has a pitch radius of 8 cm.
The gear reference frames are placed with origins at the gear centers and z-axes aligned with the
gear rotation axes so as to face away from the gear shafts. This alignment is consistent with the
Revolute Joint block, which allows rotation about the z-axis only.
Gear Assembly
The spur gear rotation axes are parallel to each other. The reference frame of the small spur gear sits
at an offset of [-4, 0, 0] cm, in Cartesian coordinates, relative to the world frame. The reference
frame of the large spur gear sits at an offset of [-8, 0, 0] cm, also relative to the world frame.
2-37
2 Multibody Systems
Complete the external spur gear model by specifying the rigid transforms described in the gear
assembly schematic. The conceptual animation that follows shows the incremental effects that the
rigid transforms would have were they to apply in sequence during model update.
If you have not yet done so, open the incomplete external spur gear model by entering:
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearExternalStart.slx')
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the small spur gear, A, relative to the world frame as
described in the Gear Assembly schematic.
• In the Rigid Transform B block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the large spur gear, B, relative to the world frame as
described in the Gear Assembly schematic.
2-38
Assemble a Gear Model
• Simulate the model. Mechanics Explorer opens with the dynamic gear visualization shown at the
beginning of this example. To see a complete external spur gear model, at the MATLAB command
prompt enter:
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearExternal.slx')
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearInternalStart.slx')
The model, based on the Common Gear Constraint block, is complete in every sense but one—all rigid
transforms are zero and the gear reference frames are therefore coincident in space.
2-39
2 Multibody Systems
This short tutorial shows how suitable transforms follow readily from the gear dimensions and
assembly constraints—and how, once specified in the Rigid Transform blocks, they enable the gear
model to assemble as though in mesh without error.
Gear Geometry
The spur gear, A, has a pitch radius of 4 cm. The ring gear, B, has a pitch radius of 8 cm. The gear
reference frames are placed with origins at the gear centers and z-axes aligned with the gear rotation
axes so as to face away from the gear shafts. This alignment is consistent with the Revolute Joint
block, which allows rotation about the z-axis only.
Gear Assembly
The gear rotation axes are parallel to each other. The spur gear reference frame sits at an offset of
[-4, 0, 0] cm, in Cartesian notation, relative to the world frame. The ring gear reference frame
sits left with its origin and z-axis coincident with those of the world frame.
Complete the internal spur gear model by specifying the rigid transforms described in the gear
assembly schematic. The conceptual animation that follows shows the incremental effects that the
rigid transforms would have were they to apply in sequence during model update.
2-40
Assemble a Gear Model
If you have not yet done so, open the incomplete internal spur gear model by entering:
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearInternalStart.slx')
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the spur gear, A, relative to the world frame as described in
the Gear Assembly schematic.
• Simulate the model. Mechanics Explorer opens with the dynamic gear visualization shown at the
beginning of this example. To see a complete internal spur gear model, at the MATLAB command
prompt, enter:
openExample('sm/DocGearModelExample','supportingFile','DocCommonGearInternal.slx')
openExample('sm/DocGearModelExample','supportingFile','DocRackAndPinionStart.slx')
The model, based on the Rack and Pinion Constraint block, is complete in every sense but one—all
rigid transforms are zero and the gear reference frames are therefore coincident in space.
2-41
2 Multibody Systems
This short tutorial shows how suitable transforms follow readily from the gear dimensions and
assembly constraints—and how, once specified in the Rigid Transform blocks, they enable the gear
model to assemble as though in mesh without error.
Gear Geometry
The pinion, A, has a pitch radius of 2 cm. The pinion reference frame is placed with origin at the
pinion center and z-axis along the pinion axis. The rack reference frame is placed with origin 3.75 cm
from the rack edge and z-axis along the rack length. The frame alignments are consistent with the
Revolute Joint and Prismatic Joint blocks, which allow motion about or along the z-axis only.
Gear Assembly
The rack translation axis is at a right angle to the pinion rotation axis. The pinion reference frame sits
at an offset of [0, 2, 0] cm, in Cartesian notation, relative to the world frame. The rack reference
frame sits at an angle of 90 deg relative to the positive y-axis of the world frame.
2-42
Assemble a Gear Model
Complete the rack-and-pinion model by specifying the rigid transforms described in the gear
assembly schematic. The conceptual animation that follows shows the incremental effects that the
rigid transforms would have were they to apply in sequence during model update.
If you have not yet done so, open the incomplete rack-and-pinion model by entering:
openExample('sm/DocGearModelExample','supportingFile','DocRackAndPinionStart.slx')
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the pinion, A, relative to the world frame as described in the
Gear Assembly schematic.
• In the Rigid Transform B block dialog box, specify the Rotation parameters shown in the table.
These parameters set the orientation of the rack, B, relative to the world frame as described in
the Gear Assembly schematic.
• Simulate the model. Mechanics Explorer opens with the dynamic gear visualization shown at the
beginning of this example. To see a complete rack-and-pinion model, at the MATLAB command
prompt enter:
2-43
2 Multibody Systems
openExample('sm/DocGearModelExample','supportingFile','DocRackAndPinion.slx')
openExample('sm/DocGearModelExample','supportingFile','DocWormAndGearStart.slx')
The model, based on the Worm and Gear Constraint block, is complete in every sense but one—all
rigid transforms are zero and the gear reference frames are therefore coincident in space.
This short tutorial shows how suitable transforms follow readily from the gear dimensions and
assembly constraints—and how, once specified in the Rigid Transform blocks, they enable the gear
model to assemble as though in mesh without error.
2-44
Assemble a Gear Model
Gear Geometry
The worm, A, has a pitch radius of 0.85 cm. The gear, B, has a pitch radius of 3.75 cm. The worm
and gear reference frames are placed with origins at the geometry centers and z-axes aligned with
the respective rotation axes. This alignment is consistent with the Revolute Joint block, which allows
rotation about the z-axis only.
Gear Assembly
The worm rotation axis is at a right angle to the gear rotation axis. The worm reference frame sits at
an offset of [0, -0.85, 0] cm, in Cartesian notation, relative to the world frame. The gear
reference frame sits at an offset of [0, +3.75, 0] cm and at an angle of 90 deg about the positive
y-axis relative to the world frame.
Complete the worm-and-gear model by specifying the rigid transforms described in the gear assembly
schematic. The conceptual animation that follows shows the incremental effects that the rigid
transforms would have were they to apply in sequence during model update.
2-45
2 Multibody Systems
If you have not yet done so, open the incomplete worm-and-gear model by entering:
openExample('sm/DocGearModelExample','supportingFile','DocWormAndGearStart.slx')
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the worm, A, relative to the world frame as described in the
Gear Assembly schematic.
• In the Rigid Transform A block dialog box, specify the Translation parameters shown in the table.
These parameters set the position of the gear, B, relative to the world frame as described in the
Gear Assembly schematic.
• In the Rigid Transform B block dialog box, specify the Rotation parameters shown in the table.
These parameters set the orientation of the gear, B, relative to the world frame as described in the
Gear Assembly schematic.
• Simulate the model. Mechanics Explorer opens with the dynamic gear visualization shown at the
beginning of this example. To see a complete worm-and-gear gear model, at the MATLAB
command prompt, enter:
openExample('sm/DocGearModelExample','supportingFile','DocWormAndGear.slx')
2-46
Model a Compound Gear Train
Planetary gear trains are common in industrial, automotive, and aerospace systems. A typical
application is the automatic transmission system of car. From a kinematic point of view, what sets this
mechanism apart is the kinematic constraint set between gear pairs. These constraints fix the angular
velocity ratios of the gear pairs, causing the gears in each pair to move in sync.
In Simscape™ Multibody™, you represent the kinematic constraint between meshed gears using
blocks from the Gears sublibrary. This tutorial shows you how to use these blocks to model a
planetary gear train. The gear train contains four bodies:
• Sun gear
• Planet gear
• Ring gear
• Planet carrier
Each body, including the planet carrier, can spin about its central axis. In addition, each planet gear
can revolve about the sun gear. Joint blocks provide the required degrees of freedom, while gear
constraint blocks ensure the gears move as if they were meshed.
Model the gear bodies and connect them with the proper degrees of freedom. In a later step, you add
gear constraints to this model.
2-47
2 Multibody Systems
2-48
Model a Compound Gear Train
• In the model workspace, define the block parameters using MATLAB® code:
% Common Parameters
Rho = 2700;
T = 3;
A = 0.8; % Gear Addendum
• Simulate the model. To induce motion, try adjusting the velocity state targets in the joint block
dialog boxes. Notice that the sun and planet gears move independently of each other. To constrain
gear motion, you must add a gear constraint block between the gear solid blocks.
2-49
2 Multibody Systems
To open a copy of the resulting model, at the MATLAB command line, enter:
openExample('sm/DocPlanetaryGearExample','supportingFile','DocPlanetaryGearA.slx')
Specify the kinematic constraints acting between the sun and planet gears. These constraints ensure
that the gears move in a meshed fashion.
2-50
Model a Compound Gear Train
• In the Common Gear Constraint block dialog box, specify these parameters.
• Simulate the model. To induce motion, try adjusting the velocity state targets in the joint block
dialog boxes. Notice that the sun and planet gears now move in sync.
To open a copy of the resulting model, at the MATLAB command line, enter:
openExample('sm/DocPlanetaryGearExample','supportingFile','DocPlanetaryGearB.slx')
Model the ring gear body, connect it with the proper degrees of freedom, and constrain its motion
with respect to the planet gear.
2-51
2 Multibody Systems
• Connect and name the blocks as shown. The new blocks are highlighted.
2-52
Model a Compound Gear Train
• In the Common Gear Constraint1 block dialog box, specify these parameters.
• In the model workspace, define the Ring Gear block parameters using MATLAB code:
Ring.Theta = linspace(-pi/Ring.N,2*pi-pi/Ring.N,100)';
Ring.RO = 1.1*Ring.R;
Ring.CSO = [Ring.RO*cos(Ring.Theta) Ring.RO*sin(Ring.Theta)];
Ring.CSI = simmechanics.demohelpers.gear_profile(2*Ring.R,Ring.N,A);
Ring.CSI = [Ring.CSI; Ring.CSI(1,:)];
Ring.CS = [Ring.CSO; flipud(Ring.CSI)];
• Simulate the model. To induce motion, try adjusting the velocity state targets in the joint block
dialog boxes. Notice that the sun, planet, and ring gears move in a meshed fashion.
To open a copy of the resulting model, at the MATLAB command line, enter:
2-53
2 Multibody Systems
openExample('sm/DocPlanetaryGearExample','supportingFile','DocPlanetaryGearC.slx')
Up to now, you have kept the sun and planet gears at a fixed distance using a Distance Constraint
block. In an actual planetary gear, a gear carrier enforces this constraint. Model the gear carrier and
connect it between the sun and planet gears.
Planar Joint
Rigid Transform
Distance Constraint
2-54
Model a Compound Gear Train
• Connect and name the blocks as shown. Pay close attention to the Rigid Transform block
orientation: the B frame ports should face the Solid block. The new blocks are highlighted.
2-55
2 Multibody Systems
• In the model workspace, define the Carrier block parameters using MATLAB code:
Theta = (90:1:270)'*pi/180;
Beta = (-90:1:90)'*pi/180;
• Simulate the model. To induce motion, try adjusting the velocity state targets in the joint block
dialog boxes. Notice that the gear carrier now performs the task of the Distance Constraint block.
2-56
Model a Compound Gear Train
To open a copy of the resulting model, at the MATLAB command line, enter:
openExample('sm/DocPlanetaryGearExample','supportingFile','DocPlanetaryGearD.slx')
Experiment with the model by adding more planet gears. Remember that you must change the
Carrier body to accommodate any additional planet gears.
To see a model with four planet gears, at the MATLAB command line, enter:
openExample('sm/DocPlanetaryGearExample','supportingFile','DocPlanetaryGearE.slx')
See Also
Extruded Solid | Rigid Transform
2-57
2 Multibody Systems
This example shows how to apply multiple point-on-curve constraints to a single body. The example is
based on a partial model of an aircraft flap that extends and retracts by riding on curved tracks. You
complete the multibody dynamics model by adding point-on-curve constraints between two points on
the flap and the flap track curves. The figure shows the visualization results of the flap model, once it
is complete.
To open the flap assembly model, at the MATLAB® command prompt, enter:
openExample("sm/DocConstrainPointToCurveExample","SupportingFile","DocPocFlapStart.slx")
Save the model with a different name in a convenient folder so that you do not inadvertently
overwrite the model.
The model is missing key connection lines and block parameters and does yet not simulate. Three
rigidly connected blocks, named Ribs, Skin, and Wicks, represent the flap body. A Planar Joint block
connects this body to the world frame with three degrees of freedom—one rotational and two
translational.
2-58
Constrain a Point to a Curve
The flap is at this point unconstrained. In this state, the degrees of freedom of the flap are those
provided by the Planar Joint block. The flap is free to rotate about the z-axis, translate along the x-
axis, and translate along the y-axis. The animated figure shows these motions. The frame axes are
color-coded, with red denoting x, green y, and blue z. The z-axis points out of the screen is not visible
in the figure.
The point-on-curve constraints couple the initially independent motions of the flap so that any one of
these motions suffices to completely determine the flap trajectory. For example, in the fully
constrained flap, a translation along the x-axis determines also the translation along the y-axis and
the rotation about the z-axis. The animated figure shows the constrained motion that you obtain at
the end of this example.
2-59
2 Multibody Systems
• In the Ribs File Solid block dialog box, expand the Frames node and click the button. The
frame creation interface opens. You use this interface to create a new frame and set its position
and orientation with respect to the solid geometry.
• In the visualization pane, zoom in on the top portion of the flap and select the top surface of the
rightmost cylindrical protrusion, as shown in the figure. The visualization pane highlights the
selected surface and reveals its normal vector.
• In the Frame Origin area of the frame creation interface, click the Based on Geometric
Feature radio button and then the Use Selected Feature button. The frame moves to the center
of the selected surface.
• Click the Save button to add the new frame to the solid. The block exposes a new port, F1,
corresponding to the new frame. You can rename the frame anything you want but, in this
example, the default name suffices.
• Repeat above steps to create a second frame with origin at the top surface of the leftmost
cylindrical protrusion, as shown in the figure. The block exposes a new port, F2, corresponding to
the new frame.
2-60
Constrain a Point to a Curve
• Connect the frame port of each Spline block to the World Frame block. This connection ensures
that the constraint curves specified in the Spline blocks are resolved in the World frame. The
curve definitions are currently the block defaults. You later change these defaults to obtain a
reasonable flap trajectory.
• Connect the frame ports of the Point on Curve Constraint blocks to the frame ports that you added
to the Ribs File Solid block (F1 and F2). The origins of these frames are the points that you
constrain in this example.
• Connect the geometry ports of the Spline blocks to the geometry ports of the Point on Curve
Constraint blocks as shown in the figure. The geometry connection lines identify the spline curve
definitions as the curves to constrain.
2-61
2 Multibody Systems
• Open Model Explorer and, in the Model Hierarchy pane, expand the DocPocFlapStart > Model
Workspace node. Model Explorer enables you to define workspace variables so that you can
reference them in block dialog box parameters.
• In the Model Workspace pane of Model Explorer, set the Data source parameter to MATLAB
Code. An editable field appears with the still-incomplete variable definitions:
theta = linspace(4*pi/12,pi/8,4)';
lowerTrack = [];
upperTrack = [];
• The variables lowerTrack and upperTrack are the constraint curves of the lower and upper flap
tracks. The variable theta is an angle range used in the definition of the lower track curve.
• Complete the lowerTrack and upperTrack definitions by specifying a few points on the curves
as shown in the following code snippet. You must click the Reinitialize from Source button to
apply the changes to the model. The new code portions are shown in blue.
theta = linspace(4*pi/12,pi/8,4)';
lowerTrack = [350 0; (640+100*cos(theta)) (130*sin(theta)-210)];
upperTrack = [50 50; 550 100];
• In the dialog box of each Spline block, specify the parameters listed in the table. The
Interpolation Points parameter is defined in terms of the MATLAB variables from the model
workspace. Ensure that this parameter is in units of mm. The Color parameter is defined as a
normalized RGB vector corresponding to a light shade of red.
2-62
Constrain a Point to a Curve
• Update the block diagram. In the Modeling tab, click Update Model. Mechanics Explorer opens
with a static visualization of the model in its initial configuration. The figure shows the spline
curves as they appear in Mechanics Explorer with the bodies hidden. You can hide a body by
selecting its node in the tree view pane and selecting Hide This.
Simulate the model. Mechanics Explorer shows a dynamic visualization of the flap assembly. The
motion of the flap is now constrained so that the origins of the frames you created always lie on the
curves you defined. Switch between the standard views of Mechanics Explorer or rotate, pan, and
zoom to better explore the flap and its motion.
To open a complete version of the flap assembly model, at the MATLAB command prompt, enter:
2-63
2 Multibody Systems
openExample("sm/DocConstrainPointToCurveExample","SupportingFile","DocPocFlap.slx")
See Also
Point on Curve Constraint
More About
• “Multibody Dynamics”
2-64
3
A multibody system includes groups of interconnected bodies. You can use Simscape Multibody to
specify dynamic behaviors of the system and measure quantities at the joints or between bodies that
are not connected by joints. For more information about the multibody dynamics simulation, see
“Multibody Dynamics”.
Identify the joints to actuate and the actuation type to use. Then, model the actuation inputs as time-
varying physical signals and connect them to the various joints. See “Specify Joint Actuation Torque”
on page 3-82 for an example.
Model damping and spring behavior at joints. Specify joint damping coefficients to model energy
dissipation and joint spring constants to model energy storage.
3-2
Modeling and Measuring System Dynamics
Identify the forces and torques acting at or between bodies not connected by joints. Model these
forces and torques explicitly using Forces and Torques blocks. See “Model Gravity in a Planetary
System” on page 3-8 for an example.
Identify the forces, torques, and motion variables to sense. You can sense these variables at joints
through Joint blocks. You can also sense motion variables using the Transform Sensor block. See
“Sense Motion Using a Transform Sensor Block” on page 3-77 for an example.
See Also
More About
• “Multibody Dynamics”
• “Model Gravity in a Planetary System” on page 3-8
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specify Joint Actuation Torque” on page 3-82
3-3
3 Internal Mechanics, Actuation and Sensing
Modeling Gravity
In this section...
“Gravity Models” on page 3-4
“Gravitational Force Magnitude” on page 3-5
“Force Position and Direction” on page 3-5
“Gravitational Torques” on page 3-6
Gravity Models
Gravity influences motion in many natural and engineered systems. These range in scale from the
very large, such as the planets orbiting the sun, to the relatively small, such as the shock absorbers
damping gravity-driven oscillations in a car. In Simscape Multibody, you can add gravity to systems
like these using three gravity models:
• Uniform gravity, as experienced by most earthbound systems. The force on each body due to
uniform gravity depends only on its mass. This force is the same everywhere in space for a given
body, though it can vary in time. You model uniform gravity using the Mechanism Configuration
block.
• Gravitational field, as experienced by the planets in the solar system. The force on each body due
to a gravitational field depends not only on its mass but also on its inverse square distance to the
field origin. You model a gravitational field using the Gravitational Field block.
• Inverse-square law force pair, similar in nature to a gravitational field, but acting exclusively
between one pair of bodies. You model an inverse-square law force pair using the Inverse Square
Law Force block. You must specify the body masses and force constants explicitly.
3-4
Modeling Gravity
Mm
Fg = − G
R2
with G being the gravitational constant. This is the force that you model when you represent gravity
through Gravitational Field or Inverse Square Law Force blocks. If the distance between source and
target masses is constant, the gravitational force reduces to a simpler form,
Fg = − mg
with g being the nominal gravitational acceleration. Near the surface of the Earth, at a distance equal
to Earth’s radius from the gravitational field origin, the nominal acceleration equals
GM
g= ≈ 9.80665 m/s2
R2
This is the gravitational force that you model when you represent gravity through the Mechanism
Configuration block. The figure shows how the magnitude of the gravitational force (Fg) varies with
distance (R) for a given body under uniform gravity, a gravitational field, and an inverse-square law
force pair.
Far from the field origin, the field origin-center of mass line remains approximately constant at small-
to-moderate displacements, and the force of gravity behaves as if its direction were fixed. This is the
approximation used in the Mechanism Configuration block. Gravity still acts at each body’s center of
mass, but its direction is now fixed along the gravity vector that you specify.
If you want to model the effects of gravity on a point other than a body’s center of mass, you can add
a frame at the desired location and apply a gravitational force directly at that frame. You model the
3-5
3 Internal Mechanics, Actuation and Sensing
force using the Inverse Square Law Force block. This force points along the imaginary line between
the two body frames that the Inverse Square Law Force block connects.
The table summarizes the application point and direction of gravity provided by the different blocks.
Gravitational Torques
A gravitational torque can arise in a large body immersed in a nonuniform gravitational field. The
lemon-shaped moon, with its near end perpetually facing Earth, is one example. Being placed at
different distances from Earth, the near and far elongated ends experience dissimilar gravitational
forces, resulting in a net gravitational torque if the line between the two ends ever falls out of
alignment with the center of the Earth.
You can model such torques in Simscape Multibody by modeling the different gravitational forces
acting on a body. You do this using the Inverse Square Law Force or Gravitational Field block. If you
use the Inverse Square Law Force block, you must create additional frames in each body whose
response to gravitational torque you want to model. You must then apply a gravitational force to each
frame explicitly. The figure shows an example.
Torque on the moon due to dissimilar gravitational forces at the elongated ends
3-6
Modeling Gravity
If you use the Gravitational Field block, you must split each body into discrete sections and connect
them through Weld Joint blocks. The Gravitational Field block automatically applies a force at the
center of mass of each section, approximating the compound effect of the different gravitational
forces on the body—which in this case is treated as a rigid multibody system. The figure shows an
example.
Torque on the moon due to dissimilar gravitational forces at the elongated ends
See Also
Gravitational Field | Mechanism Configuration | Spherical Solid | Cartesian Joint | Inverse Square
Law Force
More About
• “Model Gravity in a Planetary System” on page 3-8
3-7
3 Internal Mechanics, Actuation and Sensing
This tutorial shows how to simulate the gravity-driven orbits of the major solar system bodies. The
model treats the sun and planets as perfect spheres each with three translational degrees of freedom.
Planet spin is ignored. Gravitational fields generate the forces that keep the planets in orbit.
Spherical Solid blocks represent the solar system bodies and provide their geometries, inertias, and
colors. Cartesian Joint blocks define the bodies’ degrees of freedom relative to the world frame,
located at the solar system barycenter. Gravitational Field blocks add the long-range forces
responsible for bending the initial planet trajectories into closed elliptical orbits.
The Cartesian Joint blocks provide the initial states—positions and velocities—of the sun and planets
relative to the world frame. The initial states correspond to the solar system configuration on Jun
20th, 2016. They are sourced from ephemeris databases maintained by the Jet Propulsion Laboratory
(JPL).
You can query the databases through the JPL Horizons system using a web or telnet interface.
Aerospace Toolbox users can alternatively obtain the ephemeris data at the MATLAB® command
prompt using the planetEphemeris function after installing the Aerospace Ephemeris Data support
package.
Open the Simscape™ Multibody™ model template and remove all unnecessary blocks. Modify the
gravity settings so that you can add gravitational fields to the model. The result provides a starting
point for the solar system model.
• At the MATLAB command prompt, enter smnew. MATLAB opens a model template with commonly
used blocks and suitable solver settings for Simscape Multibody models.
• Cut all but the Mechanism Configuration, Solver Configuration, and World Frame blocks. These
three blocks provide the model with gravity settings, solver settings, and a global inertia reference
frame.
3-8
Model Gravity in a Planetary System
• In the Mechanism Configuration block dialog box, set Uniform Gravity to None. This setting
enables you to model gravity as an inverse-square law force using Gravitational Field blocks
instead.
Represent the solar system bodies using Spherical Solid blocks. Specify the geometry and inertia
parameters in terms of MATLAB variables and initialize these variables in the model workspace using
Model Explorer. The variables are data structures named after the solar system bodies using proper-
noun capitalization.
• Add to the model nine Spherical Solid blocks from the Body Elements library. The blocks represent
the sun and eight known planets.
• Connect and name the blocks as shown in the figure. The branched frame connection line between
the world frame and the planets makes them rigidly connected and coincident in space. You later
change this condition using Cartesian Joint blocks.
3-9
3 Internal Mechanics, Actuation and Sensing
• In the Spherical Solid block dialog boxes, set the Inertia > Based on parameter to Mass. The
inertia parameter setting enables you to specify the solid mass directly so that you can scale the
planet shapes without affecting the model dynamics.
• Specify the following Spherical Solid block parameters in terms of MATLAB data structure fields.
Enter the field names in the format Structure.Field, where Structure is the title-case name of the
solar system body and Field is the string shown in the table—e.g., Sun.R or Earth.RGB.
You later define the new structure fields in the model workspace using Model Explorer.
3-10
Model Gravity in a Planetary System
• In the MATLAB Code field, add the initialization code for the sun and planet solid properties. The
code is organized into sections named after the solar system bodies. You later add the initial
position and velocity data to these sections.
% Scaling
SunScaling = 0.5e2;
TerrestrialPlanetScaling = 1.2e3;
GasGiantScaling = 2.5e2;
% Sun
Sun.M = 1.99e30;
Sun.R = 6.96e8*SunScaling;
Sun.RGB = [1 0.5 0];
% Mercury
Mercury.M =3.30e23;
Mercury.R = 2.44e6*TerrestrialPlanetScaling;
Mercury.RGB = [0.5 0.5 0.5];
% Venus
Venus.M = 4.87e24;
Venus.R = 6.05e6*TerrestrialPlanetScaling;
Venus.RGB = [1 0.9 0];
% Earth
Earth.M = 5.97e24;
Earth.R = 6.05e6*TerrestrialPlanetScaling;
Earth.RGB = [0.3 0.6 0.8];
% Mars
Mars.M = 6.42e23;
Mars.R = 3.39e6*TerrestrialPlanetScaling;
Mars.RGB = [0.6 0.2 0.4];
% Jupiter
Jupiter.M = 1.90e27;
Jupiter.R = 6.99e7*GasGiantScaling;
Jupiter.RGB = [0.6 0 0.3];
% Saturn
Saturn.M = 5.68e26;
Saturn.R = 5.82e7*GasGiantScaling;
Saturn.RGB = [1 1 0];
% Uranus
Uranus.M = 8.68e25;
Uranus.R = 2.54e7*GasGiantScaling;
Uranus.RGB = [0.3 0.8 0.8];
% Neptune
Neptune.M = 1.02e26;
3-11
3 Internal Mechanics, Actuation and Sensing
Neptune.R = 2.46e7*GasGiantScaling;
Neptune.RGB = [0.1 0.7 0.8];
The Spherical Solid blocks now have all the numerical data they need to render the planet shapes and
colors. Try opening a Spherical Solid block dialog box and verify that a sphere now appears in the
solid visualization pane.
Add three translational degrees of freedom between the solar system barycenter and each solar
system body using Cartesian Joint blocks. You later use these blocks to specify the initial positions
and velocities of the solar system bodies.
• Add to the model nine Cartesian Joint blocks from the Joints library. The blocks provide the
translational degrees of freedom of the sun and eight known planets.
• Connect and name the blocks as shown in the figure. If you place a block on an existing
connection line, Simscape Multibody software automatically connects the block to that line. Flip
and rotate the joint blocks to ensure that Spherical Solid blocks connect only to follower (F) frame
ports.
3-12
Model Gravity in a Planetary System
The sun and planets are no longer rigidly connected. They can now translate relative to each other.
They are, however, still coincident in space. To place them at different initial positions and give them
initial velocities, you must specify the joint state targets.
Specify the sun and planet initial states in terms of MATLAB variables using the Cartesian Joint
blocks in your model. Then, initialize the new MATLAB variables in the model workspace using Model
Explorer. You define the MATLAB variables as new fields in the existing data structures.
• In the Cartesian Joint block dialog boxes, check the State Targets > Specify Position Target
and State Targets > Specify Velocity Target checkboxes for the X, Y, and Z prismatic joint
primitives. These settings enable you to specify the desired initial states of the sun and planets.
• Specify the Cartesian Joint state target values for the X, Y, and Z prismatic joint primitives in
terms of MATLAB structure fields. Enter the field names in the format Structure.Field, where
Structure is the title-case name of the solar system body and Field is the string shown in the table
—e.g., Sun.Px or Earth.Vz.
3-13
3 Internal Mechanics, Actuation and Sensing
You later define the new structure fields in the model workspace using Model Explorer.
% Scaling
SunScaling = 0.5e2;
TerrestrialPlanetScaling = 1.2e3;
GasGiantScaling = 2.5e2;
% Sun
Sun.M = 1.99e30;
Sun.R = 6.96e8*SunScaling;
Sun.RGB = [1 0.5 0];
Sun.Px = 5.5850e+08;
Sun.Py = 5.5850e+08;
Sun.Pz = 5.5850e+08;
Sun.Vx = -1.4663;
Sun.Vy = 11.1238;
Sun.Vz = 4.8370;
% Mercury
Mercury.M =3.30e23;
Mercury.R = 2.44e6*TerrestrialPlanetScaling;
Mercury.RGB = [0.5 0.5 0.5];
Mercury.Px = 5.1979e+10;
Mercury.Py = 7.6928e+09;
3-14
Model Gravity in a Planetary System
Mercury.Pz = -1.2845e+09;
Mercury.Vx = -1.5205e+04;
Mercury.Vy = 4.4189e+04;
Mercury.Vz = 2.5180e+04;
% Venus
Venus.M = 4.87e24;
Venus.R = 6.05e6*TerrestrialPlanetScaling;
Venus.RGB = [1 0.9 0];
Venus.Px = -1.5041e+10;
Venus.Py = 9.7080e+10;
Venus.Pz = 4.4635e+10;
Venus.Vx = -3.4770e+04;
Venus.Vy = -5.5933e+03;
Venus.Vz = -316.8994;
% Earth
Earth.M = 5.97e24;
Earth.R = 6.05e6*TerrestrialPlanetScaling;
Earth.RGB = [0.3 0.6 0.8];
Earth.Px = -1.1506e+09;
Earth.Py = -1.3910e+11;
Earth.Pz = -6.0330e+10;
Earth.Vx = 2.9288e+04;
Earth.Vy = -398.5759;
Earth.Vz = -172.5873;
% Mars
Mars.M = 6.42e23;
Mars.R = 3.39e6*TerrestrialPlanetScaling;
Mars.RGB = [0.6 0.2 0.4];
Mars.Px = -4.8883e+10;
Mars.Py = -1.9686e+11;
Mars.Pz = -8.8994e+10;
Mars.Vx = 2.4533e+04;
Mars.Vy = -2.7622e+03;
Mars.Vz = -1.9295e+03;
% Jupiter
Jupiter.M = 1.90e27;
Jupiter.R = 6.99e7*GasGiantScaling;
Jupiter.RGB = [0.6 0 0.3];
Jupiter.Px = -8.1142e+11;
Jupiter.Py = 4.5462e+10;
Jupiter.Pz = 3.9229e+10;
Jupiter.Vx = -1.0724e+03;
Jupiter.Vy = -1.1422e+04;
Jupiter.Vz = -4.8696e+03;
% Saturn
Saturn.M = 5.68e26;
Saturn.R = 5.82e7*GasGiantScaling;
Saturn.RGB = [1 1 0];
Saturn.Px = -4.2780e+11;
Saturn.Py = -1.3353e+12;
Saturn.Pz = -5.3311e+11;
Saturn.Vx = 8.7288e+03;
Saturn.Vy = -2.4369e+03;
3-15
3 Internal Mechanics, Actuation and Sensing
Saturn.Vz = -1.3824e+03;
% Uranus
Uranus.M = 8.68e25;
Uranus.R = 2.54e7*GasGiantScaling;
Uranus.RGB = [0.3 0.8 0.8];
Uranus.Px = 2.7878e+12;
Uranus.Py = 9.9509e+11;
Uranus.Pz = 3.9639e+08;
Uranus.Vx = -2.4913e+03;
Uranus.Vy = 5.5197e+03;
Uranus.Vz = 2.4527e+03;
% Neptune
Neptune.M = 1.02e26;
Neptune.R = 2.46e7*GasGiantScaling;
Neptune.RGB = [0.1 0.7 0.8];
Neptune.Px = 4.2097e+12;
Neptune.Py = -1.3834e+12;
Neptune.Pz = -6.7105e+11;
Neptune.Vx = 1.8271e+03;
Neptune.Vy = 4.7731e+03;
Neptune.Vz = 1.9082e+03;
The model now has the numerical data it needs to assemble the planets in the position coordinates
obtained from the JPL databases. However, a model simulation at this point would show the planets
moving in straight-line trajectories. To obtain elliptical orbits, you must complete the model by adding
the sun and planet gravitational fields.
3-16
Model Gravity in a Planetary System
Model the gravitational pull of each solar system body using the Gravitational Field block. This block
automatically computes the gravitational pull of a body on all other bodies using Newton’s law of
universal gravitation.
• In each Spherical Solid block dialog box, expand the Frames area and click the Create button.
• Set the Frame Name parameter to R2 and click the Save button. The new frame is an exact copy
of the reference frame but has a separate frame port. You can use these ports to connect the
gravitational field blocks while avoiding crossed connection lines.
• Add to the model nine Gravitational Field blocks from the Forces and Torques library. The blocks
provide the gravitational forces that each solar system body exerts on all other bodies.
• Connect and name the blocks as shown in the figure. Ensure that the blocks connect directly to
the Spherical Solid blocks. Such a connection ensures that the fields are centered on the solid
spheres and rigidly connected to them.
• In the Gravitational Field blocks, specify the Mass parameter as MATLAB structure field names.
Enter the field names in the format Structure.Field, where Structure is the title-case name of the
solar system body and Field is the string M—e.g., Sun.M or Earth.M. These fields have been
previously defined in the model workspace.
3-17
3 Internal Mechanics, Actuation and Sensing
Configure the Simulink® solver settings to capture ten earth revolutions in a single simulation. Then,
simulate the model and view the resulting solar system animation. Configure the animation settings
to play the ten-year animation in the period of a few seconds.
• Open the Configuration Parameters. In the Modeling tab, click Model Settings.
• Set the Stop time parameter to 10*365*24*60*60. This number, equal to ten years in seconds,
allows you to simulate a full ten earth revolutions from Jun 20th, 2016 through Jun 20th, 2026.
• Set the Max step size parameter to 24*60*60. This number, equal to one day in seconds, is small
enough to provide smooth animation results. Increase this number if you prefer faster simulation
results.
Update the block diagram. In the Modeling tab, click Update Model. Mechanics Explorer opens
with a static 3-D display of the model in its initial state. Check that the sun and planets appear in the
visualization pane and that their relative dimensions and positions are reasonable.
Run the simulation.. Mechanics Explorer plays an animation of the solar system. Note that at the
default base playback speed, the planets appear static. You must increase this speed in the Mechanics
Explorer animation settings.
3-18
Model Gravity in a Planetary System
To see the complete solar system model, at the MATLAB command prompt, enter:
openExample("sm/DocGravitationalFiledExample","SupportingFile","DocGravitationalFiled.slx").
See Also
smnew | Gravitational Field | Mechanism Configuration | Spherical Solid | Cartesian Joint
More About
• “Modeling Gravity” on page 3-4
3-19
3 Internal Mechanics, Actuation and Sensing
Actuation Modes
Joint blocks provide two actuation parameters. These parameters, Force/Torque and Motion, govern
how the joint behaves during simulation. Depending on the parameter settings you select, a joint
block can accept either actuation parameter as input or automatically compute its value during
simulation.
An additional setting (None) allows you to set actuation force/torque directly to zero. The joint
primitive is free to move during simulation, but it has no actuator input. Motion is due indirectly to
forces and torques acting elsewhere in the model, or directly to velocity state targets.
Like all joint block parameters, you select the actuation parameter settings for each joint primitive
separately. Different joint primitives in the same block need not share the same actuation settings.
Using a Pin Slot Joint block, for example, you can provide motion input and have actuation torque
automatically computed for the Z Revolute Primitive (Rz), while having motion automatically
computed with no actuation force for the X Prismatic Primitive (Px).
3-20
Specifying Joint Actuation Inputs
By combining different Force/Torque and Motion actuation settings, you can achieve different joint
actuation modes. Forward dynamics and inverse dynamics modes are two common examples. You
actuate a joint primitive in forward dynamics mode by providing actuation force/torque as input while
having motion automatically computed. Conversely, you actuate a joint primitive in inverse dynamics
mode by providing motion as input while having actuation force/torque automatically computed.
Other joint actuation modes, including fully computed and fully specified modes, are possible. The
table summarizes the different actuation modes that you can obtain by manipulating the actuation
parameter settings.
3-21
3 Internal Mechanics, Actuation and Sensing
More generally, thinking of joint actuation in terms of the specified or calculated quantities—i.e.,
force/torque and motion—provides a more practical modeling approach. You may not always know the
appropriate mode for a joint but, having planned the model beforehand, you should always know the
answers to two questions:
By selecting the joint actuation settings based on the answers to these questions, you can ensure that
each joint is properly set for your application. The figure shows the proper settings depending on
your answers.
Motion Input
The motion input of a joint primitive is a timeseries object specifying that primitive’s trajectory. For a
prismatic primitive, that trajectory is the position coordinate along the primitive axis, given as a
function of time. The coordinate provides the position of the follower frame origin with respect to the
base frame origin. The primitive axis is resolved in the base frame.
For a revolute primitive, the trajectory is the angle about the primitive axis, given as a function of
time. This angle provides the rotation of the follower frame with respect to the base frame about the
primitive axis. The axis is resolved in the base frame.
Spherical joint primitives provide no motion actuation options. You can specify actuation torque for
these primitives, but you cannot prescribe their trajectories. Those trajectories are always
automatically computed during simulation from the multibody dynamics model. For more information
about multibody dynamics simulations, see “Multibody Modeling”.
3-22
Specifying Joint Actuation Inputs
Unlike Actuation > Force/Torque, the Actuation > Motion parameter provides no zero input
option, corresponding to a fixed joint primitive during simulation. You can, however, prescribe zero
motion the same way you prescribe all other types of motion: using Simscape and Simulink blocks.
In Simscape Multibody, motion input signals are position-centric. You specify the joint primitive
position and, if filtered to the second-order, the Simulink-PS Converter block smooths the signal while
providing its two time-derivatives automatically. This behavior makes zero motion prescription
straightforward: just provide a constant signal to the motion actuation input port of the joint primitive
and simulate.
The figure shows an example of zero-motion prescription. A Simulink Constant block provides a
constant position value. A Simulink-PS Converter block converts this Simulink signal into a Simscape
signal compatible with the motion actuation input port of the Base-Crank Revolute Joint block.
Assuming that assembly and simulation are successful, this joint will maintain a fixed angle of 30
degrees, corresponding to the value set in the Simulink Constant block and the units set in the
Simulink-PS Converter block.
Input Handling
When prescribing a joint primitive trajectory, it is practical to specify a single input, the position, and
filter that input using a Simulink-PS Converter block. This filter, which must be second-order,
automatically provides the two time derivatives of the motion input. Because it also smooths the input
signal, the filter can help prevent simulation issues due to sudden changes or discontinuities, such as
those present when using a Simulink Step block.
Filtering smooths the input signal over a time scale of the order of the input filtering time constant.
The larger the time constant, the greater the signal smoothing, and the more distorted the signal
tends to become. The smaller the time constant, the closer the filtered signal is to the input signal,
but also the greater the model stiffness—and, hence, the slower the simulation.
3-23
3 Internal Mechanics, Actuation and Sensing
As a guideline, the input filtering time constant should be only as small as the smallest relevant time
scale in a model. By default, its value is 0.001 s. While appropriate for many models, this value is
often too small for Simscape Multibody models. For faster simulation, start with a value of 0.01 s.
Decrease this value for greater accuracy.
If you know the two time derivatives of the motion input signal, you can specify them directly. This
approach is most convenient for simple trajectories with simple derivatives. You must, however,
ensure that the two derivative signals are compatible with the position signal. If they are not, even
when simulation proceeds, results may be inaccurate.
Note You obtain the assembled state each time you update the block diagram, e.g., by pressing Ctrl
+D. You obtain the initial simulation state each time you run the simulation, e.g., by pressing Ctrl+T,
and pausing at time zero.
Due to the discrepancy between the two states, Model Report provides accurate initial state data only
for models lacking motion inputs. For models possessing motion inputs, that data is accurate only
when the initial position prescribed by the motion input signal exactly matches the initial position
prescribed in the joint state targets.
Similarly, Mechanics Explorer displays the initial joint states accurately only for models lacking
motion inputs. As it transitions from the assembled state to the initial simulation state, Mechanics
Explorer may show a sudden jump if a model contains motion inputs that are incompatible with the
joint state targets. You can eliminate the sudden change by making the initial position prescribed by
joint motion inputs equal to the initial position prescribed by the joint state targets.
3-24
Specifying Joint Actuation Inputs
1 Open the dialog box of the Simulink-PS Converter block and click Input Handling.
2 In Filtering and derivatives, select Filter input.
3 In Input filtering order, select Second-order filtering.
4 In Input filtering time constant (in seconds), enter the characteristic time over which filter
smooths the signal. A good starting value is 0.01 seconds.
If providing the input derivatives directly, you must first compute those derivatives. Then, using the
Simulink-PS Converter block, you can provide them to the target joint block. To specify the input
derivatives directly:
1 Open the Simulink-PS Converter block receiving the input signal and click the Input Handling
tab.
2 In Filtering and derivatives, select Provide input derivative(s).
3-25
3 Internal Mechanics, Actuation and Sensing
3 To specify both derivatives, in Input derivatives, select Provide first and second
derivatives.
The block displays two additional physical signal ports, one for each derivative.
See Also
Related Examples
• “Specify Joint Motion in Planar Manipulator Model” on page 3-112
• “Specify Joint Motion Profile” on page 3-108
• “Specifying Motion Input Derivatives” on page 3-25
3-26
Joint Actuation Limitations
In this section...
“Closed Loop Restriction” on page 3-27
“Motion Actuation Not Available in Spherical Primitives” on page 3-27
“Redundant Actuation Mode Not Supported” on page 3-27
“Model Report and Mechanics Explorer Restrictions” on page 3-27
“Motion-Controlled DOF Restriction” on page 3-28
In models not meeting this condition, you can replace a rigid connection line between two Solid
blocks with a Weld Joint block. Since the Weld Joint block represents a rigid connection, this approach
leaves the model dynamics unchanged. The advantage of this approach lies in its ability to satisfy the
Simscape Multibody closed-loop requirement without altering model dynamics.
3-27
3 Internal Mechanics, Actuation and Sensing
See Also
Related Examples
• “Specify Joint Motion in Planar Manipulator Model” on page 3-112
• “Specify Joint Motion Profile” on page 3-108
• “Specifying Motion Input Derivatives” on page 3-25
More About
• “Specifying Joint Actuation Inputs” on page 3-20
3-28
Actuating and Sensing with Physical Signals
Some Simscape Multibody blocks provide physical signal ports for actuation input or sensing output.
These ports accept or output only Simscape physical signals. If you wish to connect these ports to
Simulink blocks, you must use the Simscape converter blocks. The table summarizes the converter
blocks that Simscape provides. You can find both blocks in the Simscape Utilities library.
Block Summary
PS-Simulink Converter Convert Simscape physical signal into Simulink
signal
Simulink-PS Converter Convert Simulink signal into Simscape physical
signal
In the figure, the connection line that connects to the input port of the Simulink-PS Converter block
represents the original Simulink signal. The connection line that connects to the output port of the
same block represents the converted physical signal. This is the signal that you must connect to the
actuation ports in Simscape Multibody blocks.
3-29
3 Internal Mechanics, Actuation and Sensing
1 Connect the Simscape Multibody sensing port to the input port of a PS-Simulink Converter block.
2 Connect the output port of the PS-Simulink Converter block to the Simulink block of your choice.
The figure shows how you can connect a Simscape Multibody sensing signal to a Simulink Scope
block.
See Also
Related Examples
• “Specify Joint Motion in Planar Manipulator Model” on page 3-112
• “Specify Joint Motion Profile” on page 3-108
• “Specifying Motion Input Derivatives” on page 3-25
3-30
Actuating and Sensing with Physical Signals
More About
• “Specifying Joint Actuation Inputs” on page 3-20
3-31
3 Internal Mechanics, Actuation and Sensing
Sensing
In this section...
“Sensing Overview” on page 3-32
“Variables You Can Sense” on page 3-32
“Blocks with Sensing Capability” on page 3-33
“Sensing Output Format” on page 3-33
Sensing Overview
Sensing enables you to perform analytical tasks on a model. For example, you can perform inverse
kinematic analyses of a robotic manipulator model. By prescribing the end-effector trajectory and
sensing the joint actuation forces and torques, you can obtain the time-varying profile of each joint
actuation input.
The variables you prescribe, the model inputs, and those you sense, the model outputs, determine
which types of analysis you can perform. By changing the model inputs and outputs, you can perform
numerous other analysis types. For example, to perform forward kinematic analysis on the robotic
manipulator model, you can prescribe the manipulator joint trajectories and sense the resulting end-
effector trajectory.
• Motion variables — Linear and angular position, velocity, and acceleration. Linear variables are
available in different coordinate systems, including Cartesian, spherical, and cylindrical. Angular
variables are available in different formats, including quaternion, axis-angle, and transform
matrix.
• Force and torque variables — Actuation, constraint, and total forces and torques acting at a joint,
as well as certain forces and torques acting outside of a joint.
3-32
Sensing
• Joint blocks — Motion sensing between the base and follower port frames of a joint block.
Variables that you can sense are organized by joint primitive (prismatic, revolute, or spherical).
• Transform Sensor block — Motion sensing between any two frames in a model. This block
provides the most comprehensive motion sensing capability in Simscape Multibody.
• Joint blocks — Actuation, constraint, and total force and torque sensing between the base and
follower port frames. Actuation force and torque sensing is arranged by joint primitive.
• Constraint blocks — Constraint force and torque between the base and follower port frames.
• Certain Forces and Torques blocks — Total force the block exerts between the base and follower
port frames. Only certain Forces and Torques blocks provide this type of sensing, such as the
Spring and Damper Force and Inverse Square Law Force.
See Also
Inverse Square Law Force | Spring and Damper Force | Scope | Transform Sensor
More About
• “Actuating and Sensing with Physical Signals” on page 3-29
3-33
3 Internal Mechanics, Actuation and Sensing
Blocks with force and torque sensing appear in two Simscape Multibody libraries:
• Forces and Torques — Measure the magnitude of certain forces not explicitly provided by input.
Blocks with force sensing include Inverse Square Law Force and Spring and Damper Force. Each
block can measure only the magnitude of its own force.
• Joints — Measure various forces and torques acting directly at a joint. All joint blocks provide
force and torque sensing. However, the specific force and torque types that you can measure vary
from joint to joint. Force and torque sensing is available strictly between the bodies the joint
connects.
• Joint primitive forces and torques. Each such force or torque is individually computed for a given
joint primitive. Joint actuator forces and torques belong to this category.
• Composite forces and torques. Each such force or torque is computed in aggregate for an entire
joint. Constraint and total forces and torques belong to this category.
3-34
Force and Torque Sensing
The figure shows a basic example of these forces acting on a crank-slider piston.
In the figure:
• FA is the actuator force, which drives the piston toward the crank link.
• FI is the internal spring and damper force, which resists motion of the piston with respect to the
chamber.
• FC is the constraint force, which opposes the effect of gravity on the piston, preventing it from
falling.
The total force equals the net sum of FA, FI, and FC.
3-35
3 Internal Mechanics, Actuation and Sensing
• Follower on base — Measure the force or torque that the follower port frame exerts on the base
port frame.
• Base on follower — Measure the force or torque that the base port frame exerts on the follower
port frame.
The figure shows the effect of reversing the measurement direction. Reversing this direction changes
the measurement sign.
See Also
Revolute Joint | Weld Joint
More About
• “Measure Forces and Torques Acting at Joints” on page 3-97
• “Measure Joint Constraint Forces” on page 3-103
• “Sensing Composite Forces and Torques in Joints - Potter's Wheel” on page 8-38
3-36
Modeling Contact Force Between Two Solids
In this section...
“Spatial Contact Force Block Forces” on page 3-38
“Sensing” on page 3-38
“Connect to Solid Blocks” on page 3-39
“Considerations for Contact Modeling” on page 3-39
When modeling solid blocks in contact with each other, contact forces play an important role in how
the solid blocks behave. Both the normal force, fn, and the frictional force, ff, can cause the dynamic
behaviors of a multibody model to change. For more information about multibody dynamics
simulation, see “Multibody Dynamics”. Contact forces come into play in many different modeling
situations, such as:
• Package conveyors
• Robotic movement
• Race car dynamics
The Spatial Contact Force block models forces between base and follower frame solid bodies. When
the two solid blocks are connected, the Spatial Contact Force block applies equal and opposite forces
along a common contact plane. These forces conform to Newton's Third Law. The normal force is
applied based on the penetration depth and the penetration velocity. If applied, the frictional force is
based on the normal force and the relative velocities at the point of contact.
Simscape Multibody uses a penalty method for modeling contact between bodies, which allows the
bodies to penetrate a small amount. Contact forces in the normal direction are computed using a
spring-damper force law: the deeper the penetration and the greater the relative velocity in the
penetration direction, the greater the normal contact forces.
3-37
3 Internal Mechanics, Actuation and Sensing
For more information about these properties, see Spatial Contact Force.
Normal Force
Parameters in the Normal Force section are used to determine the normal force, fn, that the two solid
bodies exert on each other. You can specify the Stiffness, Damping, and Transition Region Width.
Frictional Force
Parameters in the Frictional Force section are used to determine the frictional force, ff, that the two
solid bodies exert on each other. If you set Method to Smooth Stick-Slip, then you can specify
the Coefficient of Static Friction, Coefficient of Dynamic Friction, and Critical Velocity. These
options are not available when the Method is set to None.
Sensing
Besides modeling contact between two solid blocks, you can also use the Spatial Contact Force block
to sense:
To enable these options, open the Spatial Contact Force block properties. Under Sensing, select the
properties that you want the block to sense. For each property, a port is exposed on the block.
Connect these ports to a viewer of your choice.
3-38
Modeling Contact Force Between Two Solids
Once this option is enabled a new geometry port, G, appears on your solid block.
Connect the geometry port to the base or follower port on the Spatial Contact Force block. Follow the
same steps for your other solid block and connect it to the remaining port. To learn more about base
and follower frames, see “Selecting a Measurement Frame” on page 3-67.
3-39
3 Internal Mechanics, Actuation and Sensing
maintainability. Simscape Multibody provides basic contact modeling constructs, but there are many
ways to use them.
Solver Parameters
The computed normal contact forces are continuous functions of penetration depth and penetration
velocity. Simscape Multibody computes these normal forces by reducing the spring and damper
forces when the depth is less than the Transition Region Width. Increasing the Transition Region
Width reduces the sharpness of the contact force, making the system easier for the solver to
advance, but allowing greater amounts of penetration. Decreasing the Transition Region Width
gives the contact forces a sharper profile, closer to idealized rigid-body contact. However, decreasing
the Transition Region Width may also degrade solver performance.
Setting the maximum step size to 1e-3 seconds or lower improves accuracy in many models. Reducing
the relative solver tolerance can produce a similar effect. However, reducing the step size also
reduces the simulation speed.
Explicit solvers, such as ode45, are usually better for systems with many rapid collisions or contact
changes. Implicit solvers may struggle under such circumstances. If the contact changes are
infrequent and more stable, implicit solvers may offer a speed advantage due to their ability to handle
the stiffness introduced by the contact forces.
The separation distance between two solid blocks is positive when the two geometries are not in
contact, zero when they are touching, and negative when there is nontrivial penetration between the
geometries. When the separation distance is negative, its magnitude is also known as the penetration
depth. Penetration depth is a continuous function of the positions and orientations of the geometries.
Simscape Multibody uses geometry analysis algorithms that are tuned for small contact-modeling
applications. Some of the algorithms assume that the penetration depth is small compared to the size
of the geometries. If this is not the case, the computed (negative) separation distances may only be
approximate, or may exhibit discontinuities, and the resulting contact forces may be erratic. For best
results, limit penetration depth in your model.
See Also
Spatial Contact Force | Brick Solid | Cylindrical Solid | Spherical Solid
More About
• “Solid Cylinder Rolling Down an Incline” on page 3-50
• “Train Humanoid Walker” on page 8-93
• “Zero-Crossing Detection”
• “Use Contact Proxies to Simulate Contact” on page 3-41
3-40
Use Contact Proxies to Simulate Contact
Contact proxies are simple shapes that are used to represent the contact parts of actual bodies. For
example, in the “Train Humanoid Walker” on page 8-93 example, red spheres are used to represent
the bottoms of the robotic feet.
By using contact proxies, you can increase the speed and robustness of a contact simulation. For
example, using contact proxies can speed up models that involve complex geometries and prevent the
discontinuous jumping of contact force locations in static contact simulations.
To choose the appropriate proxies for a contact problem, you need to indicate what parts of the actual
bodies will interact and then select the simplest proxies for these parts. Note that the proxies should
be enough to cover all the contact regions.
Simscape Multibody supports a variety of geometries and bodies for contact modeling. Based on
complexity, these geometries and bodies can be categorized into three groups.
• The geometries defined by the Point, Infinite Plane, and Spherical Solid blocks. These geometries
are the best candidates to act as proxies due to their simple shapes and high modeling efficiency.
3-41
3 Internal Mechanics, Actuation and Sensing
• The bodies defined by Brick Solid, Cylindrical Solid, and Ellipsoidal Solid blocks. They are more
computationally expensive than the geometries of the first group. If you can't use the geometries
in the first group, try to use bodies in this group as proxies.
• The geometries created by extrusions, revolutions, and CAD imports. Typically, these geometries
are not suitable to be used as proxies due to their complex shapes, high computational costs, and
simplified representations. Note that Simscape Multibody represents some of these geometries
with convex hulls instead of actual bodies when modeling contacts.
Simscape Multibody models contact between bodies by using the Spatial Contact Force block. Each
pair of potentially contacting parts needs one Spatial Contact Force block. Consequently, a complex
model that includes many proxies could lead to a plethora of Spatial Contact Force blocks and
geometry lines. Use the following techniques to keep your block diagram organized. See the first
example for how to use these techniques.
• Place each actual body and its proxies in one subsystem. The subsystem should also include all the
relevant Rigid Transform blocks needed to properly place the proxies relative to the actual body.
• Copy and paste subsystems or use referenced subsystems to create identical subsystems.
• Use the Simscape Bus block to bundle the geometry lines of a complex model.
Usually, the actual body and its proxies occupy some common regions in the 3-D space. You should
render only the actual body and hide the proxies in the final version of the simulation. However,
during a modeling or debugging step, it is helpful to view the proxies to verify whether all the
contacts are modeled as expected. Consider defining two variables to adjust the transparency of the
actual body and proxies. Use the mass of the actual body for simulation and set the mass or density of
the contact proxies to zero to avoid any effects on dynamics.
Examples
Using Proxies in Contact Models that Include Complex Shapes
Modeling contact between bodies with complex shapes is computationally expensive and time
consuming. To speed up the model, you can decompose the complex shapes into simpler parts and
use proxies to represent the parts involved in contact, then model the contacts between these
proxies.
In the “Ratchet Lifter” on page 8-103 example, the traveler climbs up along the toothed rack as the
traveler handle is pumped up and down. Only the horizontal and slanted surfaces of the rack teeth
and climber cylinders are involved in the contact. Also, the traveler only exhibits planar motion. In
other words, only the center parts of the climber cylinders are involved in the contact interactions.
Therefore, the example uses the proxies to represent only these parts and models contacts among the
proxies.
3-42
Use Contact Proxies to Simulate Contact
This example uses cylinders to represent the horizontal and slanted surfaces of the rack teeth and
spheres to represent the center parts of the climber cylinders. The advantage of using a sphere
instead of the entire climber cylinder is that spheres are simpler than cylinders and provide more
efficient contact modeling.
3-43
3 Internal Mechanics, Actuation and Sensing
The toothed rack is symmetrical and has 15 teeth on each side. Consequently, this example uses 60
cylinders to represent the teeth. The model includes a subsystem called Toothed Rack that includes
the actual body of the rack, all the proxies of the teeth, and relevant Rigid Transform blocks. The
following figure shows the Toothed Rack subsystem.
3-44
Use Contact Proxies to Simulate Contact
Because the toothed rack is symmetrical, only the proxies on one side of the rack were created
manually and grouped into the Left Slant Cylinders and Left Horiz Cylinders subsystems. Then these
subsystems were copied, pasted, and then rotated 180 degrees around the y-axis to represent the
right-side teeth.
The following image shows the Left Horiz Cylinders subsystem. The model uses 15 identical cylinders
to represent the horizontal surfaces of the left-side teeth. To minimize the number of blocks that were
manually created, one parameterized referenced subsystem was created to model one of the
cylinders. Then the parameterized referenced subsystem was copied 14 times. The parameterized
referenced subsystems use the cylinders’ indices to specify the locations of the cylinders. Finally, the
geometry lines of the cylinders are bundled using a Simscape Bus block. The same method is used to
model the subsystem of the teeth’s slant surfaces.
3-45
3 Internal Mechanics, Actuation and Sensing
The Simscape Bus block helps avoid a complex web of lines throughout the model. The following
image shows that two Simscape Bus lines connect the 60 proxies of the rack teeth with the climbers'
proxies via the Contacts Left and Contacts Right subsystems.
3-46
Use Contact Proxies to Simulate Contact
The Contacts Left and Contacts Right subsystems include all the Spatial Contact Force blocks for this
simulation. The following image shows the diagram of the contact between the horizontal surface of
the left-side teeth and the cylinder of the left climber.
3-47
3 Internal Mechanics, Actuation and Sensing
Simscape Multibody employs a point-based penalty method for modeling contact between bodies.
This method means that the Spatial Contact Force block applies necessary contact forces to its
connected bodies at the points with the maximum penetration between the two bodies. Each Spatial
Contact Force block only applies a single contact force for each body at each time step.
This point-based method has challenges when modeling static contact between the flat surfaces of
bodies. For example, consider modeling the contact between two bricks. For the purposes of
simplicity, the following image shows the 2-D version of the problem. Suppose Brick A is dropped onto
Brick B, which has a fixed position. The left image shows the configuration of the bricks when the
contact is first detected. At this point, the Spatial Contact Force block applies a contact force to the
lower-left corner of Brick A because it has the maximum penetration. Over time, the force decelerates
the downward motion of Brick A and rotates it in a clockwise direction. Then, the configuration
appears like the right image, and the force is applied to the lower right corner of Brick A. As Brick A
settles into static contact with Brick B, the location of the contact force rapidly and discontinuously
jumps among the corners of Brick A. This behavior is challenging for the solver and can significantly
decrease the simulation speed.
3-48
Use Contact Proxies to Simulate Contact
Using contact proxies is one effective way to avoid the above modeling challenges. Eight small
spheres can be rigidly attached to the corners of Brick A. With these proxies, the contact is modeled
as eight brick-sphere pairs instead of a single brick-brick pair. As the contact stabilizes, the normal
force at each bottom corner will be one-fourth of the weight of Brick A.
See Also
Spatial Contact Force | Brick Solid | Cylindrical Solid | Spherical Solid | Point | Infinite Plane |
Ellipsoidal Solid | Simscape Bus | Extruded Solid | File Solid
More About
• “Modeling Contact Force Between Two Solids” on page 3-37
• “Solid Cylinder Rolling Down an Incline” on page 3-50
• “Train Humanoid Walker” on page 8-93
• “Zero-Crossing Detection”
3-49
3 Internal Mechanics, Actuation and Sensing
smnew
Delete Scope, PS-Simulink Converter, and Simulink-PS Converter blocks. Rename and connect the
blocks as showing in following figure.
Property Value
Rotation > Method Aligned Axes
Rotation > Pair 1 > Follower +Z
Rotation > Pair 1 > Base -Y
Rotation > Pair 2 > Follower +X
Rotation > Pair 2 > Base +X
3-50
Solid Cylinder Rolling Down an Incline
Property Value
Translation > Method None
Property Value
Rotation > Method Standard Axis
Rotation > Axis +Y
Rotation > Angle 5 deg
Translation > Method Cartesian
Translation > Offset [30 0 -15] cm
Property Value
Geometry > Radius 5 cm
Geometry > Length 4 cm
Geometry > Export > Entire Geometry selected
Inertia > Type Calculate from Geometry
Inertia > Based on Density
Inertia > Density 650 kg/m^3
Graphic > Type From Geometry
Graphic > Visual Properties Simple
Graphic > Visual Properties > Color [0.6 0.0 0.0]
Graphic > Visual Properties > Opacity 1.0
Frames > Show Port R selected
Property Value
Geometry > Dimensions [90 20 5] cm
Geometry > Export > Entire Geometry selected
Inertia > Type Calculate from Geometry
Inertia > Based on Density
Inertia > Density 1000 kg/m^3
Graphic > Type From Geometry
Graphic > Visual Properties Simple
Graphic > Visual Properties > Color [0.4196 0.5569 0.1373]
Graphic > Visual Properties > Opacity 1.0
Frames > Show Port R selected
3-51
3 Internal Mechanics, Actuation and Sensing
Property Value
Normal Force > Stiffness 1e6 N/m
Normal Force > Damping 1e3 N/(m/s)
Normal Force > Normal Force: Transition 1e-4 m
Region Width
Frictional Force > Method Smooth Stick-Slip
Frictional Force > Coefficient of Static 0.3
Friction
Frictional Force > Coefficient of Dynamic 0.3
Friction
Frictional Force > Critical Velocity 0.01 m/s
Sensing > Separation Distance unselected
Sensing > Normal Force unselected
Sensing > Frictional Force Magnitude unselected
On the Modeling tab, select Model Settings > Model Settings to open the Configuration
Parameters. In the Solver pane, under Solver details, update the following:
At this point, both the Cylindrical Wheel block and Inclined Plane block should have a geometry port.
As shown in the figure, connect the geometry ports of the Inclined Plane and Cylindrical Wheel blocks
to the base and follower ports of the Spatial Contact Force block, respectively.
On the Simulation tab, click Run. In the MATLAB window, the Mechanics Explorer pane opens, and
you see the cylindrical wheel roll down the surface. For a more complicated model, see “Using the
Spatial Contact Force Block - Bumper Car” on page 8-8.
3-52
Solid Cylinder Rolling Down an Incline
See Also
More About
• Spatial Contact Force
• Brick Solid
• Cylindrical Solid
• Spherical Solid
3-53
3 Internal Mechanics, Actuation and Sensing
Motion Sensing
In this section...
“Sensing Spatial Relationships Between Joint Frames” on page 3-54
“Sensing Spatial Relationships Between Arbitrary Frames” on page 3-55
In Simscape Multibody, you can sense the spatial relationship between two frames using two types of
blocks:
• Transform Sensor — Sense the spatial relationship between any two frames in a model.
Parameters that you can sense with this block include position, velocity, and acceleration of the
linear and angular types. This block provides the most extensive motion sensing capability in the
Simscape Multibody libraries.
• Joint blocks — Sense the spatial relationship between the base and follower frames of a Joint
block. Parameters that you can sense with a Joint block include the position and its first two time
derivatives (velocity and acceleration) for each joint primitive.
These blocks output a physical signal for each measurement that you specify. You can use the sensing
output of these blocks for analysis or as input to a control system in a model.
The sensing capability of a joint block is limited to the base and follower frames of that joint block.
Every measurement provides the value of a parameter for the joint follower frame with respect to the
joint base frame. If sensing the spatial relationship with a spherical joint primitive, you can also select
the frame to resolve the measurement in. To sense the spatial relationship between any other two
frames, use the Transform Sensor block instead.
If the joint primitive is of the revolute or spherical type, the parameters correspond to the rotation
angle, angular velocity, and angular acceleration, respectively. If the joint primitive is of the prismatic
type, the parameters correspond to the offset distance, linear velocity, and linear acceleration,
respectively.
Regardless of joint primitive type, each parameter that you select applies only to the joint primitive it
belongs to. For example, selecting Position in the Z Revolute Primitive (Rz) > Sensing menu
exposes a physical signal port that outputs the rotation angle of the follower frame with respect to
the base frame about the base frame Z axis.
The table lists the port label for each parameter that you can sense using a joint block. The first
column of the table identifies the parameters that you can select. The remaining three columns
identify the port labels for the three joint primitive menus that the dialog box can contain: Spherical,
Revolute, and Prismatic.
3-54
Motion Sensing
Note For parameter descriptions, see the reference pages for Spherical Joint, Revolute Joint, and
Prismatic Joint blocks.
A joint block can contain multiple revolute and prismatic joint primitives. For blocks with multiple
primitives of the same type, the port labels include an extra letter identifying the joint primitive axis.
For example, the Position port label for the Z prismatic primitive of a Cartesian Joint block is pz.
1 Open the dialog box for the joint block to sense the spatial relationship across.
2 In the Sensing menu of the block dialog box, select the parameters to sense.
The block exposes one physical signal port for each parameter that you select. The label of each port
identifies the parameter that port outputs.
Every measurement provides the value of a parameter for the follower frame with respect to the base
frame, resolved in the measurement frame that you choose. You can connect the base and follower
frame ports of the Transform Sensor block to any two frames in a model. To measure a parameter for
a different frame, connect the follower frame port to the frame line or port that identifies that frame.
Likewise, to measure a parameter for the same frame but with respect to a different frame, connect
the base frame port to the frame line or port that identifies that frame. Finally, to resolve a
measurement in a different frame, select a different measurement frame in the block dialog box. For
more information about measurement frames, see “Selecting a Measurement Frame” on page 3-67.
For more information about frame lines and ports, see “Working with Frames” on page 1-24.
Selecting a parameter from the block dialog box exposes the corresponding physical signal port in
the block. Use this port to output the measurement for that parameter. To identify the port associated
with each parameter, each port uses a unique label.
The table lists the port labels for each angular parameter that you can sense. The first column of the
table identifies the parameters that you can select. The remaining three columns identify the port
labels for the three angular parameter menus in the dialog box: Rotation, Angular Velocity, and
Angular Acceleration. Certain parameters belong to one menu but not to others. N/A identifies the
3-55
3 Internal Mechanics, Actuation and Sensing
parameters that do not belong to a given menu—e.g. Angle, which is absent from the Angular
Velocity.
Note For parameter descriptions, see the Transform Sensor reference page.
The table lists the port labels for each linear parameter that you can sense. As in the previous table,
the first column identifies the parameters that you can select. The remaining three columns identify
the port labels for the three linear parameter menus in the dialog box: Translation, Velocity, and
Acceleration.
The block exposes one physical signal port for each parameter that you select. The label of each port
identifies the parameter that port outputs.
See Also
Related Examples
• “Sense Motion Using a Transform Sensor Block” on page 3-77
3-56
Motion Sensing
More About
• “Rotational Measurements” on page 3-58
• “Translational Measurements” on page 3-63
• “Selecting a Measurement Frame” on page 3-67
3-57
3 Internal Mechanics, Actuation and Sensing
Rotational Measurements
In this section...
“Rotation Sensing Overview” on page 3-58
“Measuring Rotation” on page 3-58
“Axis-Angle Measurements” on page 3-58
“Quaternion Measurements” on page 3-59
“Transform Measurements” on page 3-59
“Rotation Sequence Measurements” on page 3-60
Measuring Rotation
Rotation is a relative quantity. The rotation of one frame is meaningful only with respect to another
frame. As such, blocks with rotation sensing capability require two frames to make a measurement:
measured and reference frames. In these blocks, the follower frame port identifies the measured
frame; the base frame port identifies the reference frame of the measurement.
Simscape Multibody defines the rotation formats according to standard conventions. In some cases,
more than one convention exists. This is the case, for example, of the quaternion. To properly
interpret rotation measurements, review the definitions of the rotation formats.
Axis-Angle Measurements
Axis-angle is one of the simpler rotation measurement formats. This format uses two parameters to
completely describe a rotation: axis vector and angle. The usefulness of the axis-angle format follows
directly from Euler’s rotation theorem. According to the theorem, any 3–D rotation or rotation
sequence can be described as a pure rotation about a single fixed axis.
To measure frame rotation in axis-angle format, use the Transform Sensor block. The block property
inspector contains separate Axis and Angle parameters that you can select to expose the
corresponding physical signal (PS) ports (labeled axs and q, respectively). Because the axis-angle
parameters are listed separately, you can choose to measure the axis, the angle, or both.
3-58
Rotational Measurements
The axis output is a 3D unit vector in the form [ax, ay, az]. This unit vector encodes the rotation
direction according to the right-hand rule. For example, a frame spinning in a counterclockwise
direction about the +X axis has rotation axis [1 0 0]. A frame spinning in a clockwise direction about
the same axis has rotation axis [-1 0 0].
The angle output is a scalar number in the range 0–π. This number encodes the extent of rotation
about the measured axis. By default, the angle is measured in radians. You can change the angle units
in the PS-Simulink Converter block used to interface with Simulink blocks.
Quaternion Measurements
The quaternion is a rotation representation based on hypercomplex numbers. The quaternion is made
up of a scalar part, S, and a vector, V, part. The scalar part encodes the angle of rotation, and the
vector part encodes the rotational axis.
• A Transform Sensor block when measuring rotation between two general frames. The Rotation
menu of the property inspector contains a Quaternion parameter that you can select to expose
the corresponding physical signal port (labeled Q).
• A joint block that has a spherical primitive when measuring the 3-D rotation between the two joint
frames. The Sensing menu of the property inspector contains a Position parameter that you can
select to expose the corresponding physical signal port (which is also labeled Q). For more
information, see the Spherical Joint block reference page.
θ
S = cos
2
and
θ
V = [Ux Uy Uz]sin
2
θ is the angle of rotation and [Ux, Uy, Uz] is the unit vector of the rotational axis. Note that for any
given rotation, there are two quaternions. They are negatives of each other, but represent the same
rotation. For example, the quaternions [1 0 0 0] and [-1 0 0 0] both represent the identity rotation.
Transform Measurements
The rotation transform is a 3×3 matrix that encodes frame rotation. In terms of base frame axes [x, y,
z]B, the follower frame axes [x, y, z]F are:
3-59
3 Internal Mechanics, Actuation and Sensing
Each matrix column contains the coordinates of a follower frame axis expressed in the base frame.
For example, the first column contains the coordinates of the follower frame x-axis, as expressed in
the base frame. Similarly, the second and third columns contain the coordinates of the y and z-axes,
respectively. Operating on a vector with the rotation matrix transforms the vector coordinates from
the follower frame to the base frame.
You can sense frame rotation in terms of a rotation matrix using the Transform Sensor block. The
property inspector for this block contains a Transform option that when selected exposes a physical
signal port labeled R. Use this port to output the rotation matrix signal, for example, for processing
and analysis in a Simulink subsystem—after converting the output physical signal to a Simulink signal
through the PS-Simulink Converter block.
The elementary rotations are intrinsic if they are about an intermediate frame, which changes its
orientation after each elementary rotation. When the elementary rotations are about a fixed frame
the rotations are extrinsic. The measurements have 12 different rotation sequences including X-Y-X, X-
Y-Z, X-Z-X, X-Z-Y, Y-X-Y, Y-X-Z, Y-Z-X, Y-Z-Y, Z-X-Y, Z-X-Z, Z-Y-X, and Z-Y-Z. Note that the outputs from the
port seq of the Transform Sensor block are angles of intrinsic rotations. The image shows an example
that represents a 3-D rotation with three intrinsic rotations based on the Z-Y-Z sequence.
3-60
Rotational Measurements
Extrinsic rotations are equivalent to intrinsic rotations with the same angles but with an inverted
sequence order. For example, the extrinsic rotations Z-Y-X by angles φ, θ, and Ψ are equivalent to the
intrinsic rotations X-Y-Z by the angles Ψ, θ, and φ.
When the rotation does not has a locking issue, such as gimbal lock, a rotation sequence
measurement has two sets of solutions, but the Transform Sensor block or the sequenceAngles
method only outputs one set of them. All three angles are in the range [-π, π]. If a rotation sequence
has different letters, such as X-Y-Z and Z-X-Y, the angle of the second rotation is in the range of (-π/2,
π/2). If the first and last letters of a rotation sequence are the same, such as X-Y-X and Z-Y-Z, the angle
of the second rotation is in the range (0, π).
For these cases, the locking issue occurs and there are infinite number of solutions for the angles of
the first and last rotations:
• A rotation sequence has different letters and the second rotation angle equals -π/2 or π/2.
• The first and last letters of a rotation sequence are the same and the second rotation angle equals
0 or π.
In these cases, the Transform Sensor block or the sequenceAngles method outputs only one set of
solutions where the magnitudes of the first and last angles are the same.
3-61
3 Internal Mechanics, Actuation and Sensing
See Also
Related Examples
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specify Joint Actuation Torque” on page 3-82
More About
• “Motion Sensing” on page 3-54
• “Translational Measurements” on page 3-63
• “Selecting a Measurement Frame” on page 3-67
3-62
Translational Measurements
Translational Measurements
In this section...
“Translation Sensing Overview” on page 3-63
“Measuring Translation” on page 3-63
“Cartesian Measurements” on page 3-64
“Cylindrical Measurements” on page 3-64
“Spherical Measurements” on page 3-65
Measuring Translation
Translation is a relative quantity. The translation of one frame is meaningful only with respect to
another frame. As such, blocks with translation sensing capability require two frames to make a
measurement: measured and reference frames. In these blocks, the follower frame port identifies the
measured frame; the base frame port identifies the reference frame of the measurement.
Some measurements are common to multiple coordinate systems. One example is the Z-coordinate,
which exists in both Cartesian and cylindrical systems. In the Transform Sensor dialog box,
coordinates that make up more than one coordinate system appear only once. Selecting Z outputs
translation along the Z-axis in both Cartesian and cylindrical coordinate systems.
Other measurements are different but share the same name. For example, radius is a coordinate in
both spherical and cylindrical systems. The spherical radius is different from the cylindrical radius:
the former is the distance between two frame origins; the latter is the distance between one frame
origin and a frame Z-axis.
To differentiate between the two radial coordinates, Simscape Multibody uses the following
convention:
3-63
3 Internal Mechanics, Actuation and Sensing
Cartesian Measurements
The Cartesian coordinate system uses three linear coordinates—X, Y, and Z—corresponding to three
mutually orthogonal axes. Cartesian translation measurements have units of distance, with meter
being the default. You can use the PS-Simulink Converter block to select a different physical unit
when interfacing with Simulink blocks.
Transform Sensor
You can select any of the Cartesian axes in the Transform Sensor for translation sensing. This is true
even if translation is constrained along any of the Cartesian axes. Selecting the Cartesian axes
exposes physical signal ports x, y, and z, respectively.
Joints
With joint blocks, you can sense translation along each prismatic primitive axis. Selecting a sensing
parameter from a prismatic primitive menu exposes the corresponding physical signal port. For
example, if you select Position from the Z Prismatic Primitive (Pz) of a Cartesian Joint block, the
block exposes physical signal port z.
Cylindrical Measurements
The cylindrical coordinate system uses one angular and two linear coordinates. The linear
coordinates are the cylinder radius, R, and length, Z. The angular coordinate is the azimuth, ϕ, about
the length axis. Linear coordinates have units of distance, with meter being the default. The angular
coordinate has units of angle, with radian being the default. You can use the PS-Simulink Converter
block to select a different physical unit when interfacing with Simulink blocks.
3-64
Translational Measurements
Transform Sensor
Only the Transform Sensor block can sense frame translation in cylindrical coordinates. In the dialog
box of this block, you can select one or more cylindrical coordinates to measure. The cylindrical
coordinates are named Z, Radius, and Azimuth. Selecting the cylindrical coordinates exposes
physical signal ports z, rad, and azm, respectively.
Spherical Measurements
The spherical coordinate system uses two angular coordinates and one linear coordinate. The linear
coordinate is the spherical radius, R. The angular coordinates are the azimuth, ϕ, and inclination, θ.
The linear coordinate has units of distance, with meter being the default. The angular coordinates
have units of angle, with radian being the default. You can use the PS-Simulink Converter block to
select a different physical unit when interfacing with Simulink blocks.
Transform Sensor
Only the Transform Sensor block can sense frame translation in spherical coordinates. In the dialog
box of this block, you can select one or more spherical coordinates to measure. The spherical
coordinates are named Azimuth, Distance, and Inclination. Selecting the spherical coordinates
exposes physical signal ports azm, dst, and inc, respectively.
Note Azimuth belongs to both cylindrical and spherical systems. Distance is the spherical radius.
See Also
Related Examples
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specify Joint Actuation Torque” on page 3-82
More About
• “Motion Sensing” on page 3-54
• “Rotational Measurements” on page 3-58
3-65
3 Internal Mechanics, Actuation and Sensing
3-66
Selecting a Measurement Frame
You can use the Transform Sensor block to measure the relative relationship between two arbitrary
frames that are connected to the B and F frame ports of the block. The relationship includes relative
rotation, translation, and their first and second time derivatives. These measurements are 3-D vectors
or higher dimensioned quantities, such as rotation matrices.
To do computation with the measured vectors, the vectors must be expressed in coordinates. The
setting of Measurement Frame parameter determines where to express the measured vectors; the
vectors are expressed in the selected frame's coordinates. For example, in the figure, because
Measurement Frame was set to World, the Transform Sensor block expresses a translation vector,
shown as a black arrow, in the world frame's coordinates.
Note The rotation measurement of the Transform Sensor block is independent of the Measurement
Frame parameter.
Measurement Frames
You can set the Measurement Frame parameter to World, Base, Follower, Non-Rotating Base,
or Non-Rotating Follower.
World
The Transform Sensor block expresses and observes the measured vectors by using the world frame.
For an example, see “World” on page 3-70.
Base or Follower
The Transform Sensor block expresses and observes the measured vectors by using the selected base
or follower frame.
3-67
3 Internal Mechanics, Actuation and Sensing
The base or follower frame is the frame that connects to the block's B or F port, respectively. The
base and follower frames are non-inertial. Therefore, the vectors expressed in the base or follower
frame may involve centripetal and Coriolis terms.
The Transform Sensor block maps the vectors expressed in the world frame to the selected frame
that is non-rotating base or non-rotating follower frame. In other words, the block calculates the
rotation matrix from the world frame to the current base or follower frame then multiplies the matrix
with the vectors expressed in the world frame.
The non-rotating base or non-rotating follower frame is an instantaneous frame that is coincident and
aligned with the corresponding base or follower frame at the current time. The measurements
expressed in the non-rotating frames do not involve centripetal and Coriolis terms.
The table compares the properties of the measurements for the different Measurement Frame
settings.
When a selected frame satisfies the standard derivative relationship, the measurements expressed in
this frame are related to each other. For example, when you select World, the expressed linear
acceleration vector is the time derivative of the expressed linear velocity vector, which is the time
derivative of the expressed linear translation vector.
Example
This example shows the measurements of the Transform Sensor block with different settings of the
Measurement Frame parameter. The image illustrates a single degree-of-freedom system with four
parts: a support, hub, rod, and car. The support is fixed on the ground, and the rod connects the hub
and car. The base, follower, and world frames of the system are located at the center of the hub, car,
and support’s bottom, respectively. Note that the world and base frames are fixed frames and the
follower frame moves with the car.
3-68
Selecting a Measurement Frame
The rod has a length of r and rotates with a constant angular velocity, ω, around the Z-axis of the
base frame. A Transform Sensor block is used to measure the relative motions between the car and
hub. For example, the block measures the relative translation, d(t) and rotation, RFB(t) between the
car and hub. The RFB(t) maps vectors in the follower frame to vectors in the base frame.
The image shows the front view of the system. For simplicity purposes, this example only shows how
to express linear measurements, such as translation, velocity, and acceleration, in Cartesian
coordinates.
3-69
3 Internal Mechanics, Actuation and Sensing
World
When you set Measurement Frame to World, the block measures the motion of the follower frame
with respect to the base frame then expresses and observes the relative motion by using the world
frame.
3-70
Selecting a Measurement Frame
The translation, velocity, and acceleration vectors have constant magnitudes because the length of
the rod and the rotational speed are constant. However, they rotate with a constant rotational
velocity, ω, around the Y-axis of the world frame. Therefore, the translation, velocity, and acceleration
vectors can be observed as:
cosωt
dw(t) = r 0
sinωt
−sinωt
vw(t) = rω 0
cosωt
−cosωt
aw(t) = rω2 0
−sinωt
Note that the vectors expressed in the world frame always satisfy the standard derivative
relationship. For example, aw equals the time derivative of vw.
3-71
3 Internal Mechanics, Actuation and Sensing
Base or Follower
When you set Measurement Frame to Base, the block measures the relative motion of the follower
frame with respect to the base frame then expresses and observes the relative motion by using the
bases frame.
Because the base frame is fixed in this example, the measurements can be observed as:
cosωt
db(t) = r sinωt
0
−sinωt
vb(t) = rω cosωt
0
−cosωt
ab(t) = rω2 −sinωt
0
When you set Measurement Frame to Follower, the block measures the relative motion of the
follower frame to the base frame then expresses and observes the relative motion by using the
follower frame. The expressed vectors include centripetal and Coriolis terms because the follower
frame rotates over time. To an observer attached to the follower frame, the origin of the base frame
never moves. Therefore, the offset between the base and follower frames is constant, and the relative
linear velocity and linear acceleration are zero.
3-72
Selecting a Measurement Frame
0
df (t) = r 0
−1
0
vf (t) = 0
0
0
af (t) = 0
0
Note that the vectors expressed in the base and follower frames always satisfy the standard
derivative relationship. For example, vb equals the time derivative of db.
When you set Measurement Frame to Non-Rotating Base, the block maps the vectors expressed
in the world frame to an instantaneous frame that is coincident and aligned with the base frame at
the current moment.
3-73
3 Internal Mechanics, Actuation and Sensing
cosωt
B
dnb(t) = RW * dw(t) = r sinωt
0
−sinωt
B
vnb(t) = RW * vw(t) = rω cosωt
0
−cosωt
B
anb(t) = RW * aw(t) = rω2 −sinωt
0
When you set Measurement Frame to Non-Rotating Follower, the block maps the vectors
expressed in the world frame to an instantaneous frame that is coincident and aligned with the
follower frame at the current moment.
3-74
Selecting a Measurement Frame
0
F
dnf (t) = RW * dw(t) =r 0
−1
1
F
vnf (t) = RW * vw(t) = rω 0
0
0
F
anf (t) = RW * aw(t) = rω2 0
1
Note that if a base or follower frame is not fixed, the measurements in its corresponding non-rotating
frame do not satisfy the standard derivative relationship. For example, because the follower frame
rotates, if you set Measurement Frame to Non-Rotating Follower, the expressed velocity vector
is not the time derivative of the expressed translation vector.
3-75
3 Internal Mechanics, Actuation and Sensing
See Also
Related Examples
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specify Joint Actuation Torque” on page 3-82
More About
• “Motion Sensing” on page 3-54
• “Rotational Measurements” on page 3-58
• “Translational Measurements” on page 3-63
3-76
Sense Motion Using a Transform Sensor Block
Model Overview
The Transform Sensor block provides the broadest motion-sensing capability in Simscape Multibody
models. Using this block, you can sense motion variables between any two frames in a model. These
variables can include translational and rotational position, velocity, and acceleration.
In this example, you use a Transform Sensor block to sense the lower link translational position with
respect to the World frame. You output the position coordinates directly to the model workspace, and
then plot these coordinates using MATLAB commands. By varying the joint state targets, you can
analyze the lower-link motion under quasi-periodic and chaotic conditions.
Modeling Approach
In this example, you rely on gravity to cause the double pendulum to move. You displace the links
from equilibrium and then let gravity act on them. To displace the links at time zero, you use the
State Targets section of the Revolute Joint block dialog box. You can specify position or velocity.
When you are ready, you simulate the model to analyze its motion.
To sense motion, you use the Transform Sensor block. First, you connect the base and follower frame
ports to the World Frame and lower link subsystem blocks. By connecting the ports to these blocks,
3-77
3 Internal Mechanics, Actuation and Sensing
you can sense motion in the lower link with respect to the World frame. Then, you select the
translation parameters to sense. By selecting Y and Z, you can sense translation along the Y and Z
axes, respectively. You can plot these coordinates with respect to each other and analyze the motion
that they reveal.
Build Model
1 At the MATLAB command prompt, enter openExample("sm/
DocDoublePendulumModelExample"). A double pendulum model opens up. For instructions
on how to create this model, see “Model an Open-Loop Kinematic Chain” on page 2-13.
2 Drag these blocks into the model to sense motion.
3-78
Sense Motion Using a Transform Sensor Block
1 In the Revolute Joint block dialog box, select State Targets > Specify Position Target.
2 Set Value to 10 deg.
3 In the Revolute Joint1 block dialog box, check that State Targets > Specify Position Target is
cleared.
Simulate Model
Run the simulation. Mechanics Explorer plays a physics-based animation of the double pendulum
assembly.
You can now plot the position coordinates of the lower link. To do this, at the MATLAB command line,
enter:
figure;
plot(y_link.data, z_link.data, 'color', [60 100 175]/255);
xlabel('Y Coordinate (cm)');
ylabel('Z Coordinate (cm)');
grid on;
The figure shows the plot that opens. This plot shows that the lower link path varies only slightly with
each oscillation. This behavior is characteristic of quasi-periodic systems.
3-79
3 Internal Mechanics, Actuation and Sensing
By adjusting the revolute joint state targets, you can simulate the model under chaotic conditions.
One way to obtain chaotic motion is to rotate the top revolute joint by a large angle. To do this, in the
Revolute Joint dialog box, change State Targets > Position > Value to 90 and click OK.
Simulate the model with the new joint state target. To plot the position coordinates of the lower
pendulum link with respect to the world frame, at the MATLAB command prompt, enter this code:
figure;
plot(y_link.data, z_link.data, 'color', [60 100 175]/255);
xlabel('Y Coordinate (cm)');
ylabel('Z Coordinate (cm)');
grid on;
3-80
Sense Motion Using a Transform Sensor Block
Save Model
Save the model in a convenient folder under the name double_pendulum_sensing. You reuse this
model in a subsequent tutorial, “Specify Joint Motion in Planar Manipulator Model” on page 3-112.
3-81
3 Internal Mechanics, Actuation and Sensing
In this section...
“Model Overview” on page 3-82
“Four-Bar Linkages” on page 3-82
“Modeling Approach” on page 3-84
“Build Model” on page 3-85
“Simulate Model” on page 3-88
Model Overview
In Simscape Multibody, you actuate a joint directly using the joint block. Depending on the
application, the joint actuation inputs can include force/torque or motion variables. In this example,
you prescribe the actuation torque for a revolute joint in a four-bar linkage model.
Transform Sensor blocks add motion sensing to the model. You can plot the sensed variables and use
the plots for kinematic analysis. In this example, you plot the coupler curves of three four-bar linkage
types: crank-rocker, double-crank, and double-rocker.
Four-Bar Linkages
The four-bar linkage contains four links that interconnect with four revolute joints to form a planar
closed loop. This linkage converts the motion of an input link into the motion of an output link.
Depending on the relative lengths of the four links, a four-bar linkage can convert rotation into
rotation, rotation into oscillation, or oscillation into oscillation.
Links
Links go by different names according to their functions in the four-bar linkage. For example, coupler
links transmit motion between crank and rocker links. The table summarizes the different link types
that you may find in a four-bar linkage.
3-82
Specify Joint Actuation Torque
Link Motion
Crank Revolves with respect to the ground link
Rocker Oscillates with respect to the ground link
Coupler Transmits motion between crank and rocker links
Ground Rigidly connects the four-bar linkage to the world
or another subsystem
It is common for links to have complex shapes. This is especially true of the ground link, which may
be simply the fixture holding the two pivot mounts that connect to the crank or rocker links. You can
identify links with complex shapes as the rigid span between two adjacent revolute joints. In example
“Model a Closed-Loop Kinematic Chain” on page 2-16, the rigid span between the two pivot mounts
represents the ground link.
Linkages
The type of motion conversion that a four-bar linkage provides depends on the types of links that it
contains. For example, a four-bar linkage that contains two crank links converts rotation at the input
link into rotation at the output link. This type of linkage is known as a double-crank linkage. Other
link combinations provide different types of motion conversion. The table describes the different
types of four-bar linkages that you can model.
Grashof Condition
The Grashof theorem provides the basic condition that the four-bar linkage must satisfy so that at
least one link completes a full revolution. According to this theorem, a four-bar linkage contains one
or more crank links if the combined length of the shortest and longest links does not exceed the
combined length of the two remaining links. Mathematically, the Grashof condition is:
where:
Grashof Linkages
• Crank-rocker
• Double-crank
• Double-rocker
3-83
3 Internal Mechanics, Actuation and Sensing
By changing the ground link, you can change the Grashof linkage type. For example, by assigning the
crank link of a crank-rocker linkage as the ground link, you obtain a double-crank linkage. The figure
shows the four linkages that you obtain by changing the ground link.
Modeling Approach
In this example, you perform two tasks. First you add a torque actuation input to the model. Then,
you sense the motion of the crank and rocker links with respect to the World frame. The actuation
input is a torque that you apply to the joint connecting the base to the crank link. Because you apply
the torque at the joint, you can add this torque directly through the joint block. The block that you
add the actuation input to is called Base-Crank Revolute Joint.
You add the actuation input to the joint block through a physical signal input port. This port is hidden
by default. To display it, you must select Provided by Input from the Actuation > Torque drop-
down list.
You can then specify the torque value using either Simscape or Simulink blocks. If you use Simulink
blocks, you must use the Simulink-PS Converter block. This block converts the Simulink signal into a
physical signal that Simscape Multibody can use. For more information, see “Actuating and Sensing
with Physical Signals” on page 3-29.
To sense crank and rocker link motion, you use the Transform Sensor block. With this block, you can
sense motion between any two frames in a model. In this example, you use it to sense the [Y Z]
coordinates of the crank and rocker links with respect to the World frame.
The physical signal output ports of the Transform Sensor blocks are hidden by default. To display
them, you must select the appropriate motion outputs. Using the PS-Simulink Converter, you can
3-84
Specify Joint Actuation Torque
convert the physical signal outputs into Simulink signals. You can then connect the resulting Simulink
signals to other Simulink blocks.
In this example, you output the crank and rocker link coordinates to the workspace using Simulink To
Workspace blocks. The output from these blocks provide the basis for phase plots showing the
different link paths.
Build Model
Provide the joint actuation input, specify the joint internal mechanics, and sense the position
coordinates of the coupler link end frames.
Library Block
Simulink > Sources Constant
Simscape > Utilities Simulink-PS Converter
4 Connect the blocks as shown in the figure. The new blocks are shaded gray.
3-85
3 Internal Mechanics, Actuation and Sensing
Real joints dissipate energy due to damping. You can specify joint damping directly in the block dialog
boxes. In each Revolute Joint block dialog box, under Internal Mechanics > Damping Coefficient,
enter 5e-4 and press OK.
1 Add these blocks to the model. The blocks enable you to sense frame position during simulation.
3-86
Specify Joint Actuation Torque
3 In the Output signal unit parameters of the PS-Simulink Converter block dialog boxes, enter
cm.
4 In the Variable Name parameters of the To Workspace block dialog boxes, enter the variable
names:
• y_crank
• z_crank
• y_rocker
• z_rocker
5 Connect and name the blocks as shown in the figure, rotating them as needed. Ensure that the To
Workspace blocks with the z_crank and z_rocker variable names connect to the z frame ports of
the Transform Sensor blocks. The new blocks are shaded yellow.
3-87
3 Internal Mechanics, Actuation and Sensing
Simulate Model
Run the simulation. You can do this in the Simulink tool bar by clicking the run button. Mechanics
Explorer plays a physics-based animation of the four bar assembly.
3-88
Specify Joint Actuation Torque
Once the simulation ends, you can plot the position coordinates of the coupler link end frames, e.g.,
by entering the following code at the MATLAB command line:
figure;
plot(y_crank.data, z_crank.data, 'color', [60 100 175]/255);
hold;
plot(y_rocker.data, z_rocker.data, 'color', [210 120 0]/255);
xlabel('Y Coordinate (cm)');
ylabel('Z Coordinate (cm)');
axis equal; grid on;
The figure shows the plot that opens. This plot shows that the crank completes a full revolution, while
the rocker completes a partial revolution, e.g., it oscillates. This behavior is characteristic of crank-
rocker systems.
3-89
3 Internal Mechanics, Actuation and Sensing
Try simulating the model in double-crank mode. You can change the four-bar linkage into a double-
crank linkage by changing the binary link lengths according to the table.
Update and simulate the model. The figure shows the updated visualization display in Mechanics
Explorer.
Plot the position coordinates of the coupler link end frames. At the MATLAB command line, enter:
figure;
plot(y_crank.data, z_crank.data, 'color', [60 100 175]/255);
hold;
plot(y_rocker.data, z_rocker.data, 'color', [210 120 0]/255);
xlabel('Y Coordinate (cm)');
ylabel('Z Coordinate (cm)');
axis equal; grid on;
The figure shows the plot that opens. This plot shows that both links complete a full revolution. This
behavior is characteristic of double-crank linkages.
3-90
Specify Joint Actuation Torque
3-91
3 Internal Mechanics, Actuation and Sensing
In this section...
“Build Model” on page 3-92
“Specify Block Parameters” on page 3-94
“Create Simulation Script” on page 3-95
“Run Simulation Script” on page 3-95
This example shows how to use a MATLAB script to study the dynamic behaviours of a four-bar model
at various coupler lengths. The script uses the coupler motion coordinates, obtained using a
Transform Sensor block, to plot the resulting coupler curve at each value of the coupler length. For
more information about multibody dynamics simulations, see “Multibody Dynamics”.
Build Model
1 At the MATLAB command prompt, enter openExample("sm/
DocFourBarLinkageModelExample"). A four-bar model opens up. For instructions on how to
create this model, see “Model a Closed-Loop Kinematic Chain” on page 2-16.
2 Under the mask of the Binary Link B block, connect a third Outport block as shown in the figure.
You can add an Outport block by copying and pasting Conn1 or Conn2. The new block identifies
the frame whose trajectory you plot in this tutorial.
3-92
Analyze Motion at Various Parameter Values
3 Add the following blocks to the model. During simulation, the Transform Sensor block computes
and outputs the coupler trajectory with respect to the world frame.
• Translation > Y
• Translation > Z
The block exposes frame ports y and z, through which it outputs the coupler trajectory
coordinates.
5 Connect the blocks as shown in the figure. Be sure to flip the Transform Sensor block so that its
base frame port, labeled B, connects to the World Frame block.
3-93
3 Internal Mechanics, Actuation and Sensing
3-94
Analyze Motion at Various Parameter Values
The code runs simulation at nine different coupler link lengths. It then plots the trajectory
coordinates of the coupler link center frame with respect to the world frame. Coupler link
lengths range from 20 cm to 28 cm.
3 Save the script as simFourBar in the folder containing the four-bar model.
3-95
3 Internal Mechanics, Actuation and Sensing
Simscape Multibody iteratively runs each simulation, adding the resulting coupler link curve to the
active plot. The figure shows the final plot.
You can use the simple approach shown in this tutorial to analyze model dynamics at various
parameter values. For example, you can create a MATLAB script to simulate a crank-slider model at
different coupler link lengths, plotting for each simulation run the constraint force acting on the
piston.
See Also
Revolute Joint
More About
• “Model a Closed-Loop Kinematic Chain” on page 2-16
3-96
Measure Forces and Torques Acting at Joints
This example shows how to measure the actuator torque, constraint force, and total toque acting on a
Revolute Joint block. The example uses a rack and pinion model.
The joint blocks in Simscape™ Multibody™ have ports that measure force and torque. You can use
these ports to compute and output various types of forces and torques acting directly at joints. For
more information about forces and torques, see “Force and Torque Sensing” on page 3-34.
Open Model
To open the rack and pinion model, at the MATLAB® command prompt, enter:
openExample('sm/DocRackPinionExample','supportingFile','DocRackPinion.slx')
3-97
3 Internal Mechanics, Actuation and Sensing
The rack and pinion model uses a Signal Editor block to specify the actuator torque that drives the
pinion. Because the Input filtering order property of the Simulink-PS Converter block is set to
Second-order filtering, the block processes the input torque by smoothing any abrupt changes
or discontinuities. To measure the actuator torque at the Revolute Joint block:
• Double-click the Revolute Joint block to open the block dialog. Under Z Revolute Primitive (Rz)
> Sensing, select Actuator Torque. The block exposes the port t that outputs the actuator
torque, which is a 3-D vector physical signal acting at the joint primitive.
• Add a PS-Simulink Converter block and To Workspace block to the model, then connect the blocks
as shown in the figure.
• Double-click the PS-Simulink Converter block. Set the Output signal unit parameter to N*m.
• Simulate the model. The To Workspace block outputs the actuator torque to the simout variable in
the MATLAB base workspace.
• Plot the torque. At the MATLAB command prompt, enter:
figure;
plot(simout);
MATLAB plots the joint actuator torque. All but the z-component are zero throughout the simulation.
3-98
Measure Forces and Torques Acting at Joints
Compare the actuator torque plot to the input torque specified in the Signal Editor block. Neglecting
any signal smoothing due to the second-order filtering, the two signals are identical. This figure
shows the input torque.
3-99
3 Internal Mechanics, Actuation and Sensing
Joint constraint forces, which act normal to the joint primitive axes, restrict motion to the allotted
degrees of freedom. In this model, the constraint forces acting at the Revolute Joint block resist the
pull of gravity and keep the position of the pinion with respect to the world frame. To sense the
constraint forces:
• In the Mechanism Configuration block, set Uniform Gravity to Constant. Ensure that the
Gravity parameter is [0 0 -9.80665].
• In the Revolute Joint block, select Composite Force/Torque Sensing > Constraint Force. The
block exposes the port fc. The port outputs constraint forces that act at the joint to maintain the
translational constraints.
• Under Z Revolute Primitive (Rz) > Sensing, clear Actuator Torque.
• Double-click the PS-Simulink Converter block, set the Output signal unit parameter to N. Ensure
that the PS-Simulink Converter block connects to the port fc.
• Simulate the model, then plot the constraint forces. At the MATLAB command prompt, enter:
figure;
plot(simout);
MATLAB plots the constraint force with respect to time. The x and y-components are zero throughout
the simulation. The z component, which opposes the gravity vector, is the only component needed to
hold the joint frames in place.
3-100
Measure Forces and Torques Acting at Joints
Tips:
In a Weld Joint block, the constraint forces ensure the base and follower frames remain fixed with
respect to each other. You can place a Weld Joint block inside a body subsystem to measure the
internal forces or torques acting in that body during a simulation. For an example of how you can do
this in a double pendulum model, see “Measure Joint Constraint Forces” on page 3-103.
The total force or torque is a sum of all forces or torques that act between the joint base and follower
frames and includes contributions from the actuator, constraint, and internal forces or torques. To
measure the total torque that acts at the revolute joint:
• Double-click the Revolute Joint block to open the block diagram. Under Composite Force/Torque
Sensing, select Total Torque. The block exposes the port tt. This port outputs the total torque
that acts at the joint.
• Under Composite Force/Torque Sensing, clear Constraint Force.
• Double-click the PS-Simulink Converter block, set the Output signal unit parameter to N*m.
Ensure that the PS-Simulink Converter block connects to the port tt.
• Simulate the model.
• Plot the total torque. At the MATLAB command prompt, enter:
figure;
plot(simout);
MATLAB plots the total torque, which is a 3-D vector, as a function of time. The x and y-components
are zero throughout simulation. The z-component contains torque contributions from the actuation
and internal torques.
3-101
3 Internal Mechanics, Actuation and Sensing
In the plot, the torque peaks are due to the actuator torque. These peaks decay with time due to the
internal damping torques specified in the Revolute Joint block. The damping torques cause the energy
dissipation evident in the transient portions of the total torque plot.
See Also
Revolute Joint
More About
• “Force and Torque Sensing” on page 3-34
• “Measure Joint Constraint Forces” on page 3-103
3-102
Measure Joint Constraint Forces
You can use joint blocks to measure the actuation forces and torques that drive joint primitives in
Simscape Multibody models. You can also measure the total and constraint forces acting on an entire
joint.
This example shows how to use a Weld Joint block to measure the time-varying internal forces that
hold a body together. As shown in the image, the weld joint connects the two parts of the distal link
and constrains the relative motions between the two parts. The internal forces in the distal link are
equal to the constraint forces acting on the weld joint. The example uses a double-pendulum model.
For information on how to create this model, see “Model an Open-Loop Kinematic Chain” on page 2-
13.
This figure shows the constraint forces that act on the weld joint. The longitudinal constraint force
aligns with the x-axes of the weld joint frames. The transverse constraint force aligns with the y-axes.
The constraint force along the z-axes is negligible because the motion of the double-pendulum model
remains in the xy-plane.
3-103
3 Internal Mechanics, Actuation and Sensing
You can use the Weld Joint block to measure the constraint force that the follower frame exerts on the
base frame or, alternatively, the constraint force that the base frame exerts on the follower frame. The
forces have the same magnitude but opposite directions. In this example, the Weld Joint block
measures the constraint force that the follower frame exerts on the base frame.
You can also specify the frame to resolve the measured constraint forces. The resolution frame can be
either the base or follower frame. Certain joint blocks, such as the 6-DOF Joint block, can have
different orientations for the base and follower frames, which causes the same measurement to differ
depending on the choice of the resolution frame.
3-104
Measure Joint Constraint Forces
Library Block
Simscape > Utilities PS-Simulink Converter
Simulink > Sinks To Workspace
4 Connect the blocks as shown in the figure.
Specify Damping
For each Revolute Joint block, in the dialog box, set Internal Mechanics > Damping Coefficient to
1e-5 N*m/(deg/s). The damping coefficient enables you to model energy dissipation during
motion, so that the double-pendulum model eventually comes to rest.
Simulate Model
1 In the Modeling tab, click Model Settings.
2 In the left pane of the Configuration Parameters window, click Solver, and set Solver to
ode15s(stiff/NDF). This solver is recommended for physical models.
3 Expand Solver details and set the Max step size parameter to 0.001 s.
4 Run the simulation. Mechanics Explorer opens with a dynamic view of the model. In the
Mechanics Explorers tab, click the Isometric View button to view the double pendulum from an
isometric perspective.
3-105
3 Internal Mechanics, Actuation and Sensing
figure;
plot3(fcf_weld.time, fcf_weld.data(:,1), fcf_weld.data(:,2),...
'.', 'MarkerSize', 1, 'Color', 'r');
grid on;
xlabel('T, s');
ylabel('F_{C,X}, mN');
zlabel('F_{C,Y}, mN');
MATLAB plots the axial and transverse constraint forces with respect to time in 3-D. The figure shows
the resulting plot.
3-106
Measure Joint Constraint Forces
See Also
Revolute Joint | Weld Joint
More About
• “Force and Torque Sensing” on page 3-34
• “Measure Forces and Torques Acting at Joints” on page 3-97
3-107
3 Internal Mechanics, Actuation and Sensing
In this section...
“Build Model” on page 3-108
“Simulate Model” on page 3-110
This example shows how to specify the motion of a Revolute Joint block and measure the
corresponding actuation torque at the joint. The example uses a four-bar linkage mechanism.
To drive the linkage, you prescribe a time-varying position signal for the crank angle. Then you use
the Revolute Joint block to sense the actuation torque at the joint that corresponds to the prescribed
motion.
Build Model
1 At the MATLAB command prompt, enter openExample("sm/
DocFourBarLinkageModelExample") to open the linkage model. To learn how to build the
model, see “Model a Closed-Loop Kinematic Chain” on page 2-16.
2 Double-click the Base-Crank Revolute Joint block and specify these parameters:
Parameter Setting
Actuation > Torque Automatically Computed
Actuation > Motion Provided by Input
Sensing > Actuator Torque Selected
The block displays two physical signal ports. Input port q accepts the joint angular position.
Output port t provides the joint actuation torque required to achieve the prescribed angular
positions.
3 For each of the four Revolute Joint blocks, in the Internal Mechanics section, set the Damping
Coefficient to 5e-4 N*m/(deg/s). During the simulation, damping forces between the joint
frames account for dissipative losses at the joints.
4 Add these blocks to the model. These blocks enable you to specify an actuation position signal
and plot the actuation torque for the joint.
3-108
Specify Joint Motion Profile
Block Library
Simulink-PS Converter Simscape > Utilities
PS-Simulink Converter Simscape > Utilities
Scope Simulink > Sinks
Signal Editor Simulink > Sources
5 Connect the blocks as shown in the figure.
Parameter Value
Input Heading > Filtering and Filter input, derivatives
derivatives calculated
Input Heading > Input filtering order Second-order filtering
7 Use the Signal Editor block to specify the position signal. This example uses the default unit, rad,
for the signal. You can change the unit of the input signal by using the Simulink-PS Converter
block.
3-109
3 Internal Mechanics, Actuation and Sensing
• On the Signal Editor tab, click Save to save the data to a MAT-file. Close the Signal Editor
window.
• In the dialog box, under Signal properties, select Interpolate data, click Apply and OK.
Simulate Model
Run the simulation. Mechanics Explorer opens with a dynamic display of the four-bar model.
3-110
Specify Joint Motion Profile
Open the Scope window. The plot shows the joint actuation torque with which you can achieve the
motion you prescribed.
See Also
Related Examples
• “Create and Edit Signal Data”
• “How to Work with Physical Units”
• “Specify Joint Motion in Planar Manipulator Model” on page 3-112
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specifying Motion Input Derivatives” on page 3-25
3-111
3 Internal Mechanics, Actuation and Sensing
In this section...
“Add Virtual Joint” on page 3-112
“Prescribe Motion Inputs” on page 3-113
“Sense Joint Actuation Torques” on page 3-116
“Simulate Model” on page 3-117
This example shows how to specify the trajectory of the end effector of a planar manipulator and
measure the required actuator torques of the manipulator joints in the multibody dynamics model.
For more information about multibody dynamics simulations, see “Multibody Dynamics”.
In this example, you specify the time-varying trajectory coordinates of the end-effector frame with
respect to the world frame by using a 6-DOF Joint block. This block provides the requisite degrees of
freedom between the two frames. In this model, the 6-DOF Joint block does not act as a physical
connection.
During the simulation, the end effector traces the specified square pattern and the revolute joints
compute the required actuator torques.
3-112
Specify Joint Motion in Planar Manipulator Model
In this model, the 6-DOF Joint block works as a virtual connection between the world frame and
the end-effector frame. The block uses the position inputs to specify the trajectory of the end-
effector frame with respect to world frame. Ensure that the base frame of the 6-DOF Joint block
connects to the world frame and the follower frame connects to the end-effector frame.
Parameter Select
Y Prismatic Primitive (Py) > Actuation > Provided by Input
Motion
Z Prismatic Primitive (Pz) > Actuation > Provided by Input
Motion
3-113
3 Internal Mechanics, Actuation and Sensing
• In the left pane, right-click Scenario, select Insert > Signal, rename the new signal to pz,
select the Plot/Edit check box, and edit data as shown in the image.
3-114
Specify Joint Motion in Planar Manipulator Model
• In the Signal Editor tab, click Save to save the data to a MAT-file. Close the Signal Editor
window.
• In the dialog box, under Signal properties, set Active signal to py and select Interpolate
data. Then, set Active signal to pz and select Interpolate data. Click Apply and OK.
4 Use the Simulink-PS Converter blocks to convert Simulink signals into physical signals.
Parameter Value
Units > Input signal unit cm
Input Handling > Filtering and Filter input, derivatives
derivatives calculated
Input Handling > Input filtering order Second-order filtering
Input Handling > Input filtering time 0.1
constant (in seconds)
Note that a small time filtering constant can slow a simulation significantly. For most Simscape
Multibody models, a value of 0.1 seconds often provides a sufficient balance between simulation
time and accuracy.
3-115
3 Internal Mechanics, Actuation and Sensing
Parameter Setting
Actuation > Torque Automatically Computed
Sensing > Actuator Torque Selected
Note Simscape Multibody requires the number of joint primitive degrees of freedom with motion
inputs to be equal to the number of joint primitive degrees of freedom with automatically
computed joint actuator forces and torques. If the model does not meet this condition, the
simulation fails with an error.
2 Add two PS-Simulink Converter blocks and two To Workspace blocks to the model.
3 In the PS-Simulink Converter blocks, set Vector format to 1-D array. The PS-Simulink Converter
blocks convert the physical signal outputs into Simulink signals.
4 In the two To Workspace blocks, specify the Variable name parameter as t1 and t2,
respectively.
3-116
Specify Joint Motion in Planar Manipulator Model
Simulate Model
If you run the simulation, Simulink fails with an error.
Note Simscape Multibody requires any closed kinematic loop to contain at least one joint block
without motion inputs or automatically computed actuator forces or torques.
To solve the error, add a Weld Joint block to the Binary Link A subsystem and connect the blocks as
shown in the figure.
Run the simulation again. Mechanics Explorer opens with a dynamic 3-D display of the planar
manipulator model.
3-117
3 Internal Mechanics, Actuation and Sensing
Plot the computed actuation torques that act at the two revolute joints in the linkage. At the MATLAB
command line, enter:
figure;
hold on;
plot(t1.time, t1.data, 'color', [60 100 175]/255);
plot(t2.time, t2.data, 'color', [210 120 0]/255);
xlabel('Time');
ylabel('Torque (N*m)');
grid on;
The plot shows the time-varying actuation torques. These torques enable the manipulator end frame
to trace the prescribed square trajectory.
3-118
Specify Joint Motion in Planar Manipulator Model
See Also
Related Examples
• “Model an Open-Loop Kinematic Chain” on page 2-13
• “Sense Motion Using a Transform Sensor Block” on page 3-77
• “Specify Joint Motion Profile” on page 3-108
• “Specifying Motion Input Derivatives” on page 3-25
More About
• “Actuating and Sensing with Physical Signals” on page 3-29
• “Force and Torque Sensing” on page 3-34
• “Multibody Dynamics”
• “Specifying Joint Actuation Inputs” on page 3-20
3-119
Simulation and Analysis
121
4
Simulation
You can create a model manually or import it from a supported CAD application. For an example
showing how to create a model manually, see “Model an Open-Loop Kinematic Chain” on page 2-13.
For an example showing how to import a model, see “Import a CAD Assembly Model” on page 6-11.
In the Modeling tab, click Update Model. Mechanics Explorer opens with a static visualization of
the model in its initial state.
4-2
Update and Simulate a Model
Check the model assembly in the visualization pane of Mechanics Explorer. Look for bodies placed
and oriented in unexpected ways. Use the Simscape Variable Viewer or the Simscape Multibody
Model Report to identify any assembly issues. For an example showing the use of Model Report, see
“Model a Closed-Loop Kinematic Chain” on page 2-16.
Open the Configuration Parameters. In the Modeling tab, click Model Settings. Pick a solver and
specify the desired step sizes. Ensure that the time steps are small enough to accurately capture the
fastest meaningful changes in your model. Use care, though, as small time steps slow down
simulation.
Click Run. Mechanics Explorer plays a physics-based animation of your model. Examine any data
generated during simulation, for example, through Simulink Scope plots. For an example showing
how to work with sensing data from a model, see “Sense Motion Using a Transform Sensor Block” on
page 3-77.
4-3
4 Simulation
Limited visualization in models with For Each Subsystem blocks. Models with one or more
For Each Subsystem blocks simulate with limited visualization. The Mechanics Explorer visualization
utility displays the model in only one of the instances provided by the For Each Subsystem blocks.
Model simulation is not affected.
No visualization in models with Model blocks. Models with Model blocks (often referred to as
referenced models) simulate without visualization. During simulation, Simscape Multibody software
issues a warning at the MATLAB command line. If previously closed, The Mechanics Explorer
visualization utility does not open.
No Simscape local solver support. Simscape Multibody software does not support Simscape
local solvers. If you select a local solver in the Simscape Solver Configuration block, the solver does
not apply to the Simscape Multibody portion of a model—which relies exclusively on the global
Simulink solver selected in the Model Configuration Parameters window.
4-4
5
5-2
Working with Animation
In this section...
“Animation Playback” on page 5-3
“Looping Playback” on page 5-3
“Changing Playback Speed” on page 5-3
“Jumping to Playback Time” on page 5-3
Animation Playback
Animation is cached during model simulation. What you see when you run a simulation is the
animation playback, unless the simulation is slower than the animation caching. In that case, the
animation goes no faster than the simulation can produce the cache.
Once a partial or complete animation is cached from simulation, starting the animation again plays
back the cache, without running the simulation a second time. You can move backward and forward
to any time in the cached animation.
The animation cache is stored until you close Mechanics Explorer. When you simulate the model, the
cache is updated with new animation data. To create a permanent record of a model animation, you
must create an animation video. See “Create a Model Animation Video” on page 5-28
Looping Playback
Use the Toggle Loop button in the Mechanics Explorer playback toolstrip to automatically replay an
animation from the start once it reaches the end. The cached animation replays indefinitely until you
click the Pause button. Enable looping by clicking the Toggle Loop button. Disable looping by
clicking the button again.
You can set the slider to multiples of 2 from 1/256 to 256. For slower or faster animations, adjust the
base playback speed for the model. To change this parameter, from the Mechanics Explorer menu bar,
select Tools > Animation Settings.
5-3
5 Visualization and Animation
Model Visualization
Multibody models lend themselves to 3-D visualization, a qualitative means of analysis that you can
use to examine body geometries, mechanical connections, and trajectories in three-dimensional
space. In Simscape Multibody, you can visualize a model using Mechanics Explorer, adjusting the
view point and detail level as needed. You can modify the model view by:
The figure shows a Cardan gear model from the different view points using a Z up (XY Top) view
convention.
5-4
Manipulate the Visualization Viewpoint
• Y up (XY Front)
• Z up (XY Top)
• Z down (YZ Front)
The figure shows a Cardan gear model from an isometric perspective using the three view
conventions: Y up, Z up, and Z down.
5-5
5 Visualization and Animation
1 In the Mechanics Explorer tool strip, set View convention to one of the three options.
2 Select a standard view button.
The new view convention takes effect the moment you select a standard view.
•
— Rotate the camera about a general 3-D axis.
•
— Roll the camera about its current aim axis.
•
— Pan the camera in the current visualization plane.
•
— Increase or decrease the camera zoom level.
•
— Change the camera zoom to show only the selected region.
You can also use keyboard-and-mouse shortcuts. The table summarizes the available shortcuts.
Button Shortcut
Rotate 1 Click and hold the mouse scroll wheel.
2 Move the mouse in the direction you want to
rotate the model.
5-6
Manipulate the Visualization Viewpoint
Button Shortcut
Pan 1 Press and hold Shift.
2 Click and hold the mouse scroll wheel.
3 Move the mouse in the direction you want to
pan the model.
Zoom 1 Press and hold Ctrl.
2 Click and hold the mouse scroll wheel.
3 Move the mouse up to zoom in, down to zoom
out.
• Split the model view into four equally sized tiles, each with a different view point (front, right, top,
and isometric views).
• Merge all tiles into a single pane with the view point of the last highlighted tile.
• Split a visualization tile vertically or horizontally into two equally sized tiles.
The figure shows the Cardan gear model with a four-way visualization split.
You can merge two tiles by clicking the black dot between the tiles. To ensure that the resulting tile
uses the view point of one or the other tile, select that tile first before clicking the black dot between
the tiles.
5-7
5 Visualization and Animation
Visualization Cameras
In this section...
“Camera Types” on page 5-8
“Global Camera” on page 5-9
“Dynamic Cameras” on page 5-9
“Camera Trajectory Modes” on page 5-9
“Dynamic Camera Selection” on page 5-10
“Dynamic Camera Reuse” on page 5-11
Camera Types
Cameras define the model viewpoints used during animation playback. Mechanics Explorer supports
two camera types—global and dynamic. The global camera provides a static viewpoint that you can
manipulate interactively during animation playback. Dynamic cameras provide moving viewpoints
that you predefine using Camera Manager.
Camera in a Model
The moving viewpoint of a dynamic camera enables you to more easily track the motion of a system.
You can use a dynamic camera to keep a moving vehicle such as an automobile or aircraft in view
during animation playback. You must define and select a dynamic camera in order to use it in a
model. See “Create a Dynamic Camera” on page 5-12.
The figure shows a model visualization captured from the view point of a dynamic camera. This model
is part of the “Configuring Dynamic Cameras - Vehicle Slalom” on page 8-51 featured example. You
can open the model from the MATLAB command prompt by entering OpenExample('sm/
DynamicCamerasExample).
5-8
Visualization Cameras
Global Camera
The global camera is a static camera that:
You must manipulate the camera manually to change the camera viewpoint, for example, by using
the Pan, Rotate, Roll, and Zoom buttons.
• Is external to the model.
You cannot position the global camera between bodies, for example, to prevent one body from
obstructing another during animation playback.
• Uses an orthographic projection.
Apparent body sizes remain constant regardless of object distance to the camera. This effect,
shown in the figure, is consistent with a camera located relatively far from the model.
The global camera is the default camera for all model visualization tiles—each a subdivision of the
model visualization pane, when split. In the absence of custom dynamic cameras, the global camera is
the only camera available in a model.
Dynamic Cameras
Dynamic cameras are custom cameras that:
Every dynamic camera follows a trajectory that you prespecify through Camera Manager. You
cannot use the Pan, Rotate, Roll, or Zoom buttons during animation playback.
• Can be internal to a model.
Dynamic cameras can be inside or outside the perimeter of a model. Position a camera between
bodies for a viewpoint internal to the model.
• Use a perspective projection.
Apparent body sizes vary noticeably with object distance to the camera, creating a more realistic
3-D effect. This effect, shown in the figure, is consistent with a camera located relatively close to
the model.
5-9
5 Visualization and Animation
• Keyframes — Set the camera viewpoints at various playback times. Each viewpoint constitutes a
keyframe. During playback, the camera transitions between the keyframes using the smooth
interpolation method of the pchip MATLAB function. Use this camera mode to obtain camera
trajectories independent of any components in your model.
• Tracking — Constrain the camera position, aim, and up vector to coordinate frames in your
model. During playback, the camera moves with the frames it is constrained to, translating and
rotating as needed to satisfy the specified constraints. Use this camera mode to track frames and
bodies during playback.
5-10
Visualization Cameras
See Also
Related Examples
• “Create a Dynamic Camera” on page 5-12
5-11
5 Visualization and Animation
1 Simulate the model that you want to add the camera to.
Dynamic cameras exist only in the models that you define them in.
2 In the Mechanics Explorer menu bar, select Tools > Camera Manager.
Camera Manager opens with a list of previously created dynamic cameras. The list is by empty
until you create your first camera.
3
In Camera Manager, click the button.
Camera Manager switches to a camera definition view that lets you select the camera mode and
specify the camera motion.
4 In the Camera Name field, enter a name for your camera.
Make the camera name descriptive so that you can later identify it when selecting an active
camera from the Mechanics Explorer visualization context-sensitive menu.
Complete the camera definition by selecting the camera mode and specifying the camera motion. See:
• “Define a Keyframes Camera” on page 5-12 to define the camera motion in Keyframes mode.
Keyframes are viewpoints that you specify at various playback times and that Simscape Multibody
software interpolates to obtain smooth camera trajectories.
• “Define a Tracking Camera” on page 5-13 to complete the camera definition in Tracking mode.
Tracking constraints include position, aim, and up vector constraints that you specify relative to
coordinate frames in a model.
Camera Manager switches to a Keyframes view that lets you define the camera keyframes.
2 In the Mechanics Explorer toolstrip, set the playback time for the current keyframe.
Drag the playback slider to the desired point in the animation timeline. Alternatively, enter the
time directly in the playback time counter.
3 In the visualization pane or tile, manipulate the model viewpoint for your keyframe.
5-12
Create a Dynamic Camera
Use the Rotate, Roll, Pan, and Zoom buttons to manipulate the model viewpoint. Use the preset
view buttons to obtain standard views such as front, side, or isometric.
4 In the Camera Manager Keyframes window, click the Set button.
Playback must be paused or stopped. Camera Manager commits the keyframe to the camera. The
playback slider identifies the keyframe with a colored line marker located at the specified
playback time.
5 Set new keyframes as in steps 2–4 until you are satisfied with the camera motion.
Simscape Multibody software transitions between keyframes using the smooth interpolation
method of the pchip MATLAB function to yield the final camera motion.
6 Click the Save button in the camera definition and main panes of Camera Manager.
Camera Manager saves the camera and its motion to the model. The visualization context-
sensitive menu adds the camera to the list of available cameras.
To edit an existing keyframe, use the Previous and Next buttons to navigate to the keyframe you
want to edit. Then, repeat the procedure for adding a keyframe. Use the colored markers in the
playback slider to identify the existing keyframes in your dynamic camera.
Click the Remove button if you want to delete the current keyframe. Click the Save button in the
main pane to commit your changes to the camera.
Camera Manager switches to a Tracking view that lets you define the camera constraints—
position, aim, and up vector—relative to frames in your model.
2 In the Camera Manager tracking window, set the camera Position, Aim, and Up Vector
constraints:
a In the tree view or visualization pane, select a frame to constrain the camera to.
If using the visualization pane, click a frame icon. If using the tree view pane, click a frame
node. It is not enough to click the body that the frame belongs to.
b Click the Use Selected Frame button to constrain the camera motion to the frame.
If you accidentally select the wrong frame, pick a new frame and click the Use Selected
Frame button again.
c For the Aim and Up Vector dropdown lists, select how to constrain the camera:
• The Position constraint fixes the camera to the frame origin only and has no options
dropdown list.
• The Aim constraint provides the option to aim the camera at the frame origin or along a
selected frame axis.
• The Up vector constraint provides the option to align the up vector along a selected
frame axis.
5-13
5 Visualization and Animation
1 Right-click the visualization pane or tile whose camera you want to switch.
5-14
Selective Model Visualization
Visualization filtering is a Mechanics Explorer feature that lets you selectively show and hide parts of
your model. By showing only those parts that you want to see, you can more easily discern any
components placed within or behind other components—such as an engine piston traveling inside a
cylinder casing.
The figure shows an example of visualization filtering. Two cylinders, one at the front and one at the
rear, are hidden in the model visualization of the TranslationalInterfaceExample featured example.
For a tutorial showing how to use visualization filtering, see “Selectively Show and Hide Model
Components” on page 5-20.
5-15
5 Visualization and Animation
• Show This — Enable visualization for the selected component. This option has no effect if the
component is already visible.
• Hide This — Disable visualization for the selected component. This option has no effect if the
component is already hidden.
• Show Only This — Enable visualization for the selected component and disable visualization for
the remainder of the model. This option has no effect if the selected component is already the only
component visible.
• Show Everything — Enable visualization for every component in the model. This option has no
effect if every component in the model is already visible.
Frames, joints, constraints, forces, and torques have no solid geometry to visualize and therefore
cannot be filtered in Mechanics Explorer. You can still open the visualization filtering context-
sensitive menu by right-clicking these nodes, but only one option is active—Show Everything.
The tree-view pane identifies any node not being visualized by graying out its name. This includes
nodes that can be visualized but are currently hidden and nodes that cannot be visualized at all. The
figure shows an example with the grayed-out names of nodes not being visualized.
5-16
Selective Model Visualization
The figure shows portion of the tree-view pane of the TranslationalInterfaceExample featured
example. The Half_Cylinder_A node is a child to the Housing_and_Cylinder_Assembly node and a
parent to the Fins and Half_Annular_Cylinder nodes.
5-17
5 Visualization and Animation
If you want to show part of a subsystem you have previously hidden, you can change the visibility
settings for the children nodes that you want to show. For example, if after hiding the Half_Cylinder_A
node, you want to show the Fins child node, you need only right-click the Fins node and select Show
This. Such changes have no effect on the remainder of the Half_Cylinder_A parent node.
• If the model remains unchanged, the node visibility settings remain unchanged—that is, the
hidden nodes remain hidden and the visible nodes remain visible. This happens even if you save
the Mechanics Explorer configuration to the model by clicking the icon.
• If you close Mechanics Explorer before updating the model, Mechanics Explorer reopens with all
nodes visible, including any nodes you may have previously hidden.
• If you change the name of a block corresponding to a hidden node—e.g., a Solid block or a
Subsystem block containing a Solid block—the hidden node and any children nodes it may have
become visible.
• If you uncomment a block that corresponds to a hidden node and that you had previously
commented out, the hidden node and any children nodes it may have become visible.
• If you add to a hidden Subsystem block a Solid block or another Subsystem block with a Solid
block, the child node corresponding to the new block becomes visible upon model update but the
visibility of the hidden parent node remains unchanged.
• If you change the parameters of a block corresponding to a hidden node, that node and its
children nodes retain their original visibility settings—that is, hidden nodes remain hidden and
visible nodes remain visible.
5-18
Selective Model Visualization
• Lowering the opacity of obstructive components—those obscuring other parts of the model—for
example, making the cylinder encasing an engine piston transparent.
• Modeling obstructive components only in part—for example, treating engine cylinders as half-
cylinders to preserve piston visibility during simulation.
• Omitting obstructive components altogether if they serve a purely aesthetic purpose and have no
impact on model dynamics—for example, removing the cylinder subsystems from the
TranslationalInterfaceExample featured example.
• Commenting out or through obstructive components if they serve a purely aesthetic purpose and
have no impact on model dynamics—for example, removing the cylinder subsystems from the
TranslationalInterfaceExample featured example.
5-19
5 Visualization and Animation
Visualization filtering is a Mechanics Explorer feature that enables you to selectively show and hide
solids, bodies, and multibody subsystems. This tutorial shows you how to use this feature to control
the visualization of a Simscape Multibody model, for example, to observe a model component that
might otherwise remain obstructed during simulation. For more information, see “Selective Model
Visualization” on page 5-15.
5-20
Selectively Show and Hide Model Components
the left side of Mechanics Explorer. You access the visualization filtering menu by right-clicking a
node on this pane.
5-21
5 Visualization and Animation
node name is no longer grayed out in the tree-view pane. The figure shows the resulting model
visualization.
Show Everything
In the tree-view pane, right-click any node and select Show Everything. All hidden components
become visible. The corresponding nodes are no longer grayed out in the tree-view pane. The figure
shows the resulting model visualization.
5-22
Selectively Show and Hide Model Components
See Also
More About
• “Selective Model Visualization” on page 5-15
• “Translational Interface: Radial Engine with Gas Force Model” on page 8-42
5-23
5 Visualization and Animation
Simscape Multibody models are based on frames, abstract axis triads that contain all the position and
orientation data in a model. These constructs enable you to connect solids into bodies, assemble
bodies into mechanisms, and prescribe and sense forces, torques, and motion. Given their
importance, then, it makes sense to visualize where and how you place different frames in a model.
Alternatively, you can select View > Show Frames in the menu bar. Mechanics Explorer shows all
the frames in your model, suiting this approach well for models with small numbers of frames. The
figure shows a radial engine model with frame visibility toggled on.
If your model has many frames, a different approach may be ideal, as toggling frame visibility may
clutter the visualization pane with frames that you don’t want to track.
5-24
Visualize Simscape Multibody Frames
using a turquoise color. The following figure shows an example in which one of the connecting rod
assemblies in the radial engine model is highlighted in turquoise.
You can also select individual port frames, which you expose by expanding the tree nodes. For
example, expanding the Piston_Connecting_Rod_Assembly_A node exposes the port frame P node,
which you can then select in order to highlight that frame. The figure shows the result.
Finally, you can select individual solids directly in the visualization pane, highlighting their reference
frames. The figure shows the result of selecting one of the piston solids directly. Mechanics Explorer
highlights the solid and its reference frame, while the tree view pane reveals the associated Solid
block name. This is the block that you need to change if you want to modify this particular solid.
5-25
5 Visualization and Animation
5-26
Go to a Block from Mechanics Explorer
To help you troubleshoot such modeling issues, Mechanics Explorer enables you to go directly to a
block associated with a node in the tree view pane. This feature helps you also to iterate on a model
that is working properly, for example, if you want to replace a body subsystem with an alternative
version.
1 In the tree view pane of Mechanics Explorer, right-click the node whose block you want to
examine.
2 From the context-sensitive menu, select Go to Block. Simscape Multibody brings the block
diagram to the front and highlights the block corresponding to the selected node.
For an example showing how to troubleshoot a model using Mechanics Explorer block highlighting,
see “Troubleshoot an Assembly Error” on page 2-21.
5-27
5 Visualization and Animation
You can create a model animation video interactively, using the Video Creator tool, or
programmatically, using the smwritevideo function. The tool and function provide equivalent ways
to perform the same task. Use the tool to more intuitively configure and create a video. Use the
function for your command-line workflows, e.g., to automate video capture following model
simulation.
• Mechanics Explorer must be set to open on model update. You can view and change the current
setting in the Simscape Multibody > Visualization tab of the Model Configuration Parameters
window.
• Only the active visualization tile in Mechanics Explorer is recorded. A visualization tile is a
subdivision of the Mechanics Explorer visualization pane that shows a specific view of the model.
The active tile is demarcated by a colored bounding box.
• The video viewpoint is always that of the active tile. To change the model viewpoint in the
recorded video, you must change the viewpoint of the active tile. Use a dynamic camera for a
moving point or the global camera for a static viewpoint.
1 Simulate the model to record. Animations and the videos generated from them are based on your
model simulation data.
2 In Mechanics Explorer, select Tools > Video Creator. Video Creator relies on your model
visualization and is accessible through Mechanics Explorer only.
3 In Video Creator, specify the desired video parameters. Video parameters that you can modify
include the video frame rate, frame size, playback speed ratio, and video file format.
4 Click the Create button. Video Creator generates a model animation video and saves it with the
specified name in the specified folder.
5 Save the model animation video in a folder for which you have write privileges.
• In this section, we use the dump trailer model as an example. Simulate the model to record.
openExample('sm/CreateModelAnimationVideoExample')
modelName = 'HydraulicInterface'
sim(modelName)
• Define any video parameters that deviate from your current Video Creator settings. E.g.,
videoName = 'DumpTrailerAnimation'
• In the absence of a path, the function saves the video in the current folder. You must have write
privileges to the folder in order to save the video.
5-28
Create a Model Animation Video
• Call the smwritevideo function with the video name and parameters as function arguments.
smwritevideo(modelName,videoName,...
'PlaybackSpeedRatio',speedRatio,'FrameRate',fps)
The smwritevideo function creates a video of the model animation and saves it with the name
DumpTrailerAnimation in the current folder.
See Also
Related Examples
• “Hydraulic Interface - Dump Trailer with Hydraulic Cylinder” on page 8-43
5-29
Multibody Model Import
31
6
You can create a Simscape Multibody model by using a CAD assembly created by applications, such
as Onshape®, Autodesk® Inventor®, PTC® Creo™, or SolidWorks®. The conversion has two steps.
First, the export step converts a CAD assembly into an XML file and a set of geometry files, and then
the import step creates an equivalent Simscape Multibody model by using the exported files. The
import step also generates an M-file that contains the data to specify all the blocks in the model.
You can also use the smexportonshape function to export a CAD assembly from Onshape. For more
information on exporting CAD models from Onshape, see “Onshape Import” on page 6-14.
If the CAD assembly is created by other CAD applications, to generate the multibody description and
part geometry files, you can create a program that uses the CAD API and Simscape Multibody XML
schema. This task requires knowledge of XML documents, XSD schema definitions, and CAD APIs.
For the XSD schema definitions, see the schema website. For an example program built on the
SolidWorks CAD API, see MATLAB Central.
You may be able to export a CAD assembly in URDF format and use the URDF file to create the
equivalent Simscape Multibody model if your CAD application has a URDF converter. Note, however,
that the URDF specification forbids closed-chain model topologies, such as four-bar linkages and gear
assemblies. For more information, see “Import URDF Models” on page 6-30.
If the Simscape Multibody Link plug-in cannot export a part geometry file or translate a CAD
constraint set, the software returns an error message. The error message identifies the bodies with
missing geometry files and any unsupported constraints. You can still import the generated XML
multibody description file into Simscape Multibody, but the resulting model may not accurately
represent the original CAD assembly.
6-2
Convert CAD Assembly into Simscape Multibody Model
Import a Model
You can create an equivalent Simscape Multibody model by using the smimport function with the
files generated in the export step. The function parses the XML file, extracts the necessary data, and
reconstructs the assembly in the Simscape Multibody environment by using Simscape Multibody
blocks for the CAD assembly's bodies, constraints, and joints. For step-by-step instructions on how to
import a CAD assembly model via its XML file, see “Import a CAD Assembly Model” on page 6-11.
By default, the created model preserves the structural hierarchy of the source CAD assembly. If the
CAD assembly has subassemblies and parts, the smimport function converts them into Simscape
Multibody subsystems. For instance, in the “Import a CAD Assembly Model” on page 6-11 example,
the grip subassembly has seven parts.
After the conversion, the grip contains seven subsystems that represent the corresponding parts.
6-3
6 CAD and URDF Model Import
To represent the parts of a CAD assembly, the smimport function uses the Simscape Multibody solid
blocks to specify the geometries, inertias, and colors of bodies and uses Rigid Transform blocks to
specify the locations and orientations. For example, the figure shows the upper arm of a robotic
assembly.
The converted model consists of one solid block connected to a pair of Rigid Transform blocks. The
solid block models the geometry and inertial properties of the arm, and the Rigid Transform blocks
specify the location and orientation of the arm with respect to the base and lower arm bodies.
6-4
Convert CAD Assembly into Simscape Multibody Model
If an exported geometry file is invalid or missing, after the conversion, the corresponding body does
not display in the Simscape Multibody visualization utility.
During the conversion, the smimport function converts the joints, constraints, and mates of the CAD
assembly into combinations of Simscape Multibody joint and constraint blocks. For instance, in the
robotic arm example, the constraints between the upper and lower arms are converted into a
Revolute Joint block. This joint block connects the subsystems that represent the upper and lower
arms.
Warning: The set of constraints between the Upper Arm Part and Lower Arm Part
could not be mapped to a joint. A rigid connection has been added between port F
of the Upper Arm Part and port F1 of the Lower Arm Part for these constraints.
6-5
6 CAD and URDF Model Import
The rigid connection can take the form of a direct frame connection line, Rigid Transform block, or
Weld Joint block.
Block Data
During the conversion, the smimport function generates an M-file that stores the data of all the
blocks in the Simscape Multibody model. The block data is parameterized in terms of MATLAB
variables. These variables are stored in structure arrays named after the block types. The structure
arrays are nested in a parent data structure named smiData or a custom string that you specify.
Consider a converted model with a data structure named smiData. If the model contains Revolute
Joint blocks, the parameter data for these blocks is the structure array smiData.RevoluteJoint.
This structure array contains a number of data fields, each corresponding to a different block
parameter.
The structure array fields are named after the block parameters. For example, the position state
target data for the Revolute Joint blocks is in a field named Rz_Position_Target. If the model has
two Revolute Joint blocks, this field contains two entries—
smiData.RevoluteJoint(1).Rz_Position_Target and
smiData.RevoluteJoint(2).Rz_Position_target.
Each structure array index corresponds to a specific block in the converted model. The index
assignments can change if you regenerate an M-file from an updated XML multibody description file.
The smimport function checks the prior data file, when specified, to ensure the index assignments
remain the same. See “Update Converted Model” on page 6-6.
To reflect the changes of the source CAD assembly, you can use the smimport with
ImportMode=modelAndDataFile or ImportMode=dataFile argument. When using the
ImportMode=modelAndDataFile argument, the smimport function updates both the converted
model and M-File.
When using the ImportMode=dataFile argument, the smimport function updates only the M-file.
The smimport function uses the prior M-file to keep the mapping between structure array indices
and blocks consistent. The function does not update the block diagram. If you add or delete bodies in
the source CAD assembly, you must manually add or delete the corresponding blocks in the
previously converted multibody model. Before regenerating an M-file, you must export a new XML
multibody description file from the updated CAD assembly. The smimport function uses the data in
the new XML file to generate the new M-file.
6-6
Convert CAD Assembly into Simscape Multibody Model
You can simplify the topology of the converted model by using the ModelSimplification argument
of the smimport function. You can set this argument to:
• Use bringJointsToTop to group each set of rigidly connected parts into a new subsystem and
promote all joints to the top level of the model hierarchy.
• Use groupRigidBodies to group rigidly connected parts into subsystems (and leave joints in
their original places in the model hierarchy).
• Use None to import the model as is, without simplification.
Use bringJointsToTop or groupRigidBodies if the source CAD assembly has many rigidly
connected components, such as nuts and bolts, that you prefer to group together, to more intuitively
grasp the key components of the model at a glance of the block diagram.
Use bringJointsToTop if the source CAD assembly has joints inside subassemblies and you prefer
to expose them at the top level, to work with joint actuations and sensing signals without having to
search for the joints inside different subsystems.
Note that model simplification is available only for CAD assemblies. URDF models have flat topologies
with little need for simplification.
See Also
More About
• smexportonshape
• smimport
6-7
6 CAD and URDF Model Import
In this section...
“Software Requirements” on page 6-8
“Step 1: Get the Installation Files” on page 6-8
“Step 2: Run the Installation Function” on page 6-9
“Step 3: Register MATLAB as an Automation Server” on page 6-9
“Step 4: Enable the Simscape Multibody Link Plugin in a CAD Application” on page 6-9
“Importing CAD Files from Applications Not Supported by Simscape Multibody Link” on page 6-9
Simscape Multibody Link is a plugin that you can install on CAD applications to export assembly
models to Simscape Multibody. Specifically, the plugin exports a CAD assembly model as an XML file
and body geometry files that you can convert into Simscape Multibody models using the smimport
function. The plugin supports:
• SolidWorks
• Autodesk Inventor®
• PTCCreo
Software Requirements
Make sure your software meets the requirements:
Your MATLAB and CAD installations must have the same system architecture, such as Windows 64-
bit. To ensure the successful installation of Simscape Multibody Link, you must complete steps 3 and
4 prior to launching the CAD applications.
6-8
Install the Simscape Multibody Link Plugin
• Open a MATLAB session in administrator mode. At the MATLAB command prompt, enter
regmatlabserver.
• Open a Windows® command prompt window running in administrator mode. At the command
prompt, enter matlab -regserver.
See Also
smexportonshape | smimport
More About
• “Import URDF Models” on page 6-30
6-9
6 CAD and URDF Model Import
6-10
Import a CAD Assembly Model
You import a CAD assembly model into Simscape™ Multibody™ software using the smimport
function. The function parses an XML multibody description file and automatically generates the
corresponding model. Geometry files accompanying the multibody description file format provide the
body geometries for visualization purposes.
This example shows how to generate a robot model from a XML file using the smimport function.
The example is based on the Robot.xml and a set of part geometry files.
To use the XML and geometry files, open this example, and then add the supporting files to the
search path for the current MATLAB® session:
addpath(genpath("ImportedCADModelSupport"))
Import a CAD model of a robotic arm and store it in memory as the default name. You can change the
name later. As the model is in XML format, you can omit the extension in its name.
smimport("Robot");
Simscape Multibody generates the model described in the Robot.xml file using the default
smimport function settings.
6-11
6 CAD and URDF Model Import
The blocks in the generated model are parameterized in terms of MATLAB variables. The numerical
values of these variables are defined in a data file that is named Robot_DataFile.m and stored in
the same active folder as the generated model.
Alternatively, you can import the CAD model of the robotic arm and save it in the current folder with
a custom name. Name the model as Robotto and the parameter data file as Robottos_Data_File.
smimport("Robot","ModelName","Robotto",...
"DataFileName","Robottos_Data_File");
Regenerate the data file for the imported CAD model of the robotic arm. To avoid overwriting the
original data file, name the new file Robottos_New_Data_File.
smimport("Robot","ImportMode","dataFile","DataFileName",...
"Robottos_New_Data_File","PriorDataFile","Robottos_Data_File");
Point the imported model to the new data file and reinitialize the model workspace.
hws = get_param(bdroot,"modelworkspace");
hws.DataSource = "MATLAB File";
hws.FileName = "Robottos_New_Data_File";
hws.reload
To do the same using Model Explorer, first, select Modeling > Design > Model Workspace to open
the Model Explorer. Next, in the Model Hierarchy of the Model Explorer, left click Model
Workspace. In the Model Workspace pane, enter Robottos_New_Data_File.m in the File Name
parameter and click Reinitialize from Source button to apply the change.
Update the diagram to visualize the model. In the Modeling tab, click Update Model. Mechanics
Explorer opens with a static visualization of the robotic arm model in its initial configuration.
The default view convention in Mechanics Explorer differs from that in the CAD application used to
create the original assembly model. Mechanics Explorer uses a Z-axis-up view convention while the
CAD application uses a Y-axis-up view convention.
Change the view convention from the Mechanics Explorer toolstrip by setting the View convention
parameter to Y up (XY Front). Then, select a standard view from the View > Standard Views
menu to apply the new view convention.
6-12
Import a CAD Assembly Model
Check the imported model for unexpected rigid connections between bodies. Simscape Multibody
software replaces unsupported CAD constraints with rigid connections that may appear as direct
frame connection lines, Rigid Transform blocks, or Weld Joint blocks.
A warning message in the MATLAB command window identifies the bodies and connection frames
affected by the unsupported constraints. Replace the artificial rigid connections between the bodies
with suitable Joint, Constraint, or Gear blocks from the Simscape Multibody library.
Update the block diagram to rule out model assembly errors. Run simulation to ensure the model
dynamics are as expected. If you update the source CAD assembly model, you can generate an
updated data file directly from a new multibody description file.
Try to simulate the model. Because the robotic arm lacks a control system, it simply flails under
gravity. You can use Simulink® blocks to create the control system needed to guide the robotic arm
motion. A control system would convert motion sensing outputs into actuation inputs at the various
joints. You can expose the sensing and actuation ports from the joint block dialog boxes.
See Also
smimport
Related Examples
• “Four Bar Mechanism Imported from a CAD Assembly” on page 8-47
• “Humanoid Robot” on page 8-50
• “Modeling a Robot Using STEP Files” on page 8-48
• “Stewart Platform with Controller” on page 8-45
6-13
6 CAD and URDF Model Import
Onshape Import
In this section...
“Onshape Model” on page 6-14
“Preparing a Model for Import” on page 6-14
“Importing an Onshape Model” on page 6-15
“What Can You Import?” on page 6-16
“User Authentication and Account Permissions” on page 6-16
“Mapping to Simscape Multibody Blocks” on page 6-16
“Onshape Import Warnings and Errors” on page 6-17
“Physical Units” on page 6-17
“Obtaining Onshape Models to Import” on page 6-17
Onshape is a third-party CAD application that you can import multibody models from. As with other
CAD applications, you use Onshape software to model 3-D parts and articulated assemblies. Onshape
is full-cloud software and does not rely on a local installation to run.
You must have an active Onshape account to use the software. The Simscape Multibody
smexportonshape function replaces the Simscape Multibody Link plug-in as the CAD export means.
The plug-in is incompatible with Onshape and cannot be used with Onshape models.
Onshape Model
Onshape models are similar in composition to other multibody models. Parts connect through mates
such as Ball, Slider, and Revolute to form articulated linkages, mechanisms, and machines. The
models are hierarchical, with parts and mates nested inside subassemblies that can in turn be nested
inside larger subassemblies.
Each Onshape model exists in a cloud document. A document can have multiple Part Studio tabs, for
modeling parts, and Assembly tabs, for mating parts. A Part Studio tab can have multiple parts and
these can be modeled in the relative poses anticipated in the final assembly—for example, to form
rigid groups during assembly without the aid of Fixed mates.
Rigid groups are unique to Onshape models and map into Simulink Subsystem blocks with rigidly
connected bodies enclosed.
Onshape and Simscape Multibody models have different standard terms for what are often the same
things. Parts in an Onshape model are bodies in a Simscape Multibody model. Mates and relations in
an Onshape model are joints and constraints in a Simscape Multibody model. These terms are used
interchangeably here.
6-14
Onshape Import
Ensure that your Onshape parts are free of geometry errors and that your mates have been fully
defined. If no mate exists between two parts—that is, if they have six relative degrees of freedom—
the imported model will show a 6-DOF Joint block between the corresponding body subsystems. Fix at
least one part at the root assembly level to prevent such a block from being added between the
assembly and the World frame.
The XML file provides the smimport function the data it needs in order to recreate the Onshape
model in the Simscape Multibody environment. This file is referred to as the multibody description
file and is required for model import.
The STEP files provide the imported model, once generated, the 3-D geometries it needs in order to
render the bodies in the visualization panes of solid blocks and Mechanics Explorer. The files are
referred to as geometry files and are optional for model import.
The geometry files are referenced in the solid blocks of the imported model. If the geometry files are
missing, or if the paths to the files change, the body geometries no longer show in the visualization
panes of the solid blocks and Mechanics Explorer. Simulation is unaffected provided that the model is
otherwise still valid.
The remaining block parameters are specified in terms of MATLAB variables defined in the
supporting data file generated by the smimport function. The variables are stored in a single data
structure, with the data field names and indices identifying the block parameters that the variables
correspond to—e.g., smiData.Solid(2).mass.
6-15
6 CAD and URDF Model Import
You can export part geometries directly from an Onshape document using the Onshape Export
feature. This feature enables you to save geometries in various formats, but only two are compatible
with Simscape Multibody models—STL and STEP. Once exported, the geometries can be individually
imported into Simscape Multibody solid blocks. See “Try It: Import a STEP Geometry File” on page 1-
41.
Authentication occurs once per MATLAB session and is based on a protocol known as OAuth2. So that
you can validate your account, the smexportonshape function automatically opens an Onshape log-
in page on your first export attempt of a session.
You need give the Simscape Multibody Exporter app access permissions only once until these are
revoked. So that you can set the permissions for the app, the smexportonshape function
automatically opens an Onshape application authorization page on your first-ever export attempt.
You can revoke permissions at any time from the Onshape Applications page.
OAuth2 is an authentication protocol that delegates the authentication process to the service hosting
the account—in this case, Onshape. The oauth.net website describes the protocol as a valet key that
gives third-party applications such as Simscape Multibody access to some, but not all, aspects of your
account. In particular, Simscape Multibody can access your app permissions data, but it cannot see or
store your private log-in credentials.
6-16
Onshape Import
Onshape relations such as Gear and Linear are not supported. All relations in your model are ignored
during import. You can often model the ignored relations using Simscape Multibody blocks—for
example, using the Common Gear Constraint block to model a Gear relation between two gears. You
may need to create and carefully place new frames before adding such blocks.
The smexportonshape function expects the URL of an Onshape Assembly tab as an argument. An
Onshape document often comprises Part Studio, Drawing, and other tabs. If you inadvertently specify
the URL for the wrong document tab—one not containing an assembly—the function throws an error.
Zero-Mass Bodies
Onshape parts without assigned material translate into Simscape Multibody bodies with zero inertia.
Such massless bodies can cause simulation to fail due to degenerate mass errors. A MATLAB warning
identifies all massless bodies identified in your model, if any. You can manually specify the mass of a
massless body after import using the Brick Solid block for that body. However, as a best practice,
always try to assign a material to each body in an assembly before exporting it.
Onshape mates such as Tangent and relations such as Gear are not supported. The
smexportonshape function throws a warning identifying all unsupported mates and relations, if any.
Unsupported mates map into nothing in a Simscape Multibody model. For a list of Onshape mates
that you can import, see “Mapping to Simscape Multibody Blocks” on page 6-16.
Physical Units
The block parameters in the imported model are in the default units of the Onshape model
workspace. These units often include a mix derived from SI, CGS, and other unit systems. You can
change the units for an entire model in your Onshape model workspace and for an individual block in
your imported Simscape Multibody model.
See Also
smexportonshape | smimport
6-17
6 CAD and URDF Model Import
More About
• “Import an Onshape Humanoid Model” on page 6-19
• “Convert CAD Assembly into Simscape Multibody Model” on page 6-2
• “Import URDF Models” on page 6-30
6-18
Import an Onshape Humanoid Model
You can import a CAD assembly model from Onshape software into the Simscape Multibody
environment. The import process occurs in two steps based on the smexportonshape and
smimport functions. The smexportonshape exports the assembly model in an intermediate XML
conforming to the Simscape Multibody XML schema. The smimport function converts the
intermediate XML file into a Simscape Multibody version of the original Onshape model.
Example Overview
This example shows how to import an Onshape model of a humanoid robot assembly. The model
comprises various parts representing the torso, head, and limbs of the robot. The parts connect
through Revolute mates that represent the various joints. The model is identical to that shown in
“Import a URDF Humanoid Model” on page 6-37. Enter the following URL in your web browser to
access the model (Onshape login required):
https://cad.onshape.com/documents/5817806f96eae5105bfa5085/w/15ab3bfb58cacbf427d77ff3/e/181493813f84966648a8db1b
Model Schematic
1 At the MATLAB command prompt, navigate to a folder for which you have write privileges—for
example:
cd C:\Users\JDoe\Documents\Models
2 Store the model URL in a MATLAB variable named assemblyURL:
6-19
6 CAD and URDF Model Import
assemblyURL = "https://cad.onshape.com/documents/5817806f96eae5105bfa5085/w/15ab3bfb58cacbf42
3 Export the model and save the XML file name in a variable named exportedModel:
exportedModel = smexportonshape(assemblyURL);
You may be prompted to log in to your Onshape account. The smexportonshape function
generates the XML multibody description file for this model and a set of STEP files for the
various part geometries.
Build on the model, for example, by adding control systems to actuate the various joints. For a
controlled example, at the MATLAB command prompt enter OpenExample('sm/
ImportedURDFExample'). Simulate the model to view a simple animation.
6-20
Import an Onshape Humanoid Model
See Also
smexportonshape | smimport
More About
• “Onshape Import” on page 6-14
• “Convert CAD Assembly into Simscape Multibody Model” on page 6-2
• “Import URDF Models” on page 6-30
6-21
6 CAD and URDF Model Import
URDF Primer
In this section...
“URDF Elements and Attributes” on page 6-22
“XML Hierarchies and Kinematic Trees” on page 6-23
“Required and Optional URDF Entities” on page 6-25
“Create a Simple URDF Model” on page 6-26
“Obtaining URDF Models to Import” on page 6-28
Unified Robotics Description Format, URDF, is an XML specification used in academia and industry to
model multibody systems such as robotic manipulator arms for manufacturing assembly lines and
animatronic robots for amusement parks. URDF is especially popular with users of Robotics
Operating System, ROS. You can import URDF models into the Simscape Multibody environment to
create a multibody dynamics model for simulation, analysis, or control design tasks. See the
“Humanoid Robot” on page 8-50 featured example for a simple use case.
<robot>
<link>
...
</link>
<link>
...
</link>
<joint>
...
</joint>
</robot>
6-22
URDF Primer
Child elements, such as <link> and <joint> under <robot>, can in turn have child elements of
their own. For example, the <link> element has the child elements <inertial> and <visual>. The
<visual> element has the child elements <geometry> and <material>. And the <material>
element has the child element <color>. Such chains of child elements are essential to define the
properties and behavior of the parent elements.
<robot>
<link>
<inertial>
...
</inertial>
<visual>
<geometry>
...
</geometry>
<material>
<color />
</material>
</visual>
</link>
...
</robot>
In addition to child elements, the XML elements in a URDF model can have attributes. For example,
the <robot>, <link>, and <joint> elements all have the attribute <name>—a string that serves to
identify the element. The <color> element has the attribute rgba—a numeric array with the red,
green, blue, and alpha (or opacity) values of the link color. Attributes such as these help to completely
define the elements in the model.
6-23
6 CAD and URDF Model Import
You can visualize the connections between links using a schematic known as a connectivity graph.
The figure shows an example. Circles denote links and arrows denote joints. The arrow roots identify
the parent nodes and the arrow tips the child nodes. The connectivity graph reveals the topology of
the underlying model—here a simple kinematic tree with two branches.
Model topology is important in URDF. The connectivity graph of a model can take the shape only of a
kinematic tree—a kinematic chain, branched or unbranched, that is always open. Kinematic loops,
each a closed chain formed by joining the ends of an otherwise open chain, are disallowed. This
restriction impacts how <link> elements can connect in a URDF model.
The restriction translates to the following rule: no <link> element can serve as a child node in more
than one <joint> element. Put another way, no <link> element can have more than one parent
element in the model’s connectivity graph. Only the root link, that at the origin of the connectivity
graph, can have a number of parent nodes different from one (zero). Only one root link is allowed in a
model.
6-24
URDF Primer
The code declares a link, link D, as a child node in two <joint> elements, joint C and joint D.
The link D element has two parents and forms a kinematic loop. The model violates the URDF
connection rules and is invalid. The figure shows the connectivity graph of the model.
Elements and attributes shown as required inside optional elements are so only if the optional
elements are used. The default values of optional attributes are shown in parentheses and in italic
font. Note that this code is included only as a reference and that it does not represent a valid URDF
model. Ellipses (“...”) are invalid in URDF models and are used merely to break long lines of code for
ease of viewing.
<robot name>
<link name>
<inertial>
<origin xyz("0 0 0") rpy("0 0 0") />
<mass value />
6-25
6 CAD and URDF Model Import
6-26
URDF Primer
</inertial>
<visual>
<origin xyz = "0 0 0" />
<geometry>
<box size = "0.5 0.5 0.1" />
</geometry>
<material name = "gray A">
<color rgba = "0.1 0.1 0.1 1" />
</material>
</visual>
</link>
<link name = "link B">
<inertial>
<origin xyz = "0 0 -0.5" />
<mass value = "0.5" />
<inertia ixx = "0.5" iyy = "0.5" izz = "0.5"
ixy = "0" ixz = "0" iyz = "0" />
</inertial>
<visual>
<origin xyz = "0 0 -0.5" />
<geometry>
<cylinder radius = "0.05" length = "1" />
</geometry>
<material name = "gray B">
<color rgba = "0.3 0.3 0.3 1" />
</material>
</visual>
</link>
<link name = "link C">
<inertial>
<origin xyz = "0 0 -0.5" />
<mass value = "0.5" />
<inertia ixx = "0.5" iyy = "0.5" izz = "0.5"
ixy = "0" ixz = "0" iyz = "0" />
</inertial>
<visual>
<origin xyz = "0 0 -0.5" />
<geometry>
<cylinder radius = "0.05" length = "1" />
</geometry>
<material name = "gray C">
<color rgba = "0.5 0.5 0.5 1" />
</material>
</visual>
</link>
6-27
6 CAD and URDF Model Import
The code defines a multibody model named linkage. The model contains three links, named link
A, link B and link C, that connect via two joints, named joint A and joint B. The <parent>
and <child> elements of the joints identify how the links connect to each other: link A connects to
link B and link B connects to link C. link A has no parent link—that is, it appears in <joint>
elements as a child element only—and is therefore the root link.
The <inertial> element of link A defines the mass and moments of inertia (ixx, iyy, izz) of the
link. The products of inertia (ixy, ixz, and iyz) are unspecified and have the URDF default value of
zero. The visual element of link A defines the geometry type and material color for use in the
model visualization. The geometry in this case is a box with width and thickness of 0.5 m and height
of 0.1 m. The <origin> elements of the link <inertial> and <visual> specify the transforms
from the link reference frame to the inertial and visual reference frames. Similar elements apply to
link B and link C.
The type attribute of the <joint> elements defines the joints as continuous—a type of revolute joint
without motion limits. The <origin> element specifies the location of the joint relative to the
reference frame of the parent link element. For example, the <origin> element of joint A offsets
the joint 0.05 m along the -Z axis relative to the origin of the link A reference frame. The axis
element nested inside each joint element defines the rotational axis of the joint as the Cartesian
vector [0, 1, 0], or +Y.
The figure shows the components of the model—the links and joints—and the various frames they
contain. R denotes a link reference frame, I a link inertial frame, and V a link visual frame. J denotes
a joint reference frame—by definition held coincident with the reference frame of the child link. The
inertial and visual frames are offset to the centers of the links and the joint frames to their lower
edges.
6-28
URDF Primer
consultants often provide URDF models for their robotic systems. CAD applications such as
SolidWorks and PTC Creo support URDF exporters that convert your CAD assemblies into URDF
models. Consider these options when working with complex robotics models that may not be simple
to create manually.
See Also
smimport
More About
• “Import URDF Models” on page 6-30
• “Convert CAD Assembly into Simscape Multibody Model” on page 6-2
• “Multibody Modeling”
6-29
6 CAD and URDF Model Import
To import a URDF model into a Simscape Multibody model, use the smimport function. You must
specify the file extension.
smimport('Humanoid.urdf')
If you omit the file extension, the smimport function assumes that the file is in the XML format used
to import CAD models. For example, the command
smimport('Humanoid')
tells the function to create a multibody model from the Humanoid XML file. If the function finds no
XML file with the specified name, it returns an error even if there is a URDF file with the same name
in the same folder. For more information about how to import a URDF model, see “Import a URDF
Humanoid Model” on page 6-37.
6-30
Import URDF Models
</geometry>
</collision>
</link>
<joint name type>
<origin xyz rpy />
<parent link />
<child link />
<axis xyz />
<calibration rising />
<calibration falling />
<dynamics damping friction />
<limit lower upper effort velocity />
<mimic joint multiplier offset />
<safety_controller soft_lower_limit ...
... soft_upper_limit k_position k_velocity />
</joint>
</robot>
Elements are in bold font and attributes are in regular font. Unsupported elements and attributes are
highlighted in red. The smimport function does not support an element or attribute if the element or
attribute is not shown in the above example. Note that the scale attribute of the <visual>/
<geometry>/<mesh> element is shown in orange because the attribute is partially supported. For
more information about the scale attribute, see the “Mesh Geometries” on page 6-32 section.
The Subsystem blocks comprise solid, Inertia, Rigid Transform, and Reference Frame blocks. The
solid blocks provide the geometries and colors of the body; these blocks correspond to the <visual>
tags of the URDF model and are named Visual. The Inertia block provides the mass, center of mass,
moments of inertia, and products of inertia of the body; this block corresponds to the <inertial>
element of the URDF model and it is named Inertia.
The Rigid Transform blocks provide the translational and rotational offsets from the local reference
frame of the body to the Inertial and Visual elements. These transforms are derived from the
<origin> elements of the <inertial> and <visual> elements of links, as well as from the
<origin> and <axis> elements of joints. The Reference Frame block identifies the local reference
frame of the body.
The type of joint block used depends on the <type> attribute of the <joint> element. The joint
mapping between URDF and Simscape Multibody software is largely intuitive. A <joint> element of
type prismatic maps into a Prismatic Joint block. A <joint> element of type fixed maps into a Weld
Joint block. The table shows the mappings for the remaining URDF <joint> elements.
6-31
6 CAD and URDF Model Import
Mesh Geometries
To specify the visual geometries of a URDF model by using external geometry files, use the <mesh>
element, for example:
<link name="link_1.3">
<visual>
<origin rpy="0 -1.57079632679 0" xyz="0 0 0.0425"/>
<geometry>
<mesh filename="package://xela_models/mesh_simplified/finger_link_3.stl" scale="0.001 0.00
</geometry>
</visual>
</link>
The geometry files are not a part of the URDF file, and you must save the geometry files in the same
folder as the corresponding URDF file. The geometry files must be in STL or STEP format. Note that
the smimport function does not support Collada (DAE) files. If you import a model with references to
DAE files, the Simscape Multibody model does not render the geometries derived from these files.
The lack of visualization may limit your ability to analyze the model but has no impact on the model
dynamics.
When you import a URDF model whose visual geometries refer to external files, the vertex data in the
files remain unscaled regardless of the value of the scale attribute. The scale attribute specifies
the units for the vertex data in the converted File Solid blocks.
To specify the units to cm, set the x, y, and z-axis scale factors of the scale attribute to 0.01. To
specify the units as mm, set all three factors to 0.001. Note that all three factors must have the same
value, and you must specify the value as either 0.01 or 0.001. If the values do not meet these
conditions, the smimport function specifies the units to meter.
Physical Units
In the converted Simscape Multibody model, the block parameters use the International System of
Unit, SI.
6-32
Import URDF Models
The smimport function does not support the elements and attributes derived from URDF extensions,
such as <transmission>, <gazebo>, <model_state>, and <sensor> elements.
• CAD models are imported in an intermediate XML format. URDF models are imported directly in
URDF format.
The intermediate XML files provide the information needed to recreate the CAD models in the
Simscape Multibody environment. The same information is provided directly in URDF files when
importing URDF models. XML multibody description files must conform to the Simscape
Multibody XML schema. See “Export a CAD Assembly” on page 6-2 for ways to generate a valid
XML file.
• Imported CAD models have their numerical parameters defined in MATLAB files. Imported URDF
models have their numerical parameters hardcoded into the block dialog boxes.
CAD import uses a detached data framework that places all block parameter values in a cell
structure defined in a separate MATLAB data file. The detached data framework enables you to
update a previously imported model when you modify the source CAD model. URDF import lacks
this feature and does not support model update.
smimport('DoublePendulum.urdf')
If you saved your URDF model under a different name, use that name instead. The function imports
the URDF model and generates an equivalent Simscape Multibody model. The figure shows the
resulting model with the blocks and their connection lines slightly rearranged.
6-33
6 CAD and URDF Model Import
The <link> elements named link A, link B, and link C in the URDF model map into Simulink
Subsystem blocks also named link A, link B, and link C. The <joint> elements named joint
A and joint B—each with type set to continuous—map into Simscape Multibody Revolute Joint
blocks also named joint A and joint B.
The block diagram reflects the topology of the URDF model—an unbranched kinematic tree. link C
connects to link B as a child of that element. link B in turn connects to link A as a child of that
element. link A is the root link and is therefore grounded—a condition reflected in the rigid
connection between the link A and World Frame blocks.
The Subsystem blocks representing the URDF <link> elements each comprise a small block diagram
with one Reference Frame block, one Brick Solid block, one Inertia block, and multiple Rigid
Transform blocks. The Subsystem blocks are not masked and can be opened directly with a double
click. The figure shows the block diagram of the link A Subsystem block.
The Brick Solid block is the translated equivalent of the <visual> URDF element and is named
Visual. This block contains the relevant parameters of the <visual> element, including link
geometry and color. The Inertia block is the translated equivalent of the <inertial> URDF element
and is accordingly named Inertial. This block contains the relevant parameters of the <inertial>
element, including link mass, moments of inertia, and products of inertia.
6-34
Import URDF Models
link A Subsystem
The Reference Frame block identifies the local reference frame of the <link> URDF element. This
frame coincides with the joint connection frame to the parent link or, as in this case of a root link, to
the World Frame block. The Rigid Transform blocks specify the translational and rotational
transforms to the reference frames of the <inertial>, <visual>, and <joint> URDF elements. An
additional Rigid Transform block specifies the rotation transform needed to align the Simscape
Multibody joint axis with the URDF joint axis.
Build on the model to obtain a meaningful simulation. You can, for example, use joint state targets to
assemble the double pendulum in an unstable configuration and simulate its fall under gravity:
1 In the dialog box of the joint_A block, select the State Targets > Specify Position Target check
box and set the Value parameter to 30 deg. This parameter sets the starting angle of the upper
joint.
2 In the Solver pane of the Configuration Parameters window, click Additional options and set
the Max step size parameter to 0.01. This value keeps the solver step size small enough to
produce a smooth animation during simulation. Increase the value if simulation proceeds slowly.
6-35
6 CAD and URDF Model Import
3 Update the block diagram and run the simulation. In the Modeling tab, click Update Model.
You can simulate the model by selecting Run. Mechanics Explorer shows an animation of the
double pendulum fall under gravity.
See Also
smimport
More About
• “Convert CAD Assembly into Simscape Multibody Model” on page 6-2
• “Import a URDF Humanoid Model” on page 6-37
• “URDF Primer” on page 6-22
• URDF specification
6-36
Import a URDF Humanoid Model
You can import a URDF model into the Simscape™ Multibody™ environment. The import process
occurs in a single step based on the smimport function. The smimport function converts the URDF
model directly into an equivalent Simscape Multibody model.
Example Overview
This example shows how to import an Onshape® model of a humanoid robot assembly. The model
comprises various parts (”links” in URDF jargon) representing the torso, head, and limbs of the robot.
The parts connect through revolute and weld joints (”continuous” and “fixed” respectively).
To add the URDF file to the search path for the current MATLAB® session, enter:
openExample("sm/DocImportedURDFModelExample");
addpath(genpath("ImportedURDFSupport"));
smimport("Humanoid.urdf")
The function generates a Simscape Multibody model of the humanoid robot. The file extension is
required to identify the import file as URDF. Update the imported model (in the Modeling tab, click
Update Model.) to open a static visualization in the initial state. The figure shows the results.
6-37
6 CAD and URDF Model Import
Build on the model, for example, by adding control systems to actuate the various joints. For a
controlled example, at the MATLAB command prompt enter:
openExample("sm/ImportedURDFExample")
6-38
Import a URDF Humanoid Model
See Also
smimport
More About
• “URDF Primer” on page 6-22
• “Import URDF Models” on page 6-30
• “Convert CAD Assembly into Simscape Multibody Model” on page 6-2
6-39
Deployment
41
7
Code Generation
7 Code Generation
Simulation Acceleration
Simulink can generate C/C++ executable code to shorten simulation time. Two simulation modes rely
on code generated from a model:
• Accelerator
• Rapid Accelerator
Simscape Multibody supports the two accelerator modes. You can access the simulation accelerator
modes from the Debug tab. Accelerator modes do not require additional Simulink code generation
products.
Note Simulation accelerator modes do not support model visualization. When you simulate a
Simscape Multibody model in Accelerator or Rapid Accelerator modes, Mechanics Explorer
does not open with a 3-D display of your model.
7-2
Code Generation Applications
Model Deployment
With Simulink Coder, you can generate standalone C/C++ code for deployment outside the Simulink
environment. The code replicates the source Simscape Multibody model. You can use the stand-alone
code for applications that include:
Note Simscape Multibody supports, but does not perform, code generation for model deployment.
Code generation for model deployment requires the Simulink Coder product.
See Also
Related Examples
• “Generate Code for a Multibody Model” on page 7-6
7-3
7 Code Generation
Solver Selection
Simscape Multibody models have continuous states and require a continuous or hybrid Simulink
solver. You can change solvers from the Solver pane of the Model Configuration Parameters
window. Select any solver but that marked discrete (no continuous states). Consider the
ODE1 fixed-step solver if you need to approximate the behavior of a discrete solver.
Target Selection
The choice of code generation target depends on the Simulink solver used. If you select a variable-
step solver, you must set rsim.tlc as the system target file. You can specify the system target file
from the Model Configuration Parameters window. Look for the System target file parameter in
the Target selection area of the Code Generation pane.
Run-Time Parameters
You can configure most numerical block parameters as Compile-time (default) or Run-time using a
drop-down list that appears beside configurable parameters. The figure shows the run-time drop-
down list in a solid block dialog box. All parameters are by default Compile-time. The drop-down
list is disabled when the model is in Fast Restart mode.
Compile-time parameters update in value when you recompile the model. Leave parameters as
Compile-time when performing tasks that rely on inlined parameters such as model optimization.
7-4
Code Generation Setup
Run-time parameters update in value without the need for extra compilations. Set parameters to
Run-time when tuning their values in Fast Restart mode or when simulating models that rely at least
in part on generated C code.
To set a parameter as Run-time from the block dialog box, you must configure your Simscape
preferences. Open the MATLAB Preferences window, select the Simscape node, and check the Show
run-time parameter settings check box. Parameters without a run-time option or with a run-time
option that is inactive (i.e., “grayed out”) cannot be configured. The Length parameter in the figure
is an example.
For more information about Simscape run-time parameters, see “About Simscape Run-Time
Parameters”.
Compiler Optimization
You can set your C/C++ compiler to optimize generated code. Optimized code runs faster but
compiles slower. Compilation can be especially slow in large models with many bodies. The choice of
compiler can exacerbate the slow compilation times. With certain versions of Microsoft Visual C++,
Simulink software may appear to hang as the model is compiled.
If a model takes unusually long to compile, consider switching to a different installed compiler or
disabling compiler optimization for your model. The Clang compiler provides a suitable alternative to
Microsoft Visual C++. You can perform both tasks from the Code Generation menu of the Model
Configuration Parameters window.
To switch compilers, in the Toolchain settings area of the Code Generation menu, set the
Toolchain parameter to a different compiler. To disable code optimization, set the Build
configuration parameter to Faster Builds.
7-5
7 Code Generation
MATLAB software opens the four-bar example model. Save the model with a different name in a
convenient folder.
The Model Configuration Parameters window enables you to specify a code generation target and
set the code generation report options for your model.
3 In the Code Generation node of the Model Configuration Parameters window, set the System
target file parameter to rsim.tlc.
The rsim.tlc target file is compatible with Simscape Multibody models that have variable-step
solvers.
4 In the Code Generation > Report node of the Model Configuration Parameters window, check
the Create code generation report check box and click OK.
MATLAB software creates and opens a code generation report when you build your model.
5 In the Apps tab, click Simulink Coder.
Simulink Coder software generates C code for the four-bar model. The code generation report for
your model opens with a list of generated code and data files.
7-6
Generate Code for a Multibody Model
See Also
More About
• “Code Generation Applications” on page 7-2
7-7
Examples
9
8
Elevator
This example models an elevator system in Simscape™ Multibody™. The system is comprised of belt-
cable pulley circuits which control the movement of the elevator and the door mechanism. The cable
is approximated to be extensible by using high stiffness springs between the belt cable ends and the
elevator. The motor pulley is motion actuated based on the necessary elevator kinematics computed
from the Floor Number inputs. Effects of people entering and leaving the elevator are modeled using
general variable mass blocks.
Model
Simulation Results
8-2
Elevator
8-3
8 Simscape Multibody Examples
[1] Vladic, J.; Dokic, R.; Kljajin, M.; Karakasic, M.(2011). Modelling and simulations of elevator
dynamic behaviour
See Also
Belt-Cable End | Belt-Cable Properties | Belt-Cable Spool | Pulley | Revolute Joint | Spatial Contact
Force | Spherical Joint
More About
• “Cable Driven Space Manipulator” on page 8-5
• “Cable Robot” on page 8-66
• “Block and Tackle with Four Pulleys” on page 8-77
8-4
Cable Driven Space Manipulator
This example models a cable driven space manipulator. The manipulator comprises of 2 links
connected via a system of revolute joints. Each link consists of belt-cable circuits which drive the
movements of the manipulator. It also consists of a spring-damper system which provides different
stiffness requirements. A space application is shown in this example where the objective of the
manipulators is to capture a small satellite. The manipulators start from folded states and then
perform necessary maneuvers to extend and reach the desired position. The pulleys are motion
actuated from which necessary belt-cable kinematics are computed.
Model
Manipulator Subsystem
Open Subsystem
8-5
8 Simscape Multibody Examples
The plot below shows the Gripper Position and the torque applied to the motor pulleys.
8-6
Cable Driven Space Manipulator
References : [1] W.R. Doggett, J.T. Dorsey, T.C. Jones, B. King (2014). Development of a Tendon-
Actuated Lightweight In-Space MANipulator (TALISMAN)
8-7
8 Simscape Multibody Examples
This example shows a toy bumper car traveling down a series of ramps while undergoing intermittent
collisions. Spatial Contact Force blocks are used to model the friction and normal forces between
every pair of geometries that may potentially come into contact during the simulation (e.g., between
one of the car's wheels and a railing). Each Spatial Contact Force block is able to generate brief high-
impact contact forces to model collisions, as well as sustained contact forces to model rolling and
sliding.
See Also
Spatial Contact Force
More About
• “Modeling Contact Force Between Two Solids” on page 3-37
8-8
Full Vehicle on Four Post Testrig
This example models a passenger vehicle on a four-post testrig. The posts move up and down to
replicate the vertical movement of the wheels as it travels along a road. The simulation results and
animation show the response of the vehicle body and suspension as it is subjected to the motions
from the testrig. The roll and pitch of the vehicle body can be observed, and by varying the inputs
wheel hop frequencies can be determined. The vehicle model can be configured to use different
suspension types for the front suspension with different linkage combinations.
8-9
8 Simscape Multibody Examples
This example shows a single pendulum modeled using Simulink® input/output blocks and using
Simscape™ Multibody™. The initial angle for the joint is defined by a MATLAB® variable. The
annotations on the integrator block show the initial angle of the joint with respect to the world frame.
The Simulink model is built using signal connections, which define how data flows from one block to
another. The Simscape Multibody model is built using physical connections, which permit a
bidirectional flow of energy between components. Physical connections make it possible to add
further stages to the pendulum simply by using copy and paste. Input/output connections require
rederiving and reimplementing the equations.
Model
8-10
Single Pendulum in Simulink and Simscape Multibody
See Also
Revolute Joint
8-11
8 Simscape Multibody Examples
This example shows two models of a double pendulum, one using Simulink® input/output blocks and
one using Simscape™ Multibody™.
The Simulink model uses signal connections, which define how data flows from one block to another.
The Simscape Multibody model is built using physical connections, which permit a bidirectional flow
of energy between components. Physical connections make it possible to add further stages to the
pendulum simply by using copy and paste. Input/output connections require rederiving and
reimplementing the equations.
The initial angle for each joint is defined by a MATLAB® variable. The annotations on the Integrator
blocks show the initial angles of the joints with respect to the world frame.
Model
8-12
Double Pendulum in Simulink and Simscape Multibody
See Also
Planar Joint
More About
• “Assembling Parts into a Double Pendulum” on page 8-17
8-13
8 Simscape Multibody Examples
This example shows the correspondence of coordinate frames to connection lines and frame ports. It
highlights the Rigid Transform block as the fundamental method to rigidly relate nonidentical frames.
The network reference frame is the world frame, located at the center of the bottom face of the cube.
The other frames are the frames at the eight vertices of the cube, one at the center of the top face,
and two on the upper curved section.
See Also
Rigid Transform | World Frame
8-14
Creating a Simple Body
This example shows the first step in modeling a rigid body. This model is a simple body (brick) with a
frame at each of two ends and a reference frame at the center of mass. The inertia for the body is
specified as Geometric Inertia with a constant density. The block automatically computes the
appropriate inertia components. This serves as a first approximation of the actual rigid body. In
subsequent iterations more detail can be added to obtain a more accurate model of the actual rigid
body.
See Also
Brick Solid
More About
• “Model a Simple Pendulum”
8-15
8 Simscape Multibody Examples
This example shows a moderately complex mechanical link with a frame at each end and a reference
frame at the center. The link has a hole at one end and a peg at the other end. The link is a composite
of three simple solids.
See Also
Brick Solid
More About
• “Model a Simple Pendulum”
8-16
Assembling Parts into a Double Pendulum
This example shows how to assemble instances of a modularly designed link into a double pendulum.
The Upper and Lower Links are copies of the same link, with different length, density and color
parameters. The links are reused from the CompoundBodyExample example. The double pendulum
starts at an initial state and moves under the influence of gravity.
See Also
Revolute Joint
8-17
8 Simscape Multibody Examples
This example shows how to assemble instances of a modularly designed link into a four bar
mechanism (crank-rocker type). The Crank and Rocker Links are copies of the same link, with
different length, density and color parameters. The links are reused from the CompoundBody
example. The Connector link is a slightly modified version of the same link. The four bar starts at an
initial state and moves under the influence of gravity.
See Also
Revolute Joint
8-18
How to Build a Multibody in Simulink
This example highlights key concepts and recommended steps for building a mechanical model using
Simscape™ Multibody™. A simple design problem has been chosen to serve this purpose. The
following section describes the design problem and subsequent sections discuss how to solve it.
Problem Description
The problem is simplified to aiming within the plane of the mechanism. The figure shows the
schematic sketch of the mechanism and only captures the essentials of how the mechanism operates
(which is usually the case during the early stages of a design process). The link C can slide on the link
A. A motor applies torque at the revolute joint Ri and the task is to track a particular trajectory of
the revolute angle .
A key principle to follow while building models is to begin with a simple approximation to get the
basic mechanism working. In subsequent iterations add complexity to the model. The recommended
model building process in Simscape Multibody can be broken down into the following steps:
The following sections describe these steps in more detail. You can see all the model files, which are
discribed in the following sections, in the MATLAB® Current Folder Browser after opening this
example.
8-19
8 Simscape Multibody Examples
In addition, the rigid body D is rigidly connected to the world frame W since it is motionless.
You define a rigid body by specifying its shape, mass properties and interface with other parts. Each
rigid body is identified and defined in isolation. In the above example, the mechanism is composed of
four rigid bodies: A, B, C and D.
First, define the shape of the rigid body A in Simscape Multibody. Once the shape of the object is
defined and its density is specified, Simscape Multibody can compute the inertia automatically.
Instead of defining the fairly complicated shape shown above, as a first approximation, you can define
the shape of the rigid body as a simple cylinder with a length equal to that of the original part.
Once you have defined the shape (first approximation) of the rigid body A, specify its density.
Simscape Multibody now has enough information to compute the inertial properties required for
dynamic simulation. In Simscape Multibody, you define a simply shaped rigid body using the Solid
block.
The Solid block lets you define simple solids with fixed parameterizations. These include: bricks,
cylinders, polygonal extrusions, regular prisms, spheres, ellipsoids, etc. You define each
parameterized solid with respect to a reference frame. The diagram below shows the reference
8-20
How to Build a Multibody in Simulink
frames for some of the parameterized solids. The Solid block exposes this reference frame as a frame
port labelled "R" on the block.
The interface of a rigid body is established by defining frames attached to the rigid body. A rigid body
is connected to other parts of the mechanism via the rigidly attached frames. In Simscape Multibody,
joints establish a time-varying relationship between two frames. For instance, the Revolute Joint
establishes the relationship that the Z-axes of the attached frames are parallel and the origins of the
frames are coincident. The Prismatic Joint establishes the relationship that the Z-axes of the
attached frames are collinear and the X and Y axes are always parallel. Note that the frames
themselves are defined independently of the joint; the joint only establishes a relationship between
the already existing frames. Note also that the Z-axis is the axis of rotation in the case of the revolute
joint and is the axis of sliding in the case of the prismatic joint. This information is essential when we
define the interface of a rigid body by defining the frames rigidly attached to it.
In this example, the rigid body A has a cylindrical hole at one end that fits onto a peg so that A can
rotate about the axis of the cylindrical hole. This suggests that a frame should be defined at the hole
center with its Z-axis aligned with the axis of the hole (the axis of rotation). This frame is labelled as
above. The choice of orientation of the X and Y axes of partly determines the zero
configuration of the joint to which would be connected (see discussion on Zero Configuration
below). A also acts as the shaft on which part C slides. This suggests that a frame should be defined
at the center of A (an arbitrarily selected position) with its Z-axis aligned along the length of A (along
the direction of sliding). This frame is labelled as above. The frames and define the
interface for the rigid body A. The model HowToBuildAMultibodyInSimulinkBodyAApproximate
shows how the Solid and Rigid Transform blocks have been used to define the shape, inertia and
interface of the rigid body A. The Body A Ref is a Reference Frame block. This block is not
required but serves as a modeling convenience that fixes a certain frame as the frame to which other
frames are referenced to. The frames and are defined with respect to the frame to which the
Body A Ref block is connected. For a more complicated network of blocks defining a rigid body, such
a reference frame serves as a starting point for defining the positions and orientations of all other
frames.
Consider the rigid body B. The shape of the rigid body can again be approximated with a simple
cylinder. The rigid body has cylindrical holes at both ends that fit onto pegs. The rigid body B can
rotate about either hole axis. This suggests that two frames should be defined: one at each hole
center with its Z-axis aligned with the axis of the hole.
8-21
8 Simscape Multibody Examples
This rigid body has a cylindrical hole that slides on a peg. It also has a peg about which another body
can rotate. This suggests the need to define two frames: one at the center of the hole with its Z-axis
along the axis of the hole, and the other at the center of the peg with its Z-axis along the axis of the
peg. These are marked as and above.
The shape of the rigid body C can be approximated with a simple cuboid. In the first approximation of
the rigid body, the offset between the origins of frames and can also be made zero. This
results in the simplified representation of rigid body as shown below.
8-22
How to Build a Multibody in Simulink
All the individual bodies were built in isolation. The process of assembly involves establishing
relationships (using joints) between the frames attached to the rigid bodies. The following joints
establish all of the necessary relationships between the frames to assemble the mechanism.
The effort that went into carefully defining the interfaces of all of the rigid bodies (i.e. the frames
attached to them) makes it very easy to complete the mechanism by simply adding joints between the
appropriate frames. There is no need to customize the joints to achieve a default assembly of the
mechanism. The resulting assembly may or may not be in the desired configuration since the
mechanism can be assembled into multiple configurations. The model
HowToBuildAMultibodyInSimulinkAssemblyWithError shows the assembled mechanism.
8-23
8 Simscape Multibody Examples
In the model an intentional mistake has been made in the definition of the frame attached to
rigid body C. This causes the assembly to fail. The figure below shows the desired and actual
orientations of the frame .
The orientation of has to be corrected by a rotation of 90 deg about the Z-axis. Update the model
(Ctrl-D) HowToBuildAMultibodyInSimulinkAssemblyWithError to visualize the mechanism. An
error is reported indicating that the assembly failed. In the Mechanics Explorer, select Model
Report option from the Tools pulldown menu. In the Model Report the Joints section will show that
the joint Pg has failed to assemble. This indicates that there might be an error in the specification of
the frames attached to the joint Pg. In this example it is in fact true that an error was made in the
specification of the frame .
The Zero Configuration of a joint is defined as the relative position and orientation between the
base and follower frames when all of the joint angles are zero. For almost all of the joints in Simscape
Multibody, the base and follower frames are identical in the zero configuration: their origins are
coincident, and their axes are aligned. One defines the relative position and orientation between two
bodies connected by a joint when the joint angles are zero by adjusting the positions and orientations
of the base and follower frames on their respective bodies.
Consider, for example, the rigid bodies B and C and the joint Rg connecting them. The frames
and are the base and follower frames of the joint Rg. The figure below shows how different
choices of orientations for the frame attached to rigid body C result in different assembled
configurations when the joint angle is zero. The choice of orientation of the frames must be made
with the desired zero configuration in mind.
In the aiming mechanism, the choice of frame orientations leads to a default assembled configuration
in which the central axes of all of the bodies lie along the same line.
The configuration depicted in the schematic diagram of the mechanism is the desired initial assembly
configuration. From the schematic diagram we can see that in the initial configuration the angle is
about 35 deg. The assembly algorithm can be guided by specifying joint position and velocity targets.
In this example, the position target for the joint Ro can be set to guide assembly into the desired
initial configuration (see figure below). The target priority has been set as High. Since this is the only
target in the model, Simscape Multibody is able to achieve it exactly.
8-24
How to Build a Multibody in Simulink
Update the model (Ctrl-D) to update the visualization with the changes. The assembly is closer to the
configuration in the schematic diagram. Check the Model Report to see that the joint target for Ro
has been met exactly.
Unfortunately, the assembled configuration is not the intended one because the rigid body B is not
aligned as indicated in the schematic diagram. Attempting to specify the joint angles of both and
exactly is an over-specification for this one degree-of-freedom mechanism. This is not prohibited,
but if there is a conflict, neither target may be met. Moreover, the desired angle of joint Ri is not even
known exactly.
In this situation, a convenient approach is to leave the high-priority target of 35 deg on Ro but to
specify the angle of Ri through a low-priority position target. The latter provides an approximate
value, or hint, for the desired joint angle. In this case, it is obvious that the angle should be obtuse;
150 deg is a rough estimate of its desired value. This target is set for joint Ri with a priority of Low.
The assembled configuration after setting the new target is shown below.
Simulate the model (Ctrl-T) to view the motion of the mechanism under gravity.
In this example, the goal is to make the angle track a desired trajectory by applying a torque at the
joint Ri. The joint Ri will be torque actuated and the joint angle and its derivative (angular velocity)
will be sensed from the joint Ro. The entire mechanism can be enclosed within a subsystem that
takes a torque input and outputs the angle and angular velocity . This subsystem is the canonical
Plant in Control Design parlance. The model HowToBuildAMultibodyInSimulinkPlant shows the
mechanism setup for control design.
8-25
8 Simscape Multibody Examples
8-26
How to Build a Multibody in Simulink
Now that the basic model is working, the next step is to add detail to make the model more realistic
and accurate. Perhaps the first version of the model was created when detailed information about the
geometry of the rigid bodies was not yet available. Having carefully established the interfaces of the
rigid bodies, it is fairly easy to add detail to each of the rigid bodies without affecting/changing the
rest of the model.
As an example, consider adding detail to the rigid body A while keeping its interface unchanged. The
figure below shows rigid body A as a composition of simpler bodies. The interface exposed by rigid
body A is still the pair of frames and . Their positions and orientations remain unchanged.
The frames , , and are internal to the rigid body and should be created to assemble the
individual pieces of the rigid body into a whole. The model
HowToBuildAMultibodyInSimulinkBodyAComplex shows the construction of the complex version
of the rigid body A.
8-27
8 Simscape Multibody Examples
The tracking performance is similar because the controller is sufficiently robust to handle the slight
differences in inertia between the simple and detailed version of rigid body A. Following a similar
process, we can also add detail to the other parts. Different versions of each rigid body with varying
levels of detail can be maintained in a library, and the model can be tested with these various
alternatives. Configurable Subsystems would be useful here.
Summary
• Started with a schematic diagram of the mechanism and identified the rigid bodies and joints in
the mechanism.
• Built a first approximation of each rigid body in isolation
• Assembled the rigid bodies together using joints to achieve the first version of the assembled
mechanism.
• Used the Model Report tool to identify problems with the assembly
• Used Joint Position Targets to guide the assembly into a desirable configuration.
• Added a simple controller to the model to achieve target angle tracking.
• Once a full first version of the model was complete, added details to one of the rigid bodies
without changing the interface of the rigid body. Details could be added to other rigid bodies as
well.
This method of starting simply and adding complexity in subsequent iterations is recommended when
building models in Simscape Multibody.
See Also
Revolute Joint | Prismatic Joint
8-28
Using the Lead Screw Joint Block - Linear Actuator
This example illustrates the use of the Lead Screw Joint block to model a linear actuator. The Lead
Screw Joint block converts rotational motion at the Revolute Joint block to translational motion at the
four Cylindrical Joint blocks. The translational motion is specified as a motion input to a cylindrical
joint and the necessary actuator torque is automatically computed at the revolute joint.
See Also
Lead Screw Joint
8-29
8 Simscape Multibody Examples
This example shows a Power Take-Off (PTO) shaft, a device for transferring power from tractor
engines to auxiliary equipment such as soil tillers and wood chippers. The model includes two PTO
subsystems identical in every sense but their joints. One contains universal (U) joints, the other
constant-velocity (CV) joints.
At large bend angles, U joints lead to uneven rotations, subjecting the adjoining shafts to relatively
large vibrations and elevated internal stresses. CV joints eliminate these by allowing the shafts to
spin at constant velocity, resulting in a smooth motion profile no matter the bend angle.
A single set of motion inputs governs the behavior of the PTO subsystems. The Scope block plots the
resulting angular velocities and bend angles of the shafts, enabling you to compare the kinematics of
the two joint types.
8-30
Modeling Constant Velocity Joints - Power Take-Off Shaft
See Also
Constant Velocity Joint
8-31
8 Simscape Multibody Examples
This example shows the Cardan Gear mechanism that converts rotational motion into reciprocating
linear motion without using linkages or slideways. The mechanism uses three gears - one sun and two
planet gears. The sun gear is twice as large as the planet gears (which are of the same size). The red
pointer on the link traces a straight line as the gears rotate.
See Also
Common Gear Constraint
8-32
Using the Rack-Pinion Block - Windshield Wiper Mechanism
This example shows a windshield wiper mechanism. The mechanism utilizes a rack and pinion to
drive the wiper blades in a synchronized fashion. The rack is actuated using a scotch yoke coupling
(modeled using a pin-slot joint) that converts the rotary motion of the motor to reciprocating motion
of the rack. The rack and pinion arrangement converts the reciprocating linear motion of the rack
into reciprocating angular motion of the wiper blades (which are rigidly attached to the pinion).
See Also
Rack and Pinion Constraint
8-33
8 Simscape Multibody Examples
This example illustrates the use of the Worm and Gear Constraint block to model a solar tracker. A
slew drive containing a worm and gear constraint powers the yaw rotation of the solar trackers. The
worm and gear geometry gives a large reduction in a single stage of gearing which provides precision
tracking and high torque output. The yaw rotation is specified as a motion input to the gear revolute
joint and the necessary actuator torque is automatically computed at the worm revolute joint.
See Also
Worm and Gear Constraint
8-34
Using the Point-On-Curve Block: Flapping Wing Mechanism
This model simulates a barrel cam based wing flapping mechanism. This is a one degree of freedom
mechanism and the two wings flap in sync with each other. The Spline and Point On Curve blocks
have been used to model the Barrel Cam mechanism that actuates the flapping motion of the wings.
See Also
Point on Curve Constraint
8-35
8 Simscape Multibody Examples
This example illustrates the use of motion actuation to determine the actuator torques needed for the
robot to achieve a given welding task. The system consists of a seven degree of freedom robot
carrying a welding torch. The tip of the torch needs to trace the joints being welded. In this example
the tip of the torch is made to trace (using motion actuation) a plus sign, a circle and a star sign on
the workpiece. The torch is lifted off the workpiece when transitioning between the different shapes.
The motion of the welding torch is specified and the actuator torques required at the various joints of
the robot to achieve this motion is computed.
See Also
Bushing Joint | Revolute Joint
8-36
Computing Actuator Torques Using Inverse Dynamics
More About
• “Cartesian 3-D Printer” on page 8-100
• “Joint Actuation Limitations” on page 3-27
• “Motion Sensing” on page 3-54
• “Specifying Joint Actuation Inputs” on page 3-20
8-37
8 Simscape Multibody Examples
The example shows how you can sense forces and torques acting at joints. A potter's wheel spins with
a piecewise linear velocity profile while holding a piece of clay off center. The clay creates a dynamic
imbalance, generating periodic constraint forces at the joints. Viscous damping accounts for energy
dissipation in the axle.
Scopes 1 and 2 show the composite forces and torques that you can sense at the joints. These include
the constraint forces and torques and also the total forces and torques, which are the net sum of
constraint, actuation and internal components. The constraint components are zero in the direction of
motion, while the actuation and internal components are zero in the constrained directions.
8-38
Sensing Composite Forces and Torques in Joints - Potter's Wheel
See Also
Weld Joint | Revolute Joint
More About
• “Force and Torque Sensing” on page 3-34
8-39
8 Simscape Multibody Examples
This example models a self-locking worm and gear constraint. The model shows a mechanical jack
driven by a torque applied to a worm. The model includes two worm jack subsystems identical in
every sense except for the value of the worm lead angle. Both subsystems have friction models
applied to their Worm and Gear Constraint blocks.
A worm and gear constraint is self-locking when the static friction coefficient is greater than the
tangent of the worm lead angle. One subsystem has a worm lead angle slightly less than this
threshold (self-locking) and the other subsystem has a worm lead angle slightly greater than this
threshold (non-locking).
The torque applied to the worm lifts a load via a rack and pinion. When the load reaches its highest
point the torque signal is disabled. This effectively models a motor malfunction. The non-locking
subsystem back-drives and the load falls under gravity. The self-locking subsystem remains at the
highest point.
See Also
Worm and Gear Constraint
8-40
Rotational Interface: Electrically Operated Bread Slicer
This model simulates an electrically operated 1-DOF bread slicing mechanism. The electrical circuit
and motor are modeled in Simscape™ while the bread slicing mechanism is modeled in Simscape
Multibody™. The model uses a Rotational Multibody Interface block to connect the Simscape
components to a Revolute Joint block in Multibody.
See Also
Rotational Multibody Interface
8-41
8 Simscape Multibody Examples
This model simulates a five cylinder radial engine. The pressure dynamics inside the cylinders are
modelled using the Simscape™ Foundation Library gas and mechanical translational domains. The 3D
mechanical components are modelled using Simscape Multibody™. See inside any of the blocks
called "Force Model" to see how the 1D Simscape and 3D Multibody parts of the model are
interfaced. The pressure model is an ideal pressure source which applies pressure based on the crank
angle. This model can be replaced with a more realistic pressure model of the cylinder chamber. The
cylinders fire in the sequence - A C E B D providing a power stroke every 144 deg of crank rotation.
See Also
Translational Multibody Interface
8-42
Hydraulic Interface - Dump Trailer with Hydraulic Cylinder
This example shows a dump trailer powered by a double-acting hydraulic cylinder. The cylinder
actuates a scissor hoist mechanism that raises and lowers the dump bed. The model provides an
example of how to interface Simscape™ Multibody™ joints with Simscape components that have
mechanical domain ports.
The Double-Acting Hydraulic Cylinder block in the scissor hoist contains mechanical and hydraulic
subsystems. The mechanical subsystem models the piston and barrel. A Prismatic Joint block provides
the translational degree of freedom needed for piston extension and retraction. The piston's range of
motion is constrained using joint limits. The hydraulic subsystem contains two Translational
Mechanical Converter blocks from the Isothermal Liquid (IL) foundation library in Simscape. These
blocks exchange velocity and force information with the prismatic joint via a Translational Multibody
Interface block. In addition, both of the converter blocks are configured to accept a physical position
signal from the prismatic joint. These connections ensure that the state of the hyraulic chambers in
the converter blocks are always consistent with the state of the prismatic joint.
8-43
8 Simscape Multibody Examples
See Also
Rotational Multibody Interface
8-44
Stewart Platform with Controller
2. Import the Simscape Multibody Import XML into a Simscape Multibody model using the smimport
command.
3. Enclose the imported model into a subsystem (Stewart Platform). Interface layer is created to
isolate the imported model from the blocks used to interface it to the rest of the model. The
subsystem "Stewart Platform/Imported Stewart Platform" contains only the imported model.
4. Export input (Force) and output (pos and vel) ports that correspond to the control inputs and
sensor outputs. These form the interface of the Stewart Platform model to its controller.
5. Within the subsystem, connect the force input and sensor output ports to appropriate blocks of the
Stewart Platform model. Example: see block "Stewart Platform/Imported Stewart Platform/
ActuatorAssm1_2/Cylindrical".
6. Connect the controller to the Stewart Platform model inputs and outputs.
8. If there are any changes to the CAD model, then it can be re-exported and the contents of the
Stewart Platform/Imported Stewart Platform" subsystem can be replaced with the newly imported
model without changing its interface (ports) to the controller. The controller gains can be re-tuned.
8-45
8 Simscape Multibody Examples
See Also
smimport
8-46
Four Bar Mechanism Imported from a CAD Assembly
This example has been imported from a CAD assembly designed in SolidWorks® using the smimport
command. The XML file "FourBar.xml" and the STL files obtained during export of the CAD assembly
have been used to create this example.
See Also
smimport
8-47
8 Simscape Multibody Examples
This example shows how to import geometry and inertia data using STEP files. The STEP file is a
standard format used commonly for data exchange between CAD applications. The format can
capture the complete geometry information of a part. Given the mass of the part and the volume
distribution, Simscape™ Multibody™ can automatically compute the inertia properties of the part.
Open the Solid block dialogs in the above model to see how the geometry and inertia parameters are
configured to utilize STEP files exported from another application (CAD for example). This method of
importing geometry and inertia information can be used for CAD systems that are not supported by
Simscape Multibody Link. A valid STEP file from any source application can be imported by this
method.
See Also
File Solid
8-48
Modeling a Robot Using STEP Files
More About
• “Specifying Custom Inertias” on page 1-69
8-49
8 Simscape Multibody Examples
Humanoid Robot
This example has been imported from a URDF file using the smimport command. The URDF file
"Humanoid.urdf" and the STEP files that visualize the robot parts were used to create this example.
Motion actuation of the joints was manually added to the imported model to make the robot perform
interesting movements.
See Also
smimport
More About
• “Import a URDF Humanoid Model” on page 6-37
• “Import URDF Models” on page 6-30
• “Specifying Joint Actuation Inputs” on page 3-20
8-50
Configuring Dynamic Cameras - Vehicle Slalom
This example illustrates the use of dynamic cameras to view a vehicle traversing a slalom course. The
vehicle accelerates from stationary to a fixed speed and then enters the slalom course. Upon exiting,
the vehicle decelerates back to stationary before the end of the road. The model has four dynamic
cameras: three with tracking parameterization and one with keyframes. The tracking cameras show
the front and side views of the vehicle from a fixed offset relative to the vehicle, along with the view
from the driver's perspective. The keyframed camera shows a sweeping view of the vehicle maneuver.
See Also
Planar Joint | Camera Manager
8-51
8 Simscape Multibody Examples
This model shows a wing landing gear mechanism that can deploy and retract based on the input
deploy signal. The mechanism consists of the main column that houses the wheel assembly and the
locking mechanism that is used to lock the landing gear in the deployed position.
The mechanism is controlled by two low level controllers (one for deploying and retracting the main
column and the other to lock and unlock the main column into position) and a primary controller that
coordinates them. The low level controllers are both simple PID controllers. The primary controller
turns on the deploy/retract controller to deploy the landing gear and when the main column is close
enough to the deployed position, it disables the deploy/retract controller and uses the locking
controller to lock the mechanism into position. The reverse happens during retraction.
8-52
Airplane Wing Landing Gear
See Also
Revolute Joint
8-53
8 Simscape Multibody Examples
This example shows how to model an inverted double pendulum mounted on a sliding cart using
Simscape™ Multibody™. It also illustrates the use of a controller to balance the pendulum in the
upright position. Make any changes to the system and click on the blue box to generate a linearized
model for the system before running the simulation. The control gains are computed using the
linearized model. The pole placement technique is used to compute the control gains from the
linearized model. The controller keeps the double pendulum vertical in the presence of a random
disturbance force. See the supporting files linearize.m and controlGains.m for details.
See Also
Revolute Joint
8-54
Stewart Platform
Stewart Platform
This model shows a Stewart platform manipulator that can track a parameterized reference
trajectory. The shape, size, and kinematics of the manipulator are highly configurable.
The reference trajectory is specified in 6-D pose space, and an inverse kinematics module converts it
into one through 6-D leg position space. A generic PID controller attempts to drive the manipulator
along the desired trajectory.
See Also
Cylindrical Joint | Transform Sensor
More About
• “Stewart Platform with Controller” on page 8-45
8-55
8 Simscape Multibody Examples
This example illustrates a double wishbone front wheel automotive suspension. The suspension is
mounted on two platforms that can independently move up and down to simulate a road profile on
each wheel. For a given pair of road profiles, the resultant roll and bounce of the chassis can be
studied and the suspension parameters tuned for optimal performance. The inputs to the two
platforms are the road profile and its derivative. The platforms have a PD controller that controls the
vertical position of the platform to mimic the input road profile. See "Road Profiles Generator" block
dialog for details on the test road profiles.
See Also
Revolute Joint
8-56
Vehicle Suspension System Templates
This example includes templates for three common types of automotive suspension systems: double
wishbone, MacPherson, and pushrod. Tires attached to the suspension systems are mounted on
platforms that can independently move up and down. Each platform has a PD controller that allows it
to simulate a desired road profile. For a given pair of road profiles, the resultant roll and bounce of
the chassis can be studied and the suspension parameters can be tuned for optimal performance.
See Also
Revolute Joint
8-57
8 Simscape Multibody Examples
Backhoe
This example shows a hydraulically actuated backhoe model with closed-loop PID control. The
mechanism consists of a fixed vehicle model with a base mounting bracket. The bracket allows the
backhoe arm to swivel left and right. Additionally, this arm has three rotational degrees of freedom
for controlling the position of the bucket relative to the base swivel point.
The backhoe is actuated using pressure inputs to linear acting hydraulic cylinders. Pressure is
controlled with decoupled PID controllers that act on the error between measured and reference
angular positions.
The model uses Translational Multibody Interface blocks to connect 1D mechanical translational
domain lines in Simscape (used by Translational Mechanical Converter blocks to model the hydraulic
cylinders) with Prismatic Joint blocks in Simscape Multibody (used to model the backhoe mechanism).
Additionally, position signals from the Prismatic Joint blocks are fed directly into the Translational
Mechanical Converter blocks to ensure that Simscape and Simscape Multibody always agree on the
value of each cylinder's displacement.
8-58
Backhoe
See Also
Prismatic Joint | Translational Multibody Interface
More About
• “Connecting Simscape Networks to Simscape Multibody Joints”
• “Hydraulic Interface - Dump Trailer with Hydraulic Cylinder” on page 8-43
• “Modeling a Double-Acting Actuator”
8-59
8 Simscape Multibody Examples
This example models a 3-Roll robotic wrist mechanism based on the Cincinnati-Milacron 3-roll wrist
mechanism. The mechanism uses three bevel gear pairs to rotate the tool about 3 independent axes.
The tip of the tool moves along the surface of a sphere and can be rotated about an axis that passes
through the center of that sphere (drilling action). In this example, precomputed torques are applied
to the three drive shafts to achieve a certain trajectory (on the surface of the sphere) of the tool tip.
Drilling is performed at different points along the trajectory.
See Also
Bevel Gear Constraint
More About
• “Modeling Gear Constraints” on page 2-27
8-60
Fairground Carousel Ride
This example shows a fairground carousel ride. A torque applied to the wheel causes the carousel to
rotate and a hydraulic actuator provides the force to lift the arm. The cabs are free to rotate about an
axis approximately tangential to the wheel radius. When the wheel is near vertical, the centrifugal
acceleration acting on the cabs (caused by the rotation of the wheel) ensures that the cabs are close
to a near vertical position. Consequently, the riders are close to 'up-side-down' at the top of the
rotation.
The acceleration at the center of the torso of a dummy is measured to show whether the ride is 'fun'
and 'safe'. In addition, the hub motor power and hydraulic pressure are measured to validate the
design. The control signals (reference and actual) for the hub speed and lift-arm angle are plotted to
show the performance of the controllers.
See Also
Revolute Joint
8-61
8 Simscape Multibody Examples
This example models a delta robot performing a pick and place task. The robot picks up a part using a
vacuum gripper, moves the part to each of the four markers on the table, drops the part at the first
marker, and then returns to the home position. This example demonstrates how to:
• Create KinematicsSolver objects and call them via MATLAB Function blocks to compute
forward and inverse kinematics during simulation.
• Model contact using Spatial Contact Force blocks.
Model
The Delta Robot subsystem models a 3-DOF delta robot. The motion of the end effector is purely
translational due to the kinematic structure of the robot. The robot's actuators correspond to the
three torque-actuated revolute joints mounted to the upper base plate. To mimic encoder data, the
subsystem outputs the positions (angles) of the actuators. A camera frame is mounted underneath the
base plate and looks down towards the end effector. The geometry associated with the end effector is
exported via a Simscape Bus to facilitate contact modeling. See the block mask for more information.
8-62
Pick and Place Robot Using Forward and Inverse Kinematics
Because trajectory planning for the end effector is done with respect to the xyz coordinates of the
robot's camera frame, a forward kinematics map is needed to transform the positions and velocities
of the actuators to the position and velocity of the end effector. Similarly, an inverse kinematics map
is needed to transform the desired position of the end effector computed by the planner to the
corresponding positions of the three actuators. These forward and inverse kinematics computations
are done using KinematicsSolver objects. The objects are defined as persistent variables in the
functions PickAndPlaceRobotFk and PickAndPlaceRobotIk. These functions are called by the MATLAB
function blocks Planning and Control/Forward Kinematics and Planning and Control/Inverse
Kinematics highlighted below. To speed up computation and help ensure the KinematicsSolver object
for the inverse kinematics problem finds the desired solutions, the previous solution is used as the
initial guess for the current problem. Whenever the parameters of the Delta Robot subsystem change,
the PickAndPlaceRobotFk and PickAndPlaceRobotIk functions are cleared from memory so that the
KinematicsSolver objects are regenerated at the beginning of the next simulation. This ensures that
the KinematicsSolver objects and the model stay in sync.
8-63
8 Simscape Multibody Examples
Planning occurs in the MATLAB Function block Planning and Control/Path Planner highlighted below.
The planner transitions the robot between three different modes:
Whenever a mode begins, a trajectory is computed that takes the end effector from its current
position to the mode's goal position in a fixed amount of time. The trajectory is generated in two
stages: first, a third-order polynomial is computed corresponding to the path of the end effector in xyz
camera coordinates from its current position to the goal position; second, a fifth-order polynomial is
computed which is used to scale the time along the path such that the initial and final velocities and
accelerations are all zero. A mode transition occurs when the position and velocity of the end effector
are sufficiently close to the goal values. Given the current time, the planner returns the desired
position and velocity of the end effector along the trajectory as well as the desired state of the
vacuum.
The Planning and Control/Controller subsystem highlighted below contains a discrete time PID
controller that drives the actual positions of the actuators to their desired values.
8-64
Pick and Place Robot Using Forward and Inverse Kinematics
Vacuum Subsystem
To grasp the part, a simple vacuum is modeled between the part and the robot's end effector.
Whenever the planner commands suction, the vacuum applies a constant force between the center of
mass of the part and the tip of the end effector.
Contact Subsystems
Spatial Contact Force blocks inside the End Effector-Part Contact Forces and Part-Table Contact
Forces subsystems are used to model contact. To speed up the simulation, three contact points
equally spaced around the tip of the end effector are used as proxies for full cylindrical geometry
when it is in contact with the part. Similarly, three equally spaced contact points around the bottom
edge of the part are used as contact proxies for when it makes contact with the table. The vacuum
force keeps the part in contact with the end effector, and friction prevents it from slipping during
transport.
Image Processor
The Image Processor subsystem uses Transform Sensor blocks to simulate the processing of camera
data to track the locations of the part and the markers on the table.
See Also
KinematicsSolver | solve
More About
• “Perform Forward and Inverse Kinematics on a Five-Bar Robot” on page 8-141
8-65
8 Simscape Multibody Examples
Cable Robot
This example models a cable robot. The robot comprises 8 independent belt-cable circuits which
control the 6 degrees-of-freedom of the mover. A ball is dropped from a fixed height down the center
axis of the mechanism. The mover initially starts directly below the ball and the contact is modeled
between the mover and the ball such that the ball bounces elastically when striking the mover. The
objective of the mover is to perform increasingly complex maneuvers between successive bounces of
the ball. The mover is motion actuated from which the necessary cable, pulley, and motor spool
kinematics are computed.
See Also
Belt-Cable End | Belt-Cable Properties | Belt-Cable Spool | Bushing Joint | Planar Joint | Pulley |
Revolute Joint | Spatial Contact Force | Spherical Joint
More About
• “Block and Tackle with Four Pulleys” on page 8-77
8-66
Cable-Driven Cross Slide Table
This example models an XY cross positioning table that uses a cable-driven mechanism. A single cable
wraps around seven different pulleys and converts the rotational angle of the two input pulleys to the
x-y position of the table.
Inverse kinematics can be used to map table position to pulley angle. The model allows you to specify
the motion of the table in x-y coordinates and determine the required pulley rotation to produce that
movement. Inverse dynamics can be used to calculate the torque required to produce that motion.
Model
Platform Subsystem
This subsystem models the platform that has two degrees of freedom. The slider and the table are
constrained by two prismatic joints which permit movement along two perpendicular axes. The
mounting points for all seven pulleys are defined in this subsystem.
8-67
8 Simscape Multibody Examples
Pulleys Subsystem
This subsystem models the seven pulleys which are connected by a single cable. The pulley
constraints and the cable connections ensure that the rotation of the individual pulleys follows the
kinematic behavior as specified in the diagram. The cable ends attach to points on the upper part of
the platform.
8-68
Cable-Driven Cross Slide Table
Motion Subsystem
This subsystem shows the inputs that can be used to prescribe the motion of the table. The upper set
of inputs prescribes the motion of the table in x-y coordinates, and an inverse kinematic simulation
can determine the required rotations of pulleys 2 and 6 to achieve that movement. The lower set of
inputs prescribe the angles of pulleys 2 and 6. This data was recorded from the inverse kinematic
simulation.
8-69
8 Simscape Multibody Examples
8-70
Cable-Driven Cross Slide Table
The plots below show the required motion and torques for pulley 2 and pulley 6 to produce the
desired motion of the table.
8-71
8 Simscape Multibody Examples
See Also
Revolute Joint | Pulley | Belt-Cable Spool | Belt-Cable Properties | Belt-Cable End
8-72
Pulley Mechanism Right Angle Drive
This example models a pulley mechanism that takes a torque applied to a winch and transmits it to a
pulley rotated at 90 degrees to that winch. This example uses blocks from the Simscape Multibody
Belts and Cables library to model a pulley mechanism that is not all in a single plane.
Model
Pulleys Subsystem
Open Subsystem
8-73
8 Simscape Multibody Examples
The plot below shows the torque applied to the winch and the speed of the winch. Note that for the
first second, no torque is applied to the winch, but the load still moves due to gravity.
8-74
Pulley Mechanism Right Angle Drive
See Also
Revolute Joint | Pulley | Belt-Cable Spool | Belt-Cable Properties | Belt-Cable End
8-75
8 Simscape Multibody Examples
This example models a tower crane with a trolley and a hoist. The hoist can raise and lower a load,
and the trolley moves the load towards and away from the tower. Blocks from the belts and cables
library are used to model the pulleys that control lifting the load and moving the trolley.
See Also
Belt-Cable End | Belt-Cable Properties | Belt-Cable Spool | Bushing Joint | Prismatic Joint | Pulley |
Revolute Joint | Spatial Contact Force | Spherical Joint
More About
• “Cable Driven Space Manipulator” on page 8-5
• “Cable Robot” on page 8-66
• “Block and Tackle with Four Pulleys” on page 8-77
8-76
Block and Tackle with Four Pulleys
This example models a block and tackle with four pulleys. Torque is applied to a winch which acts
through the pulley mechanism to lift a load. Blocks from the Simscape™ Multibody™ Belts and
Cables library are used to model the block and tackle.
Model
8-77
8 Simscape Multibody Examples
Pulleys Subsystem
The plot below shows the torque applied to the winch and the vertical speed of the load. Note that for
the first second, no torque is applied to the winch, but the load still moves due to gravity.
8-78
Block and Tackle with Four Pulleys
See Also
Belt-Cable End | Belt-Cable Properties | Belt-Cable Spool | Planar Joint | Pulley | Revolute Joint
More About
• “Cable Robot” on page 8-66
• “Elevator” on page 8-2
8-79
8 Simscape Multibody Examples
This example models a pair of gears with parallel axes. The assembly contains the two gears and all
constraints required for the gear set. The assembly can be configured to model an external or
internal gear set by adjusting parameters in the mask.
Model
Open Subsystem
8-80
Using the Common Gear Block
The Common Gear Constraint requires that the rest of the mechanism hold the two frames to which it
is connected in alignment. This subsystem has the necessary constraints and parameterized Rigid
Transform to hold the frames in the right position and orientation.
Open Subsystem
The plot below shows the speeds of the two shafts connected by the common gear assembly in an
external configuration.
8-81
8 Simscape Multibody Examples
The plot below shows the speeds of the two shafts connected by the common gear assembly in an
internal configuration.
8-82
Using the Common Gear Block
See Also
Worm and Gear Constraint | Rack and Pinion Constraint
8-83
8 Simscape Multibody Examples
This example models a lead screw with friction. The constraint force in the lead screw is measured
and used to calculate the friction torque within the lead screw. A continuous stick-slip friction model
is used to determine the coefficient of friction based on the relative rotational speed of the two parts
connected by the lead screw.
Model
This subsystem calculates and applies the friction torque to the two parts connected by the lead
screw joint. Open Subsystem
8-84
Lead Screw with Friction
The plot below shows the actuation torque of the lead screw. In this test, the coefficient of friction is
low enough that the load force can backdrive the lead screw.
The Lead Screw Joint can be configured such that positive rotation leads to positive translation.
8-85
8 Simscape Multibody Examples
Increasing the coefficient of friction higher than the tangent of the lead angle will make the lead
screw non-backdriveable. Applying an axial load force will not be sufficient for the screw to move.
8-86
Lead Screw with Friction
See Also
Prismatic Joint | Revolute Joint | Lead Screw Joint | External Force and Torque
More About
• “Actuating and Sensing with Physical Signals” on page 3-29
8-87
8 Simscape Multibody Examples
Forklift
This example models a forklift which uses the hydraulic and pulley mechanisms to perform the lift
action. The tilting of masts is also controlled by hydraulic cylinders. The forklift comprises of 3 masts,
namely main mast, top mast and fork mast. The main mast is connected to the chassis by revolute
joints and its tilting is governed by the hydraulic tilt cylinders. The top mast slides over the main mast
and its motion is governed by the hydraulic lift cylinders. The fork mast slides on the top mast and
hangs through belt-cable circuits which drives the movement of the fork mast. A common warehouse
application is shown in this example where the objective of the forklift is to grab a box, pass over a
bump and place the box in the racks. Spatial Contact Force blocks are used at all contact locations to
model the contact between the bodies. The contact between the ground surface and the wheels are
modeled using infinite plane block and the contact between the forks and the box are modeled using
the point blocks.
Model
8-88
Forklift
Assembly of Forklift
Open Subsystem
The plot below shows the Normal force and Frictional force at each wheels during the lift, bump and
place motion of the forklift.
8-89
8 Simscape Multibody Examples
See Also
Spatial Contact Force
More About
• “Modeling Contact Force Between Two Solids” on page 3-37
• “Solid Cylinder Rolling Down an Incline” on page 3-50
• “Use Contact Proxies to Simulate Contact” on page 3-41
8-90
Using the Reduced Order Flexible Solid Block - Flexible Dipper Arm
This example shows how to model a flexible dipper arm, such as the arm for an excavator or a
backhoe, by using the Reduced Order Flexible Solid block. This block captures the mechanical
behavior of a deformable body through reduced-order stiffness and mass matrices that are associated
with interface frame locations. In this example, the Partial Differential Equation Toolbox™ is used to
create the reduced-order model.
The dipper is mounted on top of a rotating tower as part of a test rig. The cylinder actuates the arm
vertically while the rotating tower allows the arm to swing left and right. A spherical test tool is
attached to the tip of the dipper to allow contact with a solid wall. The Scope block allows us to
visualize the deformations and reaction forces that result from the motion of the rig.
See Also
Reduced Order Flexible Solid | Spatial Contact Force
8-91
8 Simscape Multibody Examples
More About
• “Model an Excavator Dipper Arm as a Flexible Body” on page 1-51
8-92
Train Humanoid Walker
This example shows how to model a humanoid robot using “Simscape Multibody” and train it using
either a genetic algorithm (which requires a “Global Optimization Toolbox” license) or reinforcement
learning (which requires “Deep Learning Toolbox” and “Reinforcement Learning Toolbox” licenses).
This example is based on a humanoid robot model. You can open the model by entering
openExample("sm/ImportedURDFExample") in the MATLAB® command prompt. Each leg of the
robot has torque-actuated revolute joints in the frontal hip, knee, and ankle. Each arm has two
passive revolute joints in the frontal and sagittal shoulder. During the simulation, the model senses
the contact forces, position and orientation of the torso, joint states, and forward position. The figure
shows the Simscape™ Multibody™ model on different levels.
8-93
8 Simscape Multibody Examples
Contact Modeling
The model uses Spatial Contact Force blocks to simulate the contact between the feet and ground. To
simplify the contact and speed up the simulation, red spheres are used to represent the bottoms of
the robotic feet. For more details, see “Use Contact Proxies to Simulate Contact” on page 3-41.
8-94
Train Humanoid Walker
8-95
8 Simscape Multibody Examples
Joint Controller
The model uses a stiffness-based feedback controller to control each joint [1]. Model the joints as
first-order systems with an associated stiffness (K) and damping (B), which you can set to make the
joint behavior critically damped. The torque is applied when the setpoint θ0 differs from the current
joint position θ:
•
T = Bθ + K θ0 − θ .
You can vary the spring set-point θ0 to elicit a feedback response to move the joint. The figure shows
the Simulink® model of the controller.
The goal of this example is to train a humanoid robot to walk, and you can use various methods to
train the robot. The example shows the genetic algorithm and reinforcement learning methods.
This example uses an objective function to evaluate different walking styles. The model gives a
reward (rt) at each timestep:
rt = w1 vy + w2ts − w3 p − w4 Δz − w5 Δx
Here:
8-96
Train Humanoid Walker
T
R= ∑ rt
t=0
Here T is the time at which the simulation terminates. You can change the reward weights in the
sm_humanoid_walker_rl_parameters script. The simulation terminates when the simulation time
is reached or the robot falls. Falling is defined as:
To optimize the walking of the robot, you can use a genetic algorithm. A genetic algorithm solves
optimization problems based on a natural selection process that mimics biological evolution. Genetic
algorithms are especially suited to problems when the objective function is discontinuous,
nondifferentiable, stochastic, or highly nonlinear. For more information, see ga (Global Optimization
Toolbox).
The model sets the angular demand for each joint to a repeating pattern that is analogous to the
central pattern generators seen in nature [2]. The repeating pattern yields an open-loop controller.
The periodicity of the signals is the gait period, which is the time taken to complete one full step.
During each gait period, the signal switches between different angular demand values. Ideally, the
humanoid robot walks symmetrically, and the control pattern for each joint in the right leg is
transmitted to the corresponding joint in the left leg, with a delay of half a gait period. The pattern
generator aims to determine the optimal control pattern for each joint and to maximize the walking
objective function.
8-97
8 Simscape Multibody Examples
To train the robot with a genetic algorithm, open the sm_humanoid_walker_ga_train script. By
default, this example uses a pretrained humanoid walker. To train the humanoid walker, set
trainWalker to true.
Alternatively, you can also train the robot using a deep deterministic policy gradient (DDPG)
reinforcement learning agent. A DDPG agent is an actor-critic reinforcement learning agent that
computes an optimal policy that maximizes the long-term reward. DDPG agents can be used in
systems with continuous actions and states. For details about DDPG agents, see rlDDPGAgent
(Reinforcement Learning Toolbox).
8-98
Train Humanoid Walker
To train the robot with reinforcement learning, open the sm_humanoid_walker_rl_train script.
By default, this example uses a pretrained humanoid walker. To train the humanoid walker, set
trainWalker to true.
References
[1] Kalveram, Karl T., Thomas Schinauer, Steffen Beirle, Stefanie Richter, and Petra Jansen-Osmann.
“Threading Neural Feedforward into a Mechanical Spring: How Biology Exploits Physics in Limb
Control.” Biological Cybernetics 92, no. 4 (April 2005): 229–40. https://doi.org/10.1007/
s00422-005-0542-6.
[2] Jiang Shan, Cheng Junshi, and Chen Jiapin. “Design of Central Pattern Generator for Humanoid
Robot Walking Based on Multi-Objective GA.” In Proceedings. 2000 IEEE/RSJ International
Conference on Intelligent Robots and Systems (IROS 2000) (Cat. No.00CH37113), 3: 1930–35.
Takamatsu, Japan: IEEE, 2000. https://doi.org/10.1109/IROS.2000.895253.
See Also
Point | Point Cloud | Spatial Contact Force
More About
• “Deep Learning Toolbox”
• “Global Optimization Toolbox”
• “Humanoid Robot” on page 8-50
• “Import a URDF Humanoid Model” on page 6-37
• “Modeling Contact Force Between Two Solids” on page 3-37
• “Reinforcement Learning Toolbox”
• “Use Contact Proxies to Simulate Contact” on page 3-41
8-99
8 Simscape Multibody Examples
This example models a Cartesian 3-D printer. The model allows you to specify the rotational motion of
the motor on each axis to define a printing path. In this example, the printing head moves along the
edges of two letters, S and M, using the predefined rotational motions.
The printer has three linear actuators that drive the motion of the printing head along x-, y-, and z-
directions. These actuators are modeled by the Lead Screw Joint blocks. The lead screw joints
convert the rotational inputs to translational motions.
Model
Subsystems
The 3-D printer has three degrees of freedom and consists of five subsystems: the printing bed,
printer base assembly, gantry assembly, sliding block assembly, and printing head assembly. The
prismatic and lead screw joints constrain the subsystems and permit movements along x-, y-, and z-
axes.
8-100
Cartesian 3-D Printer
Simulation Results
This plot shows the x-, y-, and z-positions of the printing head during the printing.
8-101
8 Simscape Multibody Examples
See Also
Lead Screw Joint | Revolute Joint
More About
• “Joint Actuation Limitations” on page 3-27
• “Motion Sensing” on page 3-54
• “Specifying Joint Actuation Inputs” on page 3-20
8-102
Ratchet Lifter
Ratchet Lifter
This example models a ratchet lifter and demonstrates how to use contact proxies for contact
problems that involve complex geometries.
In this example, as the traveler handle is pumped up and down, the traveler climbs up along the
toothed rack to lift a load. To simplify the contacts between the toothed rack and climbers, the model
represents the rack teeth and climber shaft-pins with proxies, such as cylinders and spheres, and
simulates the contacts between these proxies.
Model
Subsystems
The ratchet lifter consists of five subsystems: the Toothed Rack, Traveler, Neg Climber, Pos Climber,
and Contact subsystems. The Pin Slot Joint block connects the toothed rack and traveler. The
climbers are connected by the traveler and Spring and Damper Force block.
8-103
8 Simscape Multibody Examples
Contact Simulation
The Spatial Contact Force blocks that are used to model the contact forces between the climbers and
rack teeth are housed in the Contact subsystems.
8-104
Ratchet Lifter
The image shows the proxies of the rack teeth and climber cylinders.
8-105
8 Simscape Multibody Examples
Simulation Results
This plot shows the position and velocity of the middle pin of the traveler.
8-106
Ratchet Lifter
See Also
Pin Slot Joint | Spatial Contact Force | Spring and Damper Force
More About
• “Modeling Contact Force Between Two Solids” on page 3-37
• “Solid Cylinder Rolling Down an Incline” on page 3-50
• “Train Humanoid Walker” on page 8-93
• “Use Contact Proxies to Simulate Contact” on page 3-41
• “Zero-Crossing Detection”
8-107
8 Simscape Multibody Examples
This example models a mars rover performing a sample retrieval task using “Simscape Multibody”
and “Robotics System Toolbox”. The rover follows a desired path on a rigid terrain surface, stops at
the target location and uses its manipulator to pick and store a sample from the surface. It uses the
following key features to model different aspects of the application:
• Grid Surface for modeling the rigid terrain surface. (Requires a Simscape™ Multibody™ license)
• Point Cloud and Spatial Contact Force for modeling the contact between the rover wheels and the
rigid terrain. (Requires a Simscape Multibody license)
• Pure Pursuit (Robotics System Toolbox) for path tracking control of the rover. (Requires a
“Robotics System Toolbox” license)
• KinematicsSolver (requires a Simscape Multibody license) and Trapezoidal Velocity Profile
Trajectory (Robotics System Toolbox) (requires a “Robotics System Toolbox” license) for joint
space trajectory planning and control of the rover arm.
• Joint mode configuration (requires a Simscape Multibody license) for modeling the interaction
between the end effector and the sample. For more information about the mode configuration, see
the Mode Configuration section of the Revolute Joint block.
Refer to the model sm_mars_rover.slx to view the subsystems mentioned in this example.
8-108
Modeling and Control of a Mars Rover
This subsystem models the rover, rigid terrain surface and the path planning and controls aspects of
the system.
Rover Subsystem
This subsystem models various components of the rover like chassis, rocker-bogie suspension and
wheels. The CAD parts for the geometry are imported into Simscape Multibody using the File Solid.
The rover's actuators correspond to the six torque-actuated revolute joints mounted to each of the six
wheels for speed control and the four torque-actuated revolute joints mounted to the top of four
8-109
8 Simscape Multibody Examples
corner wheels used for steering. In addition to this, three main components of the suspension
mechanism are also modeled, namely the differential arm, rocker and bogie.
The contact between the wheels and the rigid terrain is modeled using Point Cloud and Grid Surface
contact pairs along with the Spatial Contact Force block. The points on each wheel's grousers are
created using the Point Cloud block.
8-110
Modeling and Control of a Mars Rover
8-111
8 Simscape Multibody Examples
To model a Martian surface, a rigid terrain is created using the Grid Surface block. Refer to the file
rover_rigid_terrain_params.m to setup the parameters needed to create the Grid Surface from
a STL file.
This subsystem models rover's path tracking control system. The path consists of ordered waypoints
in the X-Y plane which the rover is desired to pass through. These waypoints are assumed to be
provided by a high-level path planner and would represent an obstacle free path for the rover. These
waypoints can be loaded using the roverDesiredPath.mat file.
The goal of this subsystem is to first, compute the necessary steering angles and the wheel speeds
needed to follow a desired path and a desired chassis linear velocity and second, to compute the
necessary actuator torques needed to achieve these steering angles and wheel speeds.
For developing the path tracking controller, the following considerations are made:
• Mars rovers are typically assumed to have low forward velocity (on the order of cm/s), therefore
the dynamics of the motion are ignored and the controls problem is approached using kinematic
equations only.[1]
• To simplify the kinematics formulation, the rover is assumed to be moving on a planar surface.[1]
8-112
Modeling and Control of a Mars Rover
• The four corner wheels of the rover have independent steering which can enable the rover to
perform Ackerman steers. Based on this capability, the rover is considered to be using Ackerman
steering.
• The Ackerman steering geometry is simplified by assuming a 2D geometric bicycle model with an
equivalent turn radius. This simplification is done by representing each pair of wheels by a single
wheel located in the middle and a single steering angle corresponding to the turn radius of the
center of the rover.[1][2]
• The front and the rear wheels are considered to be steered symmetrically.
• The wheels are assumed to roll without slipping.
Based on the above considerations, a six wheel rover can be equivalently represented by a geometric
bicycle model.[1]
Pure Pursuit (Robotics System Toolbox) is used for path tracking. This is a geometric algorithm that
computes a target direction angle (α) needed to move the robot from its current position to reach
some look-ahead point in front of the robot.[1]
The steering angles for each of the four corner wheels of the rover are derived in two steps. We first
use the geometric bicycle model and the target direction angle (α) (provided by the Pure Pursuit
Controller) to obtain the bicycle steering angle (δ) and the turn radius (R) as shown below.[2]
8-113
8 Simscape Multibody Examples
2L sin α
δ = tan−1 Ld
L
R = tan δ
where,
Based on the computed bicycle steering angle (δ) and the turn radius of the rover(R), we then obtain
the individual steering angles (δLF , δLB , δRF, δLB) using the Ackerman steering geometry.[3]
L
δLF = tan−1
R−d
8-114
Modeling and Control of a Mars Rover
L
δRF = tan−1
R+d
δLB = -δLF
δRB = -δRF
where,
Based on the Ackerman steering geometry and the turn radius (R), we also obtain the relationship
between the chassis speed (Vc) and the wheel speeds (ω) as shown below [3] :
2
VC L2 + R − d
ωLF = *
Rw R
2
VC L2 + R + d
ωRF = *
Rw R
VC R−d
ωLM = Rw
* R
VC R + d
ωRM = *
Rw R
ωLB = ωLF
ωRB = ωRF
where,
ωLF, ωLM, ωLB, ωRF, ωRM, ωRB : Angular speeds of respective wheels
Vc: Linear speed of the rover chassis
Rw : Radius of the wheel
Once both the steering angles and the wheel speeds are formulated for the desired path and the
desired chassis linear velocity, a PID controller is used to drive the actual steering angles and the
angular rates of the actuators (revolute joints) to their desired values.
8-115
8 Simscape Multibody Examples
Results for path 1 when the rover is moving at ~0.3 m/s on an uneven terrain. More quantities can be
viewed at Rover Sensing subsystem in the model.
8-116
Modeling and Control of a Mars Rover
8-117
8 Simscape Multibody Examples
Results for path 2 when the rover is moving at ~0.3 m/s on an uneven terrain. More quantities can be
viewed at Rover Sensing subsystem in the model.
8-118
Modeling and Control of a Mars Rover
8-119
8 Simscape Multibody Examples
This subsystem models the rover's robot arm and its trajectory planning and control to pick and
collect a sample from the surface.
Rover Arm
The manipulator is modeled as a 6-DOF arm mounted on the front end of the chassis. Its actuators
correspond to six torque-actuated revolute joints. To mimic sensors like encoders, the subsystem
outputs the joint angles from each of the six revolute joints. We use a simplified model for the
interaction between the end effector and the sample that leverages joint mode switching. When the
end effector is sufficiently close to the sample, an initially disengaged 6-DOF joint connecting them
8-120
Modeling and Control of a Mars Rover
becomes engaged. This 6-DOF joint has tight position limits to keep the sample nearly constrained to
the end effector. When the end effector containing the sample comes sufficiently close to the sample
storage location, the engaged 6-DOF joint between the end effector and the sample is disengaged and
an initially disengaged 6-DOF joint between the sample and the storage location is engaged. This 6-
DOF joint also has tight position limits to keep the sample nearly constrained to the storage location
on the chassis.
The manipulator planning and control subsystems are enabled once the rover stops at the target
position. Once the rover stops, the sample's location with respect to the arm base is computed using a
Transform Sensor block (to mimic the camera on board).
8-121
8 Simscape Multibody Examples
8-122
Modeling and Control of a Mars Rover
To plan the trajectory of the end effector, six waypoints are defined in the task space as shown above.
Four of these waypoints (1,2 5 and 6) are precomputed and derived from the geometry of the rover
chassis and the location of the storage unit. These can be loaded from
roverArmTaskSpaceConfig.mat. Waypoints 3 and 4 are computed based on the sample position
obtained from the transform sensor block. Using these six waypoints, the trajectory of the end
effector is planned via a joint space trajectory planning approach. The planner first converts all the
six task space waypoints to joint space waypoints using the inverse kinematics module (refer to
sm_mars_rover_arm_ik.m implemented using KinematicsSolver). These joint space waypoints
are then used by a MATLAB function block Task Scheduler to advance the arm through the series of
modes as shown above. The scheduler advances the end effector to the next mode when it reaches a
target position within some tolerance value. Each task from the scheduler is an input to the
Trapezoidal Velocity Profile Trajectory (Robotics System Toolbox) block, which computes a smooth
trajectory between each waypoint in the joint space.
Once a joint space trajectory is generated, a PID controller is used to drive the actual positions of the
actuators to their desired values.
Results showing the end effector trajectory passing through the desired waypoints and the
comparison between desired and actual actuator joint angles. More quantities can be viewed at
Manipulator Sensing subsystem in the model.
8-123
8 Simscape Multibody Examples
8-124
Modeling and Control of a Mars Rover
References
[1] Filip, Jan, Martin Azkarate, and Gianfranco Visentin. "Trajectory control for autonomous planetary
rovers." In 14th Symposium on Advanced Space Technologies in Robotics and Automation (ASTRA).
2017.
[2] Snider, Jarrod M. "Automatic steering methods for autonomous automobile path tracking."
Robotics Institute, Pittsburgh, PA, Tech. Rep. CMU-RITR-09-08 (2009).
[3] X. Wu, L. Yang and M. Xu, "Speed following control for differential steering of 4WID electric
vehicle," IECON 2014 - 40th Annual Conference of the IEEE Industrial Electronics Society, 2014, pp.
3054-3059, doi: 10.1109/IECON.2014.7048945.
See Also
KinematicsSolver | Grid Surface | Point Cloud
8-125
8 Simscape Multibody Examples
This example demonstrates how a multibody system can be built using an interactive MATLAB® app.
In this example an application for exploring the design space of a multibody system is shown. The
system here is a mobile manipulator with four omni-directional wheels.
MATLAB App Designer is used to build a GUI that allows the user to vary various parameters
governing the mobile robot design, and to see an interactive visualization of the robot as the
parameters are changed. It also has a button to create a Simulink® model based on the current
design parameters.
Each parameter change triggers a call to the custom function makeMobileRobot.This is the top level
function which calls different sub functions like createMobileRobotChassis,
createOmniDirectionalWheel and createRobotArm to create and connect the various
components of the mobile robot. Each of these custom functions use different classes and methods
under the simscape.multibody.* package for building the different components.
We can also build this system by setting up the parameters directly in MATLAB in a programmatic
way and then calling the function makeMobileRobot. Refer to the script buildMobileRobot.m to
learn more.
openExample("sm/MobileRobotBuilderAppExample");
run("buildMobileRobotApp.mlapp");
8-126
Creating a Mobile Robot Using a MATLAB App
8-127
8 Simscape Multibody Examples
App Interface
See Also
simscape.multibody.Multibody
8-128
Creating a Robotic Gripper Multibody in MATLAB
This example constructs a robotic gripper multibody in MATLAB®. It demonstrates how various
classes under simscape.multibody.* package can be used to build a hierarchical multibody system.
The gripper has a palm which is a RigidBody component and has fingers which are themselves
Multibody components. Each of the articulated finger multibody comprises of rigid finger segments
connected via revolute joint knuckles.
import simscape.Value;
% Number of fingers
numFingers = 5;
% Palm dimensions
palmDims = Value([8 40], 'mm');
To perform any simulation workflows, a simulink model can be created from the gripper multibody
object using its makeBlockDiagram method.
makeBlockDiagram(gripper,gripper_op,'gripperModel');
8-129
8 Simscape Multibody Examples
See Also
simscape.multibody.Multibody | simscape.multibody.RigidBody
8-130
Creating a Four Bar Multibody Mechanism in MATLAB
This example constructs a four bar mechanism in MATLAB® using Simscape™ Multibody™. It
demonstrates various classes under simscape.multibody.* package to build a multibody system in
MATLAB.
Open the model and use a custom function fourbar to construct the four-bar multibody with user
specified link lengths. Each parameter is expected to be a Simscape Value, specifying a scalar length.
The four-bar is constructed so that the X-Y plane is the plane of motion, with gravity in the -Y
direction. Output op is an operating point that sets the bottom left joint angle to a nominal value with
high priority.
cmb = compile(fb);
visualize(cmb,computeState(cmb,op),"vizFourBar");
8-131
8 Simscape Multibody Examples
Once the four bar mechanism is created, we can also perform some analysis on it like computing and
plotting the trajectory of the top (distal) link of the specified four-bar mechanism. The function
fourBarMotionPlot plots the trajectory of the top link over a full 360 deg range of the crank angle
(when the left link is a crank of the four bar). This function varies the crank angle over a full 360-deg
range in steps of 1 deg. The trajectory of the midpoint of the top link is plotted over these 1-deg steps
to form a (typically) smooth curve. The coordinates along this curve are relative to the world frame.
fourBarMotionPlot(fb);
8-132
Creating a Four Bar Multibody Mechanism in MATLAB
See Also
simscape.multibody.Multibody
8-133
8 Simscape Multibody Examples
This example constructs a simple pendulum in MATLAB®. It demonstrates various classes under the
simscape.multibody.* package to build a simple multibody system in MATLAB.
The pendulum consists of a single link suspended at one end from a pivot. It is considered to swing in
the X-Y plane with gravity in the -Y direction. The zero position corresponds to the pendulum hanging
straight down and the positive velocities correspond to counter-clockwise motion about the pivot
when the pendulum is viewed from the +Z axis.
The following sections of code build the simple pendulum. First, import MATLAB packages so the
simscape.multibody.and Simscape. qualifiers are not needed in front of class names.
linkDimensions=Value([20 2 1],"cm");
link=RigidBody;
color=[0 1 1];
addComponent(link,"Body","reference",Solid(Brick(linkDimensions),SimpleVisualProperties(color)));
addFrame(link,"pin","reference", ...
RigidTransform(StandardAxisTranslation(linkDimensions(1)/2,Axis.NegX)));
addConnector(link,"pin");
Construct a rigid transform that aligns the +X axis of the follower frame with the -Y direction of the
base frame. This is used to position the pivot so that the pendulum swings in the X-Y plane and that it
hangs straight down at the zero position:
Create the multibody and modify gravitational acceleration to be in the -Y direction instead of the
default -Z direction:
pendulum=Multibody;
pendulum.Gravity=circshift(pendulum.Gravity,-1);
addComponent(pendulum,"World",WorldFrame);
addComponent(pendulum,"Rotator",rotator);
addComponent(pendulum,"Link",link);
addComponent(pendulum,"Pivot",RevoluteJoint);
Make appropriate connections between components. The connectVia method on class Multibody is
used to connect two frames together across a joint:
connect(pendulum,"World/W","Rotator/B");
connectVia(pendulum,"Pivot","Rotator/F","Link/pin");
Construct an operating point to position the pendulum link 30 degrees counter-clockwise from the
vertical, and rotating counter-clockwise at 1 revolution/sec:
op = OperatingPoint;
op("Pivot/Rz/q")=Target(simscape.Value(30,"deg"),"High");
op("Pivot/Rz/w")=Target(simscape.Value(1,"rev/s"),"High");
8-134
Create a Simple Pendulum in MATLAB
compiledPendulum=compile(pendulum);
state=computeState(compiledPendulum,op);
visualize(compiledPendulum,state,"simple_pendulum");
makeBlockDiagram(pendulum,op,"simple_pendulum")
See Also
simscape.multibody.Multibody | simscape.multibody.RigidBody
More About
• “Simple Link”
8-135
8 Simscape Multibody Examples
This example shows how to model a mechanism that contains different types of joints in MATLAB®. It
also shows a way of setting operating point targets for the joint primitives of the joints.
Create a Multibody object and add the necessary components, such as WorldFrame and Gravity.
mb = Multibody;
addComponent(mb, 'World', WorldFrame());
% Zero gravity
mb.Gravity = Value([0 0 0], 'm/s^2');
Add different types of joints to the Multibody object using the custom function addJoint.
To create operating points that specify the position or velocity targets of a joint, get the path to each
of the joint primitives. The Multibody object provides a method jointPrimitivePaths to list the
paths to all the joint primitives in the mechanism. Use this list as one of the inputs to the custom
8-136
Create a Mechanism with Different Joints in MATLAB
function randomOpPoint that creates an operating point specifying random velocities for all the
joints.
jointPrimPaths = jointPrimitivePaths(mb);
op = randomOpPoint(jointPrimPaths, Value(90, 'deg/s'), Value(1, 'cm/s'));
After you create the operating point, compile the Multibody object and use the computeState
method to view if the above random velocity targets are achieved.
cmb = compile(mb);
state = computeState(cmb,op)
state =
State:
Status: Valid
Assembly diagnostics:
x
Revolute_Joint
Joint successfully assembled
Rz
Free position value: +0 (deg)
High priority velocity target +23.5864 (deg/s) achieved
Prismatic_Joint
Joint successfully assembled
Pz
Free position value: +0 (m)
High priority velocity target +0.210897 (cm/s) achieved
Spherical_Joint
Joint successfully assembled
S
Free position value: [+0 +0 +0], +0 (deg)
High priority velocity target [-80.4494 -62.6214 -85.1939] (deg/s) achieved
LeadScrew_Joint
Joint successfully assembled
LSz
Free position value: +0 (deg)
High priority velocity target +0.0848914 (cm/s) achieved
ConstantVelocity_Joint
Joint successfully assembled
CV
High priority position target +90 (deg) achieved
High priority velocity target [-5 +10] (deg/s) achieved
Universal_Joint
Joint successfully assembled
Rx
Free position value: +0 (deg)
High priority velocity target +73.9708 (deg/s) achieved
Ry
Free position value: +0 (deg)
High priority velocity target +10.0194 (deg/s) achieved
Rectangular_Joint
Joint successfully assembled
Px
Free position value: +0 (m)
High priority velocity target +0.162366 (cm/s) achieved
Py
8-137
8 Simscape Multibody Examples
8-138
Create a Mechanism with Different Joints in MATLAB
To perform any simulation workflows, generate the Simulink® model of the mechanism by using the
makeBlockDiagram method.
makeBlockDiagram(mb,op,'jointZooModel');
8-139
8 Simscape Multibody Examples
See Also
simscape.multibody.Multibody | simscape.multibody.RigidBody |
simscape.multibody.Joint | compile
8-140
Perform Forward and Inverse Kinematics on a Five-Bar Robot
This example shows how to use the KinematicsSolver object to perform forward kinematics (FK)
and inverse kinematics (IK) on a five-bar robotic mechanism. First, the example demonstrates how to
perform FK analyses to calculate a singularity-free workspace for a five-bar robot. Then the example
shows how to perform IK analyses to compute the motor angles that correspond to an end-effector
trajectory within that workspace.
A five-bar robot, which is also called a five-bar planar manipulator, is a two-degree-of-freedom parallel
mechanism. In this example, the robot has four equal-length links that cannot collide with each other.
The robot uses two stepper motors to drive the proximal links to move the pen.
The five-bar robot has four configuration space regimes: --, -+, ++, and +-. As shown in the image,
each sign indicates the sign of the offset angle between the corresponding proximal and distal links.
The active revolute joints a and b are directly controlled by the motors, and the passive revolute
joints c and d connect the proximal and distal links.
8-141
8 Simscape Multibody Examples
Configurations in which one or both of the arms become fully extended cause the end effector to lose
at least one of its degrees of freedom. These configurations correspond to kinematic singularities and
occur when the robot transitions from one regime to another. To avoid the kinematic singularities in
the FK analysis, this example only studies the five-bar robot workspace in the +- regime.
This section demonstrates how to perform an FK analysis to compute a singularity-free workspace for
the pen that corresponds to a set of motor angles. Specifically, the example assigns the active joint
angles of the robot as target variables and the x and y coordinates of the pen as output variables. The
example also assigns the passive joints as initial guess variables, which are used to help bias the
solutions towards the +- regime.
1. To perform the FK analysis, first load the five-bar robot model into memory and create a
KinematicsSolver object (fk) for the model.
mdl = "sm_five_bar_robot";
load_system(mdl);
fk = simscape.multibody.KinematicsSolver(mdl);
2. To specify and study the relationships between the pen, world frame, active joints, and passive
joints of the robot, you need to create frame variables that correspond to the position of the pen with
respect to the world frame. Note that you don't need to create joint variables because they are
created automatically when the object is constructed.
8-142
Perform Forward and Inverse Kinematics on a Five-Bar Robot
Add a group of three translational frame variables for the pen to fk. Specify the world frame as the
base and the Tip frame of the pen as the follower. Name the frame variable group Pen.
base = mdl + "/World Frame/W";
follower = mdl + "/Five Bar Robot/Pen/Pen/Tip";
addFrameVariables(fk,"Pen","Translation", base, follower);
3. Assign the position-based joint variables of the active joints (j5.Rz.q and j4.Rz.q) as targets. To
find the IDs of the position-based joint variables, use the jointPositionVariables object function.
jointPositionVariables(fk)
ans=5×4 table
ID JointType BlockPath
_________ ________________ ____________________________________________________________
targetIDs = ["j5.Rz.q";"j4.Rz.q"];
addTargetVariables(fk,targetIDs);
To find the IDs of the frame variables, use the frameVariables object function.
frameVariables(fk)
ans=3×4 table
ID Base Follower
___________________ _________________________________ _________________________________
outputIDs = ["Pen.Translation.x";"Pen.Translation.y";"j1.Rz.q";"j2.Rz.q"];
addOutputVariables(fk,outputIDs);
5. Assign the joint variables of the passive joints (j1.Rz.q and j2.Rz.q) as guesses.
guessIDs = ["j1.Rz.q";"j2.Rz.q"];
addInitialGuessVariables(fk,guessIDs);
6. The image is a sketch of the five-bar robot. The angles of the active joints are θa and θb, and the
passive joints are θc and θd. Use a nested for loop to compute the workspace of the pen for a set of
active joint angles that vary between [95, 150] and [30, 85] degrees, respectively. To ensure that the
robot is in the +- regime, use [50 -50] degrees as the initial values for the guess variables (j1.Rz.q
and j2.Rz.q) and then use the latest values of the guess variables to guide the next FK solution.
8-143
8 Simscape Multibody Examples
% Calculate the robot's workspace for the given theta_a and theta_b
for i = 1:length(theta_a)
for j = 1:length(theta_b)
targets = [theta_b(j),theta_a(i)];
[outputVec,statusFlag] = solve(fk,targets,guesses);
if statusFlag == 1 % Save a solution if its statusFlag is 1
ik_data(index,1:length(outputIDs)) = outputVec;
index = index + 1;
guesses = [outputVec(3),outputVec(4)]; % Update next guess with last solution
end
end
end
7. Plot the angles of the passive joints to verify if the five-bar robot is in the +- regime. If the robot is
in the +- regime, the values of θc and θd are consistently positive and negative, respectively.
figure
plot(ik_data(1:index-1,3),"b","LineWidth",2); % Note that the total number of the solutions that
hold on
8-144
Perform Forward and Inverse Kinematics on a Five-Bar Robot
plot(ik_data(1:index-1,4),"k","LineWidth",2);
hold off
The plot shows that the five-bar robot is in the +- regime. Moreover, the computed workspace is
singularity-free because the values of θc and θd are away from zero.
8. Plot the workspace data on the top-view image of the five-bar robot.
hold on
8-145
8 Simscape Multibody Examples
axis equal
axis([-1 1 -1 1]);
hold off
In this section, the example shows how to perform an IK analysis to compute the motor angles that
correspond to an end-effector trajectory. Specifically, the example assigns the translational x and y
components of the pen as target variables and assigns the motor angles as output variables. Then the
example computes the motor angles for a trajectory of the pen. To ensure the robot is in the +-
regime, use the active and passive joint angles as guesses to bias the IK solutions. Note that you need
to run the FK section before running this section.
1. Define a circular end-effector trajectory within the previously calculated workspace. Save the
coordinates of the circle for the IK analyses.
figure
% Plot the calculated workspace as blue dots on the top-view image of the five-bar robot
image(x,y,C)
hold on
plot(ik_data(:,1),ik_data(:,2),"b.")
8-146
Perform Forward and Inverse Kinematics on a Five-Bar Robot
2. To perform the IK analysis, first create a KinematicsSolver object (ik) for the model.
ik = simscape.multibody.KinematicsSolver(mdl);
3. Create frame variables for the position of the pen with respect to the world frame and add them to
the object (ik). You can reuse the base and follower variables from the FK section.
4. Assign the variables that correspond to the translational x and y components of the pen
(Pen.Translation.x and Pen.Translation.y) as targets. To find the IDs of the frame variables,
use the frameVariables object function.
frameVariables(ik)
8-147
8 Simscape Multibody Examples
ans=3×4 table
ID Base Follower
___________________ _________________________________ _________________________________
targetIds = ["Pen.Translation.x";"Pen.Translation.y"];
addTargetVariables(ik,targetIds);
• The position-based joint variables of the active joints (j5.Rz.q and j4.Rz.q)
• The position-based joint variables of the passive joints (j1.Rz.q and j2.Rz.q)
To find the IDs of the position-based joint variables, use the jointPositionVariables object
function.
jointPositionVariables(ik)
ans=5×4 table
ID JointType BlockPath
_________ ________________ ____________________________________________________________
outputIds = ["j5.Rz.q";"j4.Rz.q";"j1.Rz.q";"j2.Rz.q"];
addOutputVariables(ik,outputIds);
6. Use a for loop to implement the IK analysis. Specifically, use the for loop to assign the
coordinates of the predefined trajectory to the pen and calculate the corresponding motor angles.
7. Plot the passive joints of the robot to see if the robot is in the +- regime.
8-148
Perform Forward and Inverse Kinematics on a Five-Bar Robot
The plot shows that the robot is not always in the +- regime.
During the IK analysis, the Kinematics Solver Viewer opens and shows an animation of the process.
The animation also shows that the result is not desired because the five-bar robot is not always in the
+- regime. The image shows a snapshot of the animation in the ++ regime.
8-149
8 Simscape Multibody Examples
8. To help ensure that all solutions stay in the +- regime, assign the joint variables of the passive
(j1.Rz.q and j2.Rz.q) and active (j5.Rz.q and j4.Rz.q) joints as guesses to bias the IK
solutions.
guessIds = ["j1.Rz.q";"j2.Rz.q";"j5.Rz.q";"j4.Rz.q"];
addInitialGuessVariables(ik,guessIds);
Use [50 -50 45 135] degrees as initial values for the guess variables and use the latest values of the
guess variables to guide the next IK solution.
guesses = [50 -50 45 135]; % Assign initial guesses for passive and active joints
N = length(coordinates_x);
index_in_ik = 1;
ik_data = zeros(N,length(outputIds)); % Allocate memory for the variable
for ind = 1:N
targets = [coordinates_x(ind), coordinates_y(ind)]; % Use the x and y coordinates of the pres
[outputVec_ik,statusFlag_ik] = solve(ik,targets, guesses);
if statusFlag_ik == 1
viewSolution(ik) % View the solution in the Kinematics Solver Viewer
ik_data(index_in_ik,1:length(outputIds)) = outputVec_ik; % Save the rotations of the moto
index_in_ik=index_in_ik+1;
guesses = [outputVec_ik(3) outputVec_ik(4) outputVec_ik(1) outputVec_ik(2)]; % Update nex
else
error("Did not hit targets");
end
end
closeViewer(ik);
The plot indicates that the passive joint angles are always well away from zero and are always in the
+- regime. Therefore, this set of motor angles corresponds to the end effector moving in a smooth
motion along the circular trajectory without passing through any kinematic singularities.
8-150
Perform Forward and Inverse Kinematics on a Five-Bar Robot
plot(ik_data(:,3),"b","LineWidth",2);
hold on
plot(ik_data(:,4),"k","LineWidth",2);
hold off
title("Passive Joint Angles")
xlabel("Index")
ylabel("Angle (Degrees)")
legend("Joint c","Joint d")
See Also
KinematicsSolver | frameVariables | initialGuessVariables | jointPositionVariables
| outputVariables | targetVariables | addFrameVariables | addInitialGuessVariables |
addOutputVariables | addTargetVariables | solve | viewSolution | closeViewer
More About
• “Pick and Place Robot Using Forward and Inverse Kinematics” on page 8-62
8-151
8 Simscape Multibody Examples
This example models a package delivery quadcopter. The quadcopter takes off from the launchpad
and delivers the package to the drop-off location while following a desired trajectory.
Model
The quadcopter comprises of a chassis and four motor-propeller pairs, each spinning alternately in
clockwise and counterclockwise direction. The quadcopter chassis has four identical arms rigidly
attached to the top and bottom plates using the Rigid Transform block. The motor comprises of a
motor base, a motor shaft which is connected to the motor base via revolute joint and a motor cap.
The propeller is rigidly attached to the motor shaft. The motor base is rigidly connected to the arm
using the Rigid Transform Block. Based on the rotational speed of the propeller, the thrust coefficient
and thrust generated by each propeller are calculated. The package is attached to the quadcopter via
weld joint. Whenever the quadcopter carrying the package gets in the proximity of the drop-off
location, the MATLAB Function block: Package Delivery Quadcopter/Package Release Trigger
disengages the weld joint to deliver the package. The Spatial Contact Force blocks are used to model
the contact forces between the package and the ground surface.
8-152
Package Delivery Quadcopter
The desired trajectory of the quadcopter is computed using the MATLAB Function block: Trajectory
Generation and Control/Trajectory Generator. The waypoints between the launchpad and the drop-off
location are prescribed. Given the current time, the block returns a 5th order polynomial trajectory
(desired position and velocity) for the quadcopter. The trajectory between two successive waypoints is
computed as a piecewise 5th order polynomial such that the initial and final velocities and
accelerations at the waypoints are all zero. Whenever the quadcopter gets in the proximity of a
waypoint, the desired trajectory is computed between the current and the next waypoint. The
quadcopter hovers when it reaches the drop-off location and delivers the package. The Trajectory
Generation and Control/Position and Attitude Controller and Trajectory Generation and Control/
Altitude Controller subsystems generate the control signals that drives the actual attitude and
altitude of the quadcopter to the desired values. The Trajectory Generation and Control/Motor Mixer
subsystem uses the attitude and the altitude control signals to compute the desired rotational speed
for the quadcopter motors.
8-153
8 Simscape Multibody Examples
A cascade control is used to drive the position of the quadcopter to the desired state. The inner loop
contains a PID controller which controls the attitude dynamics of the quadcopter. A backstepping
controller inside MATLAB Function block: Position and Attitude Controller/Position Controller
computes the desired roll and pitch angles necessary to achieve the control objective.
The plot below shows the actual and desired position of the Quadcopter
8-154
Package Delivery Quadcopter
References : [1] Das, A., Lewis, F. and Subbarao, K., 2009. Backstepping approach for controlling a
quadrotor using lagrange form dynamics. Journal of Intelligent and Robotic Systems, 56(1),
pp.127-151.
See Also
6-DOF Joint
8-155
8 Simscape Multibody Examples
This example highlights key concepts and recommended steps for building a multibody system in
MATLAB®. A simple design problem has been chosen to serve this purpose. The following section
describes the design problem and subsequent sections discuss how to solve it.
Problem Description
The problem is simplified to aiming within the plane of the mechanism. The figure shows the
schematic sketch of the mechanism and only captures the essentials of how the mechanism operates
(which is usually the case during the early stages of a design process). The link C can slide on the link
A. A motor applies torque τ at the revolute joint Ri and the task is to track a particular trajectory of
the revolute angle β.
A key principle to follow is to begin with a simple approximation to get the basic mechanism working
and then in subsequent iterations add complexity to the model. The recommended model building
process can be broken down into the following steps:
8-156
How to Build a Multibody System in MATLAB
9 Add details to the individual rigid bodies to make the model a more accurate representation of
the actual mechanism.
In addition, the rigid body D is rigidly connected to the world frame W since it is motionless.
You define a rigid body by specifying its geometry, mass properties and interface with other parts.
Each rigid body is identified and defined in isolation. In the above example, the mechanism is
composed of four rigid bodies: A, B, C and D.
Once the shape of the object is defined and its density is specified, Simscape™ Multibody™ can
compute the inertia automatically. Instead of defining the fairly complicated shape shown above, as a
first approximation, you can define the shape of the rigid body as a simple cylinder.
8-157
8 Simscape Multibody Examples
The above shown rigid body can be defined in MATLAB using a high-level function like
dcrankaim_approx_body_A which makes use of objects like simscape.multibody.RigiBody,
simscape.mulitbody.Solid etc. This function takes input arguments like length, radius, density and
color and returns a rigidbody object containing a cylindrical solid with one frame at the end of the
link and the other at the center.
radius = simscape.Value(2,'cm');
length = simscape.Value(1,'m');
color = [0 0 1];
density = simscape.Value(2700,'kg/m^3') ;
bodyA = dcrankaim_approx_body_A(length,radius,density,color);
To understand the use of these different objects, let us take a look at the implementation of this
function. In the dcrankaim_approx_body_A , we first import the packages needed to use Simscape
Value, OperatingPoint and Simscape Multibody MATLAB classes.
import simscape.Value simscape.op.* simscape.multibody.*;
We then create an object of the class RigidBody. The RigidBody class is a container which can
comprise of solids, inertias, graphics, frames (which act as interface to connect it to the other parts of
Multibody system) and other rigid body objects.
link = RigidBody;
We then define and add a cylindrical solid to approximate the shape of BodyA. This is created using
the cylindrical geometry, density, and its visual properties.
cylinder = Solid(Cylinder(radius, length),...
UniformDensity(density),...
SimpleVisualProperties(color));
Once we have defined the shape (first approximation) of the rigid body A and specified its density. We
now has enough information to compute the inertial properties of the solid. You can define a simply
shaped geometry in MATLAB using the following geometry classes.
• simscape.multibody.Brick
• simscape.multibody.Sphere
• simscape.multibody.Cylinder
• simscape.multibody.Ellipsoid
• simscape.multibody.RegularExtrusion
• simscape.multibody.GeneralExtrusion
• simscape.multibody.Revolution
These geometry objects are contained in the Solid class. Solids are characterized by geometry,
inertia and visual properties and by using it with the above geometry objects, it allows us to create
simple solids of different shapes. Solids are always rigid and always have an implicit reference frame,
and the geometry and inertia are specified relative to this frame.
The interface of a rigid body is established by defining frames attached to the rigid body. A rigid body
is connected to other parts of the mechanism via the rigidly attached frames. In Simscape Multibody,
joints establish a time-varying relationship between two frames. For instance, the Revolute Joint
establishes the relationship that the Z-axes of the attached frames are parallel and the origins of the
8-158
How to Build a Multibody System in MATLAB
frames are coincident. The Prismatic Joint establishes the relationship that the Z-axes of the
attached frames are collinear and the X and Y axes are always parallel. Note that the frames
themselves are defined independently of the joint; the joint only establishes a relationship between
the already existing frames. Note also that the Z-axis is the axis of rotation in the case of the revolute
joint and is the axis of sliding in the case of the prismatic joint. This information is essential when we
define the interface of a rigid body by defining the frames rigidly attached to it.
In this example, the rigid body A has a cylindrical hole at one end that fits onto a peg so that A can
rotate about the axis of the cylindrical hole. This suggests that a frame should be defined at the hole
center with its Z-axis aligned with the axis of the hole (the axis of rotation). This frame is labelled as
F AD above. The choice of orientation of the X and Y axes of F AD partly determines the zero
configuration of the joint to which F AD would be connected (see discussion on Zero Configuration
below). A also acts as the shaft on which part C slides. This suggests that a frame should be defined
at the center of A (an arbitrarily selected position) with its Z-axis aligned along the length of A (along
the direction of sliding). This frame is labelled as F AC above. The frames F AD and F AC define the
interface for the rigid body A.
The following code shows how the frames are defined and added to the rigidbody A in the function
dcrankaim_approx_body_A.
The frames F AC and F AD are defined with respect to the reference frame of the rigidbody.
mb = Multibody;
addComponent(mb,'BodyA',bodyA);
cmb = compile(mb);
visualize(cmb,computeState(cmb,OperatingPoint),'BodyVizA');
Now let us consider the rigid body B. The shape of the rigid body can again be approximated with a
simple cylinder. The rigid body has cylindrical holes at both ends that fit onto pegs. The rigid body B
can rotate about either hole axis. This suggests that two frames should be defined: one at each hole
center with its Z-axis aligned with the axis of the hole.
8-159
8 Simscape Multibody Examples
The function dcrankaim_approx_body_B shows how the RigidBody, Solid and RigidTransform
objects have been used to define the shape, inertia and interface of the rigid body B.
radius = simscape.Value(2,'cm');
length = simscape.Value(1,'m');
color = [0 0 1];
density = simscape.Value(2700,'kg/m^3') ;
bodyB = dcrankaim_approx_body_B(length,radius,density,color);
mb = Multibody;
addComponent(mb,'BodyB',bodyB);
cmb = compile(mb);
visualize(cmb, computeState(cmb,OperatingPoint),'BodyVizB');
A similar approach can be taken for building a first approximation of the rigid body D.
This rigid body has a cylindrical hole that slides on a peg. It also has a peg about which another body
can rotate. This suggests the need to define two frames: one at the center of the hole with its Z-axis
along the axis of the hole, and the other at the center of the peg with its Z-axis along the axis of the
peg. These are marked as FCA and FCB above.
8-160
How to Build a Multibody System in MATLAB
The shape of the rigid body C can be approximated with a simple cuboid. In the first approximation of
the rigid body, the offset between the origins of frames FCB and FCA can also be made zero. This
results in the simplified representation of rigid body as shown below.
The function dcrankaim_approx_body_C shows how the RigidBody, Solid and RigidTransform
objetcs have been used to define the shape, inertia and interface of the rigid body C.
All the individual bodies were built in isolation. The process of assembly involves establishing
relationships (using joints) between the frames attached to the rigid bodies. The following joints
establish all of the necessary relationships between the frames to assemble the mechanism.
The function dcrank_aiming_mechanism_v1 shows how objects like Mulitbody and Joints are
used to assemble individual rigid bodies. The function takes the length of each of the cylindrical links
BodyA, BodyC, BodyD and the dimensions of the slider link BodyB as the input arguments and
returns the multibody object as the output.
bodyA_l = Value(80,'cm');
bodyB_l = Value(30, 'cm');
bodyC_dim = Value([10, 8, 8], 'cm');
bodyD_l = Value(40, 'cm');
dcrankAimMech_mb = dcrank_aiming_mechanism_v1(bodyA_l,bodyB_l,bodyC_dim,bodyD_l);
To understand how this function assembles the mechanism, let us look at some its implementation.
dcrankAimMech_mb = Multibody;
8-161
8 Simscape Multibody Examples
We then add the World frame to the Multibody by using its addComponent method.
addComponent(dcrankAimMech_mb,'World', WorldFrame());
Then BodyA , BodyB , BodyC and BodyD are created using the RigidBody object, as discussed in the
above sections.
% add body_a
bodyA_l = Value(80,'cm');
bodyA_r = simscape.Value(2,'cm');
bodyA_color = [1 0.6 0];
bodyA_density = simscape.Value(2700,'kg/m^3') ;
body_a = dcrankaim_approx_body_A(bodyA_l,bodyA_r,bodyA_density,bodyA_color);
% add body_b
bodyB_l = Value(30, 'cm');
bodyB_r = simscape.Value(2,'cm');
bodyB_color = [0 0 1];
bodyB_density = simscape.Value(2700,'kg/m^3') ;
body_b = dcrankaim_approx_body_B(bodyB_l,bodyB_r,bodyB_density,bodyB_color);
% add body_c
bodyC_dim = Value([10, 8, 8], 'cm');
bodyC_color = [0 1 0];
bodyC_density = simscape.Value(2700,'kg/m^3') ;
body_c = dcrankaim_approx_body_C(bodyC_dim,bodyC_density,bodyC_color);
% add body_d
bodyD_l = Value(40, 'cm');
bodyD_r = simscape.Value(2,'cm');
bodyD_color = [0.2 0.2 0.2];
bodyD_density = simscape.Value(2700,'kg/m^3') ;
body_d = dcrankaim_approx_body_D(bodyD_l,bodyD_r,bodyD_density,bodyD_color);
Once all the 4 bodies are created, we add them to the Multibody container object using its
addComponent method.
addComponent(dcrankAimMech_mb,'body_a', body_a);
addComponent(dcrankAimMech_mb,'body_b', body_b);
addComponent(dcrankAimMech_mb,'body_c', body_c);
addComponent(dcrankAimMech_mb,'body_d', body_d);
The mechanism has 4 joints - 3 revolutes and 1 prismatic. We create and add them using the
RevoluteJoint and PrismaticJoint objects.
rJoint = RevoluteJoint;
pJoint = PrismaticJoint;
addComponent(dcrankAimMech_mb,'Ro', rJoint);
addComponent(dcrankAimMech_mb,'Ri', rJoint);
addComponent(dcrankAimMech_mb,'Rg', rJoint);
addComponent(dcrankAimMech_mb,'P', pJoint);
Now, we have all the required components for the mechanism. However, we still need to connect
these components. We add these connections using the connect and connectVia methods of the
Multibody object by connecting the appropriate RigidBody frames to the Base and Follower frames
of the appropriate Joints.
8-162
How to Build a Multibody System in MATLAB
connect(dcrankAimMech_mb,'World/W', 'body_d/Fdw');
connectVia(dcrankAimMech_mb,'Ro', 'body_d/Fda', 'body_a/Fad');
connectVia(dcrankAimMech_mb,'P', 'body_a/Fac', 'body_c/Fca');
connectVia(dcrankAimMech_mb,'Rg', 'body_b/Fbc', 'body_c/Fcb');
connectVia(dcrankAimMech_mb,'Ri', 'body_d/Fdb', 'body_b/Fbd');
The effort that went into carefully defining the interfaces of all of the rigid bodies (i.e. the frames
attached to them) made it very easy to complete the mechanism by simply adding and connecting the
joints between the appropriate frames. However, at this point the resulting assembly may or may not
be in the desired configuration since the mechanism can be assembled into multiple configurations.
The function dcrankaim_assembly_failure shows the assembled mechanism.
dcrankAimMech_mb = dcrankaim_assembly_failure(bodyA_l,bodyB_l,bodyC_dim,bodyD_l);
In the function above, an intentional mistake has been made in the definition of the frame FCA
attached to rigid body C. This causes the assembly to fail. The figure below shows the desired and
actual orientations of the frame FCA.
The orientation of FCA has to be corrected by a rotation of 90 deg about the Z-axis. To identify this
issue, we first compile the multibody using the compile method of the Multibody object.
compiled_mb = compile(dcrankAimMech_mb);
Then we use the computeState method of the compiled multibody object for a default
OperatingPoint.
state = computeState(compiled_mb,simscape.op.OperatingPoint)
state =
State:
Status: PositionViolation
Assembly diagnostics:
x
Ro
Joint successfully assembled
Rz
Free position value: +0.000377073 (deg)
Free velocity value: +0 (deg/s)
8-163
8 Simscape Multibody Examples
P
Joint successfully assembled
Pz
Free position value: +0.3 (m)
Free velocity value: +0 (m/s)
Ri
Joint successfully assembled
Rz
Free position value: +0.00087955 (deg)
Free velocity value: +0 (deg/s)
Rg
Joint not assembled due to a position violation.
Rz
Free position value: N/A (deg)
Free velocity value: N/A (deg/s)
The State object returned by the computeState method indicates if the attempt to compute a state
was successful or not. In this case, it reported indicating that there is a PositionViolation and that
the joint Rg is not assmebled due to a position violation. In this example it is in fact true that an error
was made in the specification of the frame FCA which would cause a position violation.
Changing the parameters of the rigid transform ax_fca.BaseAxis2, from Axis.NegZ to Axis.PosZ in
dcrankaim_approx_body_C_assembly_failure fixes the problem and allows the assembly to
succeed.
The Zero Configuration of a joint is defined as the relative position and orientation between the
base and follower frames when all of the joint angles are zero. For almost all of the joints in Simscape
Multibody, the base and follower frames are identical in the zero configuration: their origins are
coincident, and their axes are aligned. One defines the relative position and orientation between two
bodies connected by a joint when the joint angles are zero by adjusting the positions and orientations
of the base and follower frames on their respective bodies.
Consider, for example, the rigid bodies B and C and the joint Rg connecting them. The frames FCB
and FBC are the base and follower frames of the joint Rg. The figure below shows how different
choices of orientations for the frame FCB attached to rigid body C result in different assembled
configurations when the joint angle is zero. The choice of orientation of the frames must be made
with the desired zero configuration in mind.
8-164
How to Build a Multibody System in MATLAB
8-165
8 Simscape Multibody Examples
In the aiming mechanism, the choice of frame orientations leads to a default assembled configuration
in which the central axes of all of the bodies lie along the same line.
Visualize the mechanism created using dcrank_aiming_mechanism_v1 (contains the fix for the
errors found in dcrankaim_approx_body_C_assembly_failure ) using the following code.
dcrankAimMech_mb = dcrank_aiming_mechanism_v1(bodyA_l,bodyB_l,bodyC_dim,bodyD_l);
cmb = compile(dcrankAimMech_mb);
visualize(cmb,computeState(cmb,simscape.op.OperatingPoint),'vizAssembly');
It can be seen that all of the bodies are collapsed onto a common line; this is the default assembly
configuration. In this configuration, all of the revolute joint angles are zero. Thus, the base and
follower frames of each revolute joint are coincident and aligned with each other; the corresponding
frame pairs are: FDA and F AD, FCB and FBC and FBD and FDB. In contrast, the frame FCA is translated
from frame F AC, thus the joint Pg is not in its zero state. We can view the computeState result to view
the values of the joint positions in this assembled configuration. This is currently not a desirable
assembly configuration.
The configuration depicted in the schematic diagram of the mechanism is the desired initial assembly
configuration. From the schematic diagram we can see that in the initial configuration the angle β is
about 35 deg. The assembly algorithm can be guided by specifying joint position and velocity targets
using the OperatingPoint. In this example, the position target for the joint Ro can be set to guide
assembly into the desired initial configuration using operating points. The target priority has been set
as High. Since this is the only target for the system that computeState is able to achieve exactly.
op = simscape.op.OperatingPoint;
op('Ro/Rz/q') = simscape.op.Target(35, 'deg', 'high') ;
% Note: As an aid to obtain the joint primitive paths needed by the operating point (i.e
% 'Ro/Rz/q'), use jointPrimitivePaths method of the Multibody object.
% For example, in this case we can view all the joint primitive paths using
% >> dcrankAimMech_mb.jointPrimitivePaths;
Now compute the state for the above operating point and check the State object to see that the joint
target for Ro has been met exactly.
compiled_mb = dcrankAimMech_mb.compile();
state = compiled_mb.computeState(op)
state =
State:
Status: Valid
8-166
How to Build a Multibody System in MATLAB
Assembly diagnostics:
x
Ro
Joint successfully assembled
Rz
High priority position target +35 (deg) achieved
Free velocity value: +0 (deg/s)
P
Joint successfully assembled
Pz
Free position value: +0.120952 (m)
Free velocity value: +0 (m/s)
Ri
Joint successfully assembled
Rz
Free position value: +84.8864 (deg)
Free velocity value: +0 (deg/s)
Rg
Joint successfully assembled
Rz
Free position value: -49.8864 (deg)
Free velocity value: +0 (deg/s)
compiled_mb.visualize(state,'vizAimMech');
Unfortunately, the assembled configuration is not the intended one because the rigid body B is not
aligned as indicated in the schematic diagram. Attempting to specify the joint angles of both Ro and
Ri exactly is an over-specification for this one degree-of-freedom mechanism. This is not prohibited,
8-167
8 Simscape Multibody Examples
but if there is a conflict, neither target may be met. Moreover, the desired angle of joint Ri is not even
known exactly.
In this situation, a convenient approach is to leave the high-priority target of 35 deg on Ro but to
specify the angle of Ri through a low-priority position target. The latter provides an approximate
value, or hint, for the desired joint angle. In this case, it is obvious that the angle θ should be obtuse;
150 deg is a rough estimate of its desired value. This target is set for joint Ri with a priority of Low.
op('Ri/Rz/q') = simscape.op.Target(150, 'deg', 'low') ;
compiled_mb = compile(dcrankAimMech_mb);
state = computeState(compiled_mb,op);
visualize(compiled_mb,state,'vizAimMech');
The assembled configuration after setting the new target is shown below.
To simulate the mechanism, we can create a simulink model by using the makeBlockDiagram
method of the Multibody object.
makeBlockDiagram(dcrankAimMech_mb,op,'dcrankAimMech_model');
Once the model is created, simulate the model (Ctrl-T) to view the motion of the mechanism under
gravity.
Now that the basic model is working, the next step is to add detail to make the model more realistic
and accurate. Perhaps the first version of the model was created when detailed information about the
geometry of the rigid bodies was not yet available. Having carefully established the interfaces of the
rigid bodies, it is fairly easy to add detail to each of the rigid bodies without affecting/changing the
rest of the model.
As an example, consider adding detail to the rigid body A while keeping its interface unchanged. The
figure below shows rigid body A as a composition of simpler bodies. The interface exposed by rigid
8-168
How to Build a Multibody System in MATLAB
body A is still the pair of frames F AD and F AC. Their positions and orientations remain unchanged.
The frames F12 , F21 , F23 and F32 are internal to the rigid body and should be created to assemble
the individual pieces of the rigid body into a whole. The function dcrankaim_detailed_body_A shows
the construction of the complex version of the rigid body A.
8-169
8 Simscape Multibody Examples
8-170
How to Build a Multibody System in MATLAB
dcrankAimMech_mb = dcrank_aiming_mechanism_v2(simscape.Value(80,'cm'),simscape.Value(30,'cm'),sim
cmb = compile(dcrankAimMech_mb);
op = OperatingPoint;
op('Ro/Rz/q') = Target(35, 'deg', 'high') ;
op('Ri/Rz/q') = Target(150, 'deg', 'low') ;
visualize(cmb,computeState(cmb,op),'vizMechDetailed');
Similarly, details can be added to the other rigid bodies by following the above discussed process.
Summary
• Started with a schematic diagram of the mechanism and identified the rigid bodies and joints in
the mechanism.
8-171
8 Simscape Multibody Examples
• Built a first approximation of each rigid body in isolation using the RigidBody object.
• Assembled the rigid bodies together using joints to achieve the first version of the assembled
mechanism using various objects like Multibody, RevoluteJoint, PristmaticJoint etc.
• Used the computeState method of Multibody object to identify problems with the assembly.
• Used OperatingPoint to guide the assembly into a desirable configuration.
• Once a full first version of the model was complete, added details to one of the rigid bodies
without changing the interface of the rigid body. Details could be added to other rigid bodies as
well.
See Also
addComponent | addConnector | addFrame | compile | simscape.multibody.Solid |
simscape.op.OperatingPoint | simscape.Value
More About
• “Double Pendulum”
8-172
Vehicle Dynamics - Car with Heave and Roll
This example models vehicle dynamics using a vehicle model that has 14 degrees of freedom. The
driver inputs can be configured as you select one of the maneuvers.
The vehicle model includes a six degree-of-freedom body model, two axles each with heave and roll
degrees of freedom, and four wheels that rotate. The front wheels are steered using the Ackermann
steering equation. Many of the vehicle parameters can be modified using MATLAB.
The tire model is the Magic Formula Tire Force and Torque block from Simscape Multibody. You can
plot the forces and torques at the contact patch from the simulation results.
Explore the Simscape Vehicle Templates for more customizable models of battery-electric vehicles,
hybrid-electric, and multi-axle vehicles.
Acknowledgements: MathWorks would like to thank M V Krishna Teja, PhD, Virtual Proving Ground
and Simulation Lab, Raghupati Singhania Centre of Excellence at the Indian Institute of Technology,
Madras for contributions to this example, including the tire parameters.
See Also
Magic Formula Tire Force and Torque
8-173
8 Simscape Multibody Examples
This example shows a ball and dumbbell rolling down on an L-shaped surface. Grid Surface block is
used to generate the L-shaped membrane. Point Cloud blocks are used to model the contact between
the ball/dumbbell and the surface. The number of point blocks can be controlled by varying the point
cloud density. This example demonstrates the capabilities of Grid Surface and Point Cloud blocks to
model contacts between complex shaped bodies.
See Also
Grid Surface | Point Cloud
8-174
Crane Boom Arm Test Bench
This example shows how to combine hydraulics modeling in Simscape™ Fluids™ with six-degree-of-
freedom motion and animation in Simscape Multibody™. This example also shows how to
parameterize, test, and compare design cases for a counterbalance valve in a crane boom arm test
bench. A counterbalance valve allows an upstream flow from the back port to the load port through
the check valve stage during cylinder rod extension, and it allows a downstream flow from the load
port to the back port through the relief valve stage during cylinder rod retraction in the boom arm
mechanism. A counterbalance valve help with the load holding, load actuation, speed control, and
safety by controlling the piston motion of the boom cylinder.
Model
The following figure shows the model of a crane boom arm test bench.
Crane Boom Assembly Subsystem: This subsystem models the crane boom system assembly.
8-175
8 Simscape Multibody Examples
Hydraulic Actuator Subsystem: Simscape Multibody connections Cylinder Base and Piston Head are
the Multibody ports associated with the bracket holes of the cylinder and piston rod respectively.
Simscape Fluids connections Cap and Rod ports are associated with the cylinder and rod side
hydraulic fluid respectively.
Boom Arm Subsystem: This subsystem models the multibody boom arm.
8-176
Crane Boom Arm Test Bench
Pulley and Weight Subsystem: This subsystem models the top pulley connected to the front bracket of
the boom arm and the bottom pulley connected to the top pulley with the rope. The bottom pulley is
connected to the weight.
Hydraulic Circuit Subsystem: This subsystem models the hoses connecting to the boom cylinder rod
and cap sides. The hoses are connected with the counterbalance valve and 4-way 3-position valve.
The rod extends the boom arm for the negative displacement valve command. The hydraulic fluid
flows into the cap side of the boom cylinder through the check valve stage of the counterbalance
valve.
The rod retracts the boom arm for the positive displacement valve command. The hydraulic fluid
flows out of the cap side of the boom cylinder through the pilot assisted relief valve stage of the
counterbalance valve.
8-177
8 Simscape Multibody Examples
This figure shows the boom cylinder position and the pressures at the cap side and rod side of the
cylinder piston.
8-178
Crane Boom Arm Test Bench
This figure shows the boom cylinder position, directional control valve spool position, and the flow
rates through the counterbalance valve for the design cases 1 and 2 of the counterbalance valve. The
boom cylinder extends when the directional control valve is in the negative spool position and
retracts when the directional control valve is in the positive spool position.
8-179
8 Simscape Multibody Examples
This figure shows the boom cylinder position and the hydraulic forces at the cap side and rod side of
the cylinder piston.
8-180
Crane Boom Arm Test Bench
See Also
Pulley | Prismatic Joint | Revolute Joint
8-181
8 Simscape Multibody Examples
This example shows a rotating arm that raises up a ball, drops the ball, and catches the ball in one
cycle of rotation.
A weld joint with its mode configured to be provided by input is used to attach and detach the ball
from the plate on the end of the arm. Transform sensors are used to measure the motion of the ball
and plate to determine when to catch and drop the ball and hence set the mode of the weld joint.
See Also
Pulley | Prismatic Joint | Revolute Joint
8-182
Variable Mode Joint Recirculation - Collision Course
This example simulates three balls with trajectories that restart when they reach the bottom of an
obstacle course, allowing each of them to traverse the course multiple times per simulation.
Spherical joints with their modes configured to be provided by input are used to transport each ball
back to its starting position after it reaches the bottom of the course. The contact signal emitted
when a ball touches the bottom front wall of the course is used to temporarily change the mode of the
ball's spherical joint, resetting the ball's position, but not its rotation.
See Also
Spherical Joint | Spatial Contact Force
8-183
8 Simscape Multibody Examples
This example shows how you can use modal reduction for performance acceleration in models with
flexible bodies. The model in this example uses a rectangular beam for simplicity, but you can apply
modal reduction to all flexible body blocks. By only retaining the lowest-frequency modes of vibration
of flexible bodies in your multibody system, you can speed up simulation while maintaining sufficient
fidelity.
To have the best reading experience of this example, you can hide the code. To hide the code, you can
go to the View tab, and in the View section, click Hide Code . If plots and tables do not display,
This example investigates the response of a cantilever beam when a sinusoidal force is applied to its
free end. You can perform a comparative study of the results obtained when the model is unreduced,
and when the model retains the first 1, 5 and 10 modes. For more information on the model, check
the file ModalReductionForFlexibleBodies.slx in the Current Folder browser.
numModes = [1 5 10];
[simTimeUnred,simTimesRed] = simulateAndPlot(numModes);
8-184
Using Modal Reduction in Flexible Bodies to Improve Simulation Performance
The figure shows the transverse deflection of the free end of the beam. The upper subplot shows the
simulation output, while the lower subplot zooms in on a short time interval for clarity. The plots show
that only a few of the lowest-frequency modes are needed to capture the bulk of the flexible body's
behavior in this scenario.
The table shows the simulation times for the different cases as well as the improvement in
performance compared to the unreduced simulation:
[numModes,sortIndices] = sort(numModes,"descend");
simTimesRed = simTimesRed(sortIndices);
disp(table( ...
["Unreduced";numModes(:)], ...
[string(num2str([simTimeUnred;simTimesRed(:)],"%6.3f"))], ...
[" - ";string(num2str(simTimeUnred./simTimesRed(:),"%4.1fx"))], ...
'VariableNames',["Number of Modes", ...
"Simulation Time (sec)", ...
"Performance Improvement"]));
8-185
8 Simscape Multibody Examples
Enter the number of modes you want to retain, then run the analysis to perform a comparison against
the unreduced case.
maxNumModes = getMaxNumModes();
numModes = ;
[simTimeUnred,simTimesRed] = simulateAndPlot(numModes);
fprintf("It took %.3f sec to simulate the unreduced model, and\n" + ...
"%.3f sec for the reduced model, which is %.1fx faster.", ...
simTimeUnred,simTimesRed,round(simTimeUnred./simTimesRed,1));
8-186
Using Modal Reduction in Flexible Bodies to Improve Simulation Performance
% Setup
model = "ModalReductionForFlexibleBodies";
load_system(model);
beamPath = model + "/Beam";
% Infer the maximum number of modes from the number of beam elements
numElements = str2double(get_param(beamPath,"NumElements"));
maxNumModes = 6*numElements;
% Teardown
close_system(model,0);
end
% Setup
model = "ModalReductionForFlexibleBodies";
load_system(model);
set_param(model,"SimMechanicsOpenEditorOnUpdate","off");
beamPath = model + "/Beam";
8-187
8 Simscape Multibody Examples
% Teardown
close_system(model,0);
end
See Also
Flexible Rectangular Beam | External Force and Torque
8-188
Ratchet Pawl Mechanism
This example models a ratchet with a locking pawl. The arm pushes the driving pawl to rotate the
ratchet wheel. The locking pawl holds the ratchet wheel in place while the arm reverses direction.
Planar contact modeling geometry is used to streamline computation.
Model
This plot shows the extrusion data for the wheel. This was created in MATLAB and was used to
generate the data for the contact geometry along the edges of the wheel.
8-189
8 Simscape Multibody Examples
This plot shows the extrusion data for the pawl. This was created in MATLAB and was used to
generate the location for the frame where the contact geometry is placed at the tip of the pawl.
8-190
Ratchet Pawl Mechanism
Wheel
The wheel subsystem models the mass and inertia of the wheel, contact geometry for the edges of the
wheel, and contact forces between the wheel and pawls. Simscape Bus blocks are used to group the
geometry connections for each of the line segments representing the teeth edges.
8-191
8 Simscape Multibody Examples
The rotational speeds of the wheel and driver arm are plotted below. The arm and wheel rotate at
nearly the same speed as the driver arm rotates counterclockwise. The wheel stays nearly still as the
drive arm rotates clockwise. The spikes in the wheel speed are due to the contact forces between the
pawls and the wheel.
See Also
Spatial Contact Force | “Ratchet Lifter” on page 8-103
8-192
Measure Inertial Properties of Multibody Systems
This example shows how to measure the inertial properties, such as mass and center of mass, of a
multibody mechanism or a specific body group. This example uses a model of a centrifugal governor
system and measures the inertial properties of the governor by using the Inertia Sensor block. For
details on the governor model, open the example.
The mechanism of a multibody model encompasses all body elements present in the model. The body
element blocks can be any solid, inertia, flexible body, or variable mass block in the Body Elements
sublibrary. For example, this diagram shows the body element blocks in the governor.
8-193
8 Simscape Multibody Examples
In a multibody model, a body group is a group of element blocks that are rigidly interconnected.
These interconnections can be direct or facilitated by Rigid Transform blocks. The joint blocks
separate the mechanism into distinct body groups. For example, this diagram shows the body groups
in the governor mechanism and uses the same color to highlight the body elements that belong to the
same body group.
8-194
Measure Inertial Properties of Multibody Systems
To measure the inertia properties of an entire mechanism or a specific body group, use the Inertia
Sensor block.
To measure the inertial properties of a mechanism, you can connect an Inertia Sensor block to any
part of the model and specify the sensor extent to measure the whole mechanism. For example, to
measure the mass of the entire governor mechanism:
• Open the Governor subsystem, then add Inertia Sensor, PS-Simulink Converter, and Display
blocks.
• Specify the parameters of these blocks as shown in the table.
8-195
8 Simscape Multibody Examples
Run the simulation. The measured mass agrees with the total mass of the governor mechanism.
8-196
Measure Inertial Properties of Multibody Systems
In this model, the gearbox is a ground body. To exclude the mass of the gearbox from the
measurement, under the Sensor Extent section of the Inertia Sensor block, select Exclude
grounded Bodies.
8-197
8 Simscape Multibody Examples
Simulate the model. The measured mass does not include the gearbox.
8-198
Measure Inertial Properties of Multibody Systems
The Inertia Sensor block never categorizes flexible bodies as ground bodies, even if the flexible
bodies rigidly connect to the world frame. To verify this:
8-199
8 Simscape Multibody Examples
Simulate the model. The measured mass includes the mass of the flexible body.
8-200
Measure Inertial Properties of Multibody Systems
You can also measure the inertial properties of a single body group. For example, in the governor
model, you can measure the mass of the body group that comprises the right arm and the right
flyball.
8-201
8 Simscape Multibody Examples
This diagram shows the body element blocks in the body group. Two revolute joints separate this
body group from the other body groups in the governor.
8-202
Measure Inertial Properties of Multibody Systems
8-203
8 Simscape Multibody Examples
Run the simulation. The measurement agrees with the total mass of this body group.
Like other types of joint blocks, the Weld Joint block separates body element blocks into two body
groups. For example, add a Weld Joint block between the Extension Arm R and Top Arm R blocks to
separate the Top Arm R block from the body group.
8-204
Measure Inertial Properties of Multibody Systems
Run the simulation. The measured mass does not include the top arm.
In certain applications, you need to use the Weld Joint block to connect body element blocks and
measure the connected blocks as a body group. To achieve this goal, you can change the sensor
extent of the Inertia Sensor block. For example, to include the Top Arm R block in the measurement,
open the Inertia Sensor block and, under the Sensor Extent section, select the Span Weld Joints
parameter.
8-205
8 Simscape Multibody Examples
Run the simulation. The measured mass includes the top arm.
The measurement frame of the Inertia Sensor block specifies the frame to use to measure and
express the center of mass (COM), inertia matrix, and centered inertia matrix. This section shows
how to measure the center of mass (COM) of the highlighted body group and express the
measurement in three different frames.
8-206
Measure Inertial Properties of Multibody Systems
8-207
8 Simscape Multibody Examples
You can express the measured COM in a frame that is affixed to this body group. For example, to
express the measured COM in the reference frame of the Flyball R block, connect the reference
frame to the S port of the Inertia Sensor block and, in the sensor dialog box, specify Measurement
8-208
Measure Inertial Properties of Multibody Systems
Frame as Attached. The specified measurement frame is highlighted in the image with a light blue
color.
Simulate the model. The Display block shows the COM at the initial step and the Scope block shows
the COM throughout the simulation. Change the legend of the signals as shown in the image. The
result shows that the COM is fixed to this measurement frame throughout the simulation.
8-209
8 Simscape Multibody Examples
It is common to express measured quantities in the world frame, which remains stationary during the
simulation. To express the measured COM in the world frame, in the Inertia Sensor block dialog box,
set Measurement Frame to World. In this image, the world frame is highlighted with a light blue
color.
8-210
Measure Inertial Properties of Multibody Systems
Simulate the model. The Display block shows the COM at the initial step and the Scope block shows
the COM throughout the simulation.
8-211
8 Simscape Multibody Examples
The result shows that the x and y coordinates exhibit oscillatory behavior, with the frequency of
oscillation between two to six seconds being notably higher compared to other intervals. These
results correspond to the right branch of the governor having a more rapid rotation about the z-axis
of the world frame during this time frame. These observations are consistent with the simulated
behavior of the governor.
You can also express the measured quantities in a custom frame. To express the COM in the reference
frame of the spindle:
• Expose the M port of the Inertia Sensor by setting Measurement Frame to Custom.
• Expose the reference frame port of the Spindle block by selecting Show Port R under Frames.
• Reorganize and connect the blocks as shown in the image.
• Change the layout of the plots for the Scope block. Double-click the Scope block, select View >
Layout, and select 4-by-1 layout.
8-212
Measure Inertial Properties of Multibody Systems
• Connect the 4th input port of the Scope block to the Rotation Inport block.
• Run the simulation.
The specified measurement frame is highlighted in the image with a light blue color.
The Display block shows the COM at the initial step and the Scope block shows the COM throughout
the simulation.
8-213
8 Simscape Multibody Examples
The plots show that, during the simulation, the y coordinate remains constant while the x and
z coordinates are proportional to the angular velocity, which equals the slope of the rotation signal. In
other words, the COM is on the xz-plane of the measurement frame, and the frame undergoes
rotations about its z-axis. These observations are consistent with the simulation of the governor.
See Also
Related Examples
• Inertia Sensor
8-214