Main Content

Create a Simple Pendulum in MATLAB

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.

import simscape.multibody.* simscape.Value simscape.op.*

Construct the pendulum link with a brick geometry:

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:

rotator=RigidTransform(AlignedAxesRotation(Axis.PosX, Axis.NegY, Axis.PosZ, Axis.PosZ));

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);

Add the necessary components to the multibody:

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");

Visualize the pendulum:

compiledPendulum=compile(pendulum);
state=computeState(compiledPendulum,op);
visualize(compiledPendulum,state,"simple_pendulum");

Generate a Simulink® model of the pendulum:

makeBlockDiagram(pendulum,op,"simple_pendulum")

See Also

|

Related Topics