Guy and Seth on Simulink

February 1st, 2012

Applying Motion to SimMechanics Models

One of the features I like about SimMechanics is the ability to specify the motion of a system without having to think about the forces involved. This can simplify testing a model so you don't have to design a controller if all you are doing is testing the plant model for correctness. Today I want to talk about a common problem people run into.

The Problem

I have the following SimMechanics model. This model is supposed to simulate a big crane... you know the ones with a big ball at the end of a cable used to destroy buildings.

SimMechanics model of a crane

When applying a sine wave trajectory (position) to the base, I expect the ball to swing, however it does not!

SimMechanics animation of a crane

The Explanation

As you probably noticed, the base is actuated with a Joint Actuator, setup to Actuate with motion. In this configuration, three components must be fed to the block: Position, Velocity and Acceleration.

Obviously, the velocity and acceleration corresponding to a sine wave trajectory are not 0!

The Solution: First Try

To get valid results with SimMechanics, it is important to provide valid inputs.

To do that, the first thing that probably goes through your mind is to use Derivative blocks, like this:

Using Derivative blocks

This works if the position signal is smooth, however in many cases this can cause problems.

Why? If you have a discontinuity in the position signal, this will cause a sudden change in the velocity signal and an infinite acceleration. Infinite accelerations are not realistic and cause derivative errors in the solver.

A Better Solution

What I recommend is to implement a filtered derivative using a Transfer Function block.

Using Derivative blocks

Now we can see that our crane behaves as expected.

SimMechanics animation of a crane

Now it's your turn

If you are interested, you can find the model here.

Look at the documentation section titled Stabilizing Numerical Derivatives in Actuation Signals for more details and let us know what you think by leaving a comment here.

January 22nd, 2012

Advanced S-function Techniques: Scheduling Future Events

Today I will describe how to use a variable sample time s-function to schedule events in the future. This topic is fairly advanced, so hold on tight... or as we say where I come from: Attachez vos tuques avec d'la broche

The question

The question I received is:

I have a model with a variable sample time solver. In this model, I have a signal with a continuous sample time, but discontinuous amplitude. Every time the signal changes amplitude, I need to trigger a subsystem. But I do not want to trigger the subsystem immediately. I need to trigger after fixed delay.

Original Model

First attempt

The first thing the user tried is delaying the signal using the Transport Delay block and detecting the changes in the delayed signals.

As I explained in a previous post, the Transport Delay expects a smoothly changing continuous signal. When fed a signal with discontinuities, the output of the Transport Delay is not exactly the input offset by a delay. This is the situation we encounter as shown in this image below.

Delaying the input signal

Variable Sample Time

One way for a block to tell the Simulink solver to take steps at a specific moment in the future is to specify variable sample time. For example, the Pulse Generator block uses this technique to run only when needed.

If I make a model with the Pulse Generator block configured to have a period of 5s and a pulse width of 40%, the block will tell the variable step solver to take steps at times 0s, 2s, 5s, 7s, 10s,...

Pulse Generator, a Variable Sample Time block

Variable Sample Time S-function

With an s-function, you can do the same!

For a basic example, look at the demo model sfcndemo_vsfunc.mdl. This model shows how to use mdlGetTimeOfNextVarHit to specify the next time your block should run.

The solution

Based on that, we want to write an s-function that will look at its input every major step of the simulation. When a change will be detected, we will store the time value in a buffer. Every time an event will be generated, we will look into this buffer and schedule the next event.

In S-function specific terms, this means:

  • In mdlInitializeSizes, we specify the size of the buffer using ssSetNumRWork . We also define an integer work vector using ssSetNumIWork to keep the index of events coming in and out of the buffer.
  • In mdlInitializeSampleTimes, we declare 2 sample times: Fixed in Minor and Variable. The fixed in minor sample time will allow us to monitor each sample of the input signal for detected changes and the variable sample time will be used to generate the events.
  • In mdlUpdate, we monitor the input. If a change is detected, we store the time in the work vector.
  • Every time a variable sample time is hit, the solver calls mdlGetTimeOfNextVarHit to obtain the time of the next variable sample time hit. When this happens, we look into the work vector to get the time of the next event and use ssSetTNext to register it.
  • In mdlOutputs, we use ssIsSampleHit to know if the current step is a hit of the variable sample time. If this is the case, we generate a function call using ssCallSystemWithTid.

When this is all implemented, I have a block that can schedule events in the future

Final Model

For those interested to see the final results, here are links to the model and the s-function source code.

Now it's your turn

Do you use variable sample times in your model? Leave us a comment here.

January 11th, 2012

Model-Based Design of a Dicycle

The other day I found this video:

If you watch carefully, you will see around 1:50 that they used Simulink to design their controller.

So for this week's post, I thought it would be interesting to see how we can design a simple planar version of a dicycle in Simulink.

Modeling the plant in SimMechanics

Since this system is not very complex, I could have derived the equations of motion by hands. But even if the equations are simple, it is simpler (and more fun) to model it with SimMechanics.

To model this planar dicycle, we need 3 bodies: the ground, a wheel and a center body. The important trick here is the Velocity Driver block constraining the motion of the wheel relative to the ground. Note that, to make the SimMechanics visualization look nicer, I added 2 posts acting as starting and stopping references.

Modeling a Diwheel using SimMechanics
Click on the image to download the model.

Our system has 2 sensors, a gyroscope returning the angle of the body relative to gravity, and an encoder giving the angle of the body relative to the wheel. On the actuator side, the system has 1 motor applying a torque between the wheel and the body.

Testing the plant motion

When developing a plant model, it is important to validate it. To validate the plant, I apply a torque to the actuator and observe if the resulting motion is as expected.

Uncontrolled motion

This behaves as expected... but if I don't find a better controller, the passenger will quickly get sick. Let's see how we can design a controller.

Linearizing the plant

Most control techniques I know are based on a linear representation of the system. To obtain this representation, I use Simulink Control Design. I can use the graphical interface or the command-line API. For my model, the command-line version looks like:

mdl = 'Diwheel';
% Set the controller to zero during linearization
K = [0 0 0 0];
% Construct linearization input/output
io(1) = linio([ mdl '/Ctrl'],1,'in','on')
io(2) = linio([ mdl '/Sensors'],1,'out','on')
% Linearization
sys = linearize(mdl,io);

Designing a controller

Now I will use the Control System Toolbox function lqr to design a state-feedback controller. The code looks like this:

% Get minimal realization
[sys U] = minreal(sys);
% Design state feedback controller
Q = diag([ 100 1 100 1],0);
R = 1;
[K,S,e] = lqr(sys,Q,R);
% Transformation from y to x
K = K/sys.C;

All I had to tune are the values on the diagonal of matrix Q to give a priority to each state. You can download the complete initialization script here.

Now if I try to command the vehicle an aggressive trajectory of 1m/s for 10 meters and sudden breaking, I get the following:

Controlled motion

Next steps

I will stop here for this post. If I had to implement this controller on a real system, I would have a lot more steps to go through. This would involve adding to the model actuators limits, sensors resolution, discretizing the controller, maybe converting it to fixed-point, etc.

Now it's your turn

Let us know what you think of this control design process by leaving a comment here.

January 4th, 2012

Frames… from signals to blocks

Today I want to talk about an important topic for DSP System Toolbox and Communication System Toolbox users: Frame-Based Processing

Beginning in R2010b, MathWorks started to significantly change the handling of frame- and sample-based processing. Currently, we are in a transition phase and it's time to update your models to the new paradigm.

Sample-based processing vs. frame-based processing

Let's begin by a quick explanation of the difference between frame-based and sample-based processing.

Let's say I have a signal of dimensions 3x2. If I process this signal in a sample-based manner, every simulation step I will process the 6 elements individually as 6 independent channels:

One sample

In frame-based processing, blocks process signals multiple sequential samples per time step. For example, a 3x2 matrix like in the previous example could contain only 2 independent channels. For each channel, this matrix contains a frame of 3 samples:

One frame

As you can guess, frame-based processing can lead to significant performance improvements because each block operates on frames of data rather than on individual samples, and interblock communication is reduced.

Changes to Frame-Based Processing

Historically, in Simulink the frame status has always been an attribute of the signals, like data type and dimensions.

This can be seen by looking at the CompiledPortFrameData property of an Output port with a code like the following:

modelname([],[],[],'compile')
ph = get_param('modelname/White Noise','PortHandles')
get_param(ph.Outport,'CompiledPortFrameData')
modelname([],[],[],'term')

Beginning in R2010b, we started to significantly change the handling of frame- and sampled-based processing. In the future, frame status will no longer be a signal attribute. Instead, individual blocks will control whether they treat inputs as frames of data or as samples of data.

This means that many blocks in the DSP System Toolbox and Communications System Toolbox now have an Input Processing option where they can decide to process columns as channels (frame-based) or elements as channels (sample-based). You can notice in the following image that the block dialog clearly mentions that the option to inherit the processing type from the input signal will be removed in the future.

One frame

To open a demo model highlighting the effects of this setting, type ex_inputprocessing at the MATLAB prompt.

What should I do to update my model?

One word: slupdate

During the transition phase, the frame information is still propagated through the signals in your model. Based on this information, slupdate can automatically configure the blocks for the new paradigm.

In the future, the frame information will be removed from signals and you will no longer be able to upgrade your models using the slupdate function. Therefore, you should upgrade your existing models using slupdate as soon as possible.

Now it's your turn

Give a look at the R2011a and 2011b release notes of the DSP System Toolbox and let us know what you think by leaving a comment here.

December 27th, 2011

Model-Based Design Dilemma

I am currently working on a model and I have a dilemma. There are two ways I could model my system. I need you to tell me which approach is best and why.

I need your help!

The Goal

I am building a model to drive a small robot made of Lego blocks. The system is similar to the NXTWay-GS submission on the MATLAB Central.

NXTWay-GS

Following a Model-Based Design approach, I want to setup my files so that I can easily develop my controller in simulation and generate code to test my algorithm on the real hardware. This means that in simulation I need to send my actuator commands to an LTI system approximating the system dynamics; and for code generation I need to send and receive signals from hardware drivers.

Hardware drivers and simulation model

My question now is: What is the best way to include these 2 sets of blocks in my model architecture?

Option 1: Two Top Models

My first option is to create 2 top models that will both refer to the same controller using model referencing.

I would have one top model for simulation:

Model for simulation

and one top model for code generation:

model for code generation

Option 2: Subsystem Variants

My second option is to create one top model. In this top model, use Subsystem Variants to switch between the simulation and the hardware drivers:

One top model with 2 variant

Now it's your turn

What architecture do you prefer? For which reasons? Do you see other options? I am very interested to hear your comments and ideas. Please leave a comment here.

December 20th, 2011

Mixed-signal modeling with Simulink

If you’re a mixed-signal engineer, we have a Christmas present for you – a new library of mixed-signal blocks and demos available for free. My colleague Mike Woodward explains all.

Designing mixed-signal systems with the free mixed-signal library

For years now, MathWorks engineers have been building mixed-signal examples for customers. We’ve built ADCs, PLLs, digital pre-distortion, and switch-mode power supply demos, often including documentation. It occurred to us that we could help our customers if we bundled demos and blocks into a library. Better still, this library could offer full help and full integration with Simulink. Best of all, we could offer the library for free. This is the new mixed-signal library.

The library has 20+ demos covering ADCs, PLLs, digital pre-distortion, switched-mode power supplies, signal integrity, and RF. Each demo has full help, accessible from the demo or from Simulink’s help system. Here’s a screenshot of one of my favorite demos:

Mixed-signal demo

There are 40+ blocks ranging from OpAmp to Clock Divider to Triggered Eye Display. Every block has help and we’ve made sure every block appears in a demo. Here’s a screenshot showing some of the blocks:

Mixed-signal Library

We’ve also supplied three detailed tutorials that take you step-by-step through the process of building an ADC, a PLL, and a digital pre-distortion system. We’ve included all the files, including the data files and the model files for each step of the process. This way, if you make a mistake, you can correct it very quickly.

The library depends on MATLAB and Simulink, plus some other products. As you might expect, the dependencies vary from demo to demo – for example, the circuit demos require products the behavioral demos don’t. We’ve listed the dependencies in the help for each block and demo.

To make it all easier to use, we’ve fully integrated the library with Simulink – the library appears in the library browser and in the help browser. The installation process is easy and you can do it in under 5 minutes.

Now it's your turn

Download the mixed-signal library here and let us know what you think by leaving a comment here.

December 14th, 2011

Welcome to the Linear Analysis Tool!

Today I am happy to welcome back guest blogger Erman Korkut to talk about the new Linear Analysis Tool.

Guest blogger, Erman Korkut

Linear Analysis Tool

Have you ever trimmed your model? Have you ever linearized it? Have you ever estimated its frequency response? Simulink Control Design has been offering all these capabilities for some time. In R2011b, we introduced the Linear Analysis Tool streamlining all these capabilities into a single interface.

Trimming a model

Before linearizing a model or estimating its frequency response, it is important to specify an operating point. It can be by taking a snapshot at a specific instant, or by finding a steady state (equilibrium) operating point, commonly referred to as trimming.

To get started, go to Tools -> Control Design -> Linear Analysis, select the Linear Analysis tab and click the Trim Model or the Operating Point Snapshot button:

Linear Analysis tab

Linearizing a model

The linearization of your model provides you with a lot of insight about its dynamics. You can inspect the frequency response, evaluate stability margins, and design controllers using the linearization result. You can linearize a model around different operating points to analyze and compare its behavior at different operating conditions.

Once you are ready to start, select the Exact Linearization tab:

Exact Linearization tab

Estimating the frequency response of a model

Another way to compute the frequency response of your nonlinear model is to simulate it with appropriate input signals, measure the output signals of interest, and inspect the frequency content of those output signals. The frequency response data obtained this way can be used to identify a parametric model or to design a controller. It also serves as an independent test for the exact linearization; thus, it can be used to validate exact linearization results.

Select the Frequency Response Estimation tab and define your input signal:

Frequency Response Estimation Tab

Analyze your Results

Once you completed a linearization or a frequency response estimation, the Linear Analysis Tool allows to visualize your systems in multiple ways and to easily transfer data to the MATLAB workspace:

Frequency Response Estimation Tab

Videos

You want to see more? I highly recommend watching the following short videos to see the linear analysis tool in action:

Trim Batch Mode Trimming and Linearization Frequency Response Estimation
Trim, Linearization and Control Design for an Aircraft Batch Mode Trimming and Linearization Frequency Response Estimation


Now it is your turn

Do you trim, linearize and estimate the frequency response of your Simulink models? What tools are you using to do so? Try using the Linear Analysis Tool with your model and share how it goes by leaving a comment here.

December 9th, 2011

Simulink Student Challenge Results

Do you remember that a few months ago Seth posted a video to launch the first Simulink Student Challenge?

simulink-student-challenge.png

We are very impressed by all the entries. Thanks to everyone who participated!

Here are the winners!

First Place

Claudio Loconsole from Scuola Superiore Sant'Anna wins $500 for "Reaching with MATLAB/Simulink."


Second Place

Jonny Lin from University of Auckland wins $300 for "Renewable Energy System for Rural Households."


Third Place

Jared Frank from Polytechnic Institute of New York University wins $200 for "iPhone-Controlled Laboratory."


You can learn more about the winners and the entries we received at the MathWorks Simulink Student Challenge site.

Look for another challenge in 2012!

December 5th, 2011

Initializing buses using a MATLAB Structure

Did you notice that since R2010a it is possible to initialize buses with a MATLAB structure? If you were not aware, here is how it works.

Starting from a Structure

Let's say I have a structure in the MATLAB workspace and I would like to make that a bus signal in Simulink. I can use Simulink.Bus.createObject to create a bus object:

myStruct.a = 5;
myStruct.b = true;
myStruct.c.x1 = 22;
myStruct.c.x2 = 3;
busInfo = Simulink.Bus.createObject(myStruct);

Then I can configure a Constant block to use this bus object as data type and to use myStruct as value.

Configuring a Constant block to output a bus

Constant block outputing a bus signal

Starting from a model

Let's say I have the following model where a bus signal is going through a Unit Delay block. I want to specify different initial values for the elements of the bus.

Specifying the initial condition for a bus signal

In that case I can use the handle to a port of the Unit Delay block as input to Simulink.Bus.createMATLABStruct. This will create a MATLAB structure with the same hierarchy as the bus, filled with zeros. I can then overwrite fields of this structure as needed and use it as the initial value of the Unit Delay.

portHandle = get_param(gcb,'PortHandles');
initStruct = Simulink.Bus.createMATLABStruct(portHandle.Inport);
initStruct.bus2.Pulse = 5;
initStruct.signal1.Chirp = 3;

Requirements to Use Bus Signal Initialization

To enable bus signal initialization, you need to set two Configuration Parameter diagnostics:

Even if you don't need to initialize buses, I always recommend using those setting. They help making your models easier to understand and improve the consistency of simulation results.

Now it's your turn

Look at Specifying Initial Conditions for Bus Signals for more details and let us know how you will use this feature by leaving a comment here.

November 28th, 2011

Finding where variables are used from the Model Explorer

In a previous post, we illustrated the Simulink.findVars function.

To be honest, I am not very good at remembering the syntax of functions. Every time I encounter a situation where I could use Simulink.findVars, I need to open the documentation to figure out how to use it. Being a Simulink user, if there is a way I can click somewhere to get or set what I want, you can be sure I will go that way.

For those like me, I want to share this trick I just discovered.

Find Where Used

Most models rely on tens or even hundreds of variables in the workspace. Sometimes I need to know which blocks in the model use a specific variable. To accomplish this, open the model and right click on the variable. You will see a Find Where Used option:

Finding variables form the Model Explorer

This will launch a window asking if you want to search for a specific model or all open models:

Selecting the search scope

Depending on the type of variable, the search might require a model update. Once this is done, you will get the list of blocks using the variable.

Found blocks

Double click on the block name. Simulink will bring it up and highlight it:

Found block highlighted

Now it's your turn

Look at the documentation section titled The Model Explorer: Working with Workspace Variables and let us know how this is applicable to your work-flow. Leave us a comment here.


MathWorks
Guy Rouleau and Seth Popinchalk are Application Engineers for MathWorks. They write here about Simulink and other MathWorks tools used in Model-Based Design.

These postings are the author's and don't necessarily represent the opinions of The MathWorks.