You are on page 1of 109

Technical Articles and Newsletters

Using MATLAB Live Scripts to Teach Optimal Control and Dynamic Programming Online

By Duarte J. Antunes, Eindhoven University of Technology

When my course Optimal Control and Dynamic Programming transitioned to an online model during the COVID-19 pandemic, MATLAB® live scripts proved invaluable. They enabled me to teach
complex concepts in a way that was interactive, engaging, and better suited to online learning than a traditional lecture-with-slides approach.

With live scripts I can combine formatted text, images, hyperlinks, equations, and code (Figure 1). Because the scripts are live, students can tune parameters or modify the code and immediately see
how their changes affect the output. The process engages students in active learning and encourages exploration of the material. In a post-course student survey, 97% of the respondents reported that
live scripts either “helped” or were “very useful” in completing assignments.
Technical Articles and Newsletters


Figure 1. A live script used in Optimal Control and Dynamic Programming.
Limitations of Lectures-with-Slides
Technical Articles and Newsletters
When I taught Optimal Control and Dynamic Programming in the past, my lectures incorporated slides in which I introduced a new concept, described how it could be implemented, and then showed
some sample output. For example, in a lesson on linear-quadratic regulators (LQRs) I would start with a discussion of the relevant equations as well as special cases and assumptions, show the
MATLAB implementation, and then show the output of the code for various parameter values (Figure 2). Later, I would assign exercises that asked students to solve a set of optimal control problems
using MATLAB. The exercises included a sample solution with a snapshot of MATLAB code.
Technical Articles and Newsletters


Technical Articles and Newsletters
Figure 2. Slide series on LQR. Clockwise from top left: introduction, sample application, the corresponding MATLAB code, and plots of the results.

I always felt that this approach was a clumsy way of presenting material. The code on the slide was just a snapshot of the implementation, and I had to include numerous plots to show the effect of
different parameter values on the output. Motivated by these issues, I decided to convert all the course material involving MATLAB to live scripts.

From Slides to Live Scripts


Altogether, I converted 16 lectures, 30 MATLAB examples, 30 MATLAB exercises, and 10 graded assignments. For each course topic, I copied the introductory discussion text into the live script and
structured it with headings, bullet points, and hyperlinks to background material. I used the Live Editor to type in LaTeX commands and preview the corresponding equation before placing the equation in
the live script (Figure 3).
Technical Articles and Newsletters
Figure 3. Inserting a LaTeX equation into a Live Script and previewing the output.
Technical Articles and Newsletters
In some cases, the equations were quite long, and I did not have the LaTeX code. In these cases I used Mathpix OCR software to scan written or printed equations and generate the LaTeX for me.

Once I had created the live scripts, I shared them with students via MATLAB Drive cloud-based storage. Students downloaded the scripts for each lecture and ran them either on their laptops or in a
browser using MATLAB Online (Figure 4). With MATLAB Online, students can run and edit scripts from any computer or tablet, even machines that do not have MATLAB installed.

Figure 4. The live script for the LQR control lesson running in a browser with MATLAB Online. Students can change parameter values with the slider on line 29 and see the resulting effects in the
plots on the right.

Live Script Assignments and Automatic Grading


During lectures, students often experiment with the corresponding live scripts, varying parameter values and checking the results. I encourage this kind of experimentation because it helps them to
absorb the new material.
Live scripts are equally valuable in helping students with assignments. One assignment, for example, involves developing a control algorithm for a buzz wire game. In the real-world version of the game,
Technical Articles and Newsletters
the objective is to pass a ring along a curved wire without letting the ring touch the wire at any point. For the assignment, I reduced it to a two-dimensional problem in which the algorithm must control the
ring’s trajectory by calculating the offset and angle of the ring for each time step as it moved down the wire (Figure 5) so that it reaches the end of the wire in a minimum time.

Figure 5. A visualization of the buzz wire assignment in which a ring (blue lines) must pass along a wire (red curve) without touching it.

Students tend to have a lot of questions when I explain this assignment. When I provide them with a live script of a sample implementation, they are able to answer many of these questions themselves;
they can run the script offline, change control parameters, see exactly what constitutes a touch of the ring making contact with wire, and so on.

To simplify grading, I show the students exactly the function they needed to develop within the live script to complete the assignment, with clearly defined inputs and outputs. I then use this specific
function to automatically grade the students’ solution with MATLAB Grader, which is integrated with Canvas, our learning management system.

Planned Improvements and Other Uses for Live Scripts


I continue to add enhancements as I develop new live scripts for my courses. These enhancements include incorporating more animations. I did this for an assignment in which the students had to
develop an optimal control policy for the ghosts chasing a Pac-Man™-like character in a pursuit-evasion game (Figure 6). I found that the animation helped the students understand the assignment
much better than my textual description could do.
Technical Articles and Newsletters

Figure 6. Pursuit-evasion game in which students develop optimal control algorithms for the ghost (red) to pursue the main character (yellow).

In response to student feedback, I’m also adding more in-line comments to the MATLAB code. I’ve noticed that today’s students depend on seeing the code, and code comments, to cement their
understanding. In the past, I tended to de-emphasize implementation details, but more and more students understand the language of programming and find it easier to grasp certain concepts when
they are expressed in commented code rather than in our natural language. One student noted, “It really helps to see how a problem/solution changes when you decide to change a certain parameter or
piece of code. Normally, examples are limited by the one variation that is shown. Besides that, the actual implementation of some of the theory is hard to imagine sometimes, while such a piece of code
can help that process immensely.”

One of the principal advantages of live scripts is that they are easy to learn and use. I’ve found that most students are up and running after about five minutes of looking at the documentation. In another
course that I teach on signals and systems, I asked students to submit a report on their projects. Many decided on their own to create their final reports as live scripts and use live scripts to explain their
project through a video.

About the Author


Duarte Antunes is an assistant professor at Mechanical Engineering Department at Eindhoven University of Technology (TU/e), where he is a member of the Control Systems Technology group.
His teaching and research activities focus on control theory. Technical Articles and Newsletters

Published 2021

Products Used
• MATLAB

Learn More
• Signals and Systems Top 10 Student Projects (35:31) - Video

• Create Interactive Scripts with Live Editor - Overview

• Interactive Control Design Using Live Editor Tasks (4:56) - Video

• Teaching Parallel Computing Online with MATLAB - Article

View Articles for Related Capabilities


• Technical Computing

• Data Acquisition

• Algorithm Development

mathworks.com
© 1994-2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or
registered trademarks of their respective holders.

Join the conversation


Technical Articles and Newsletters

Profiling C Code Generated by MATLAB Coder

By Paul Peeling, MathWorks

Whether you are generating C code to accelerate MATLAB® algorithms or to deploy MATLAB algorithms to embedded targets, execution speed is an important consideration. By profiling your code and
collecting timing information, you can quickly find hotspots and bottlenecks and identify opportunities to improve code performance.

This article shows how to profile C code generated by MATLAB Coder™. We’ll be using sample-based profiling, a technique that lets you find hotspots without having to modify the code. Sample-based
profiling periodically samples the call stack of the running code and aggregates the data to report the relative execution time of different parts of the code. Other profiling methods rely on instrumenting
the code, which changes the performance of the running code.

The workflow uses the Microsoft® Visual Studio® C++ compiler and a freely available profiling tool, AMD CodeAnalyst, but most other compilers and profiling tools work equally well.

Code Profiling Example


In this example, we will use the following MATLAB algorithm:

function z = do_intense_computations( x )
% do_intense_computations perform computationally intensive operations
%#codegen

% Copyright 2012-2016 MathWorks


y = fft_magnitude( x );
z = self_convolve( y );
end

function y = fft_magnitude(x)
coder.inline('never')
y = abs( fft ( x ) );
end

function y = self_convolve( x )
coder.inline('never')
y = conv( x, x );
end

We’ll use profiling to see whether the FFT or the convolution operation is more computationally intensive.
Preparing Code for Profiling
Technical Articles and Newsletters
Although sample-based profiling requires no modification of the generated code, it is good practice to break up the algorithm into functions or subfunctions. Use coder.inline(‘never’) to ensure that
whenever a function is used in MATLAB, the generated C code has a corresponding function call. It’s then easy to trace profiling results from the C code back to MATLAB.

Creating a Script for Profile Runs


CodeAnalyst does profiling over a set time period. The default run length is 20 seconds. Since our MATLAB algorithm might not take this long to execute, we create a script that allows us to call it
multiple times:

x = randn( 256, 1 );
while ( true )
y = do_intense_computations( x );
pause( 0.1 ) % allow for CTRL-C operations to break execution
end

We then run the code in MATLAB to confirm that it executes without error, and press CTRL-C to stop the code running after CodeAnalyst has finished profiling.

Configuring Code Generation for MEX or SIL Verification


First, we create a MEX file from our MATLAB algorithm using MATLAB Coder, checking that the code generation settings are correct for performance. To accelerate the algorithm, we will perform
profiling on the generated MEX function. For embedded target deployment, we will generate a static library (.lib) and perform profiling on the standalone C code using software-in-the-loop (SIL) with
Embedded Coder®.

MEX Verification Settings


To set the MEX verification settings we do the following:

1. In the MATLAB Coder App, select the MEX build type and More Settings.


2. From the Debugging tab, select Disable C compiler optimizations and click Generate.
Technical Articles and Newsletters

3. Run our test script against the generated MEX file to check that the test script completes without error.

Once the script completes, we find a MEX file in the current folder and a .pdb file in the build folder. We copy the .pdb file into the current folder.

SIL Verification Settings


To set the SIL verification settings we do the following:

1.In the MATLAB Coder App, select the Static Library (.lib) build type and More Settings.


2. From the Build Configuration options in the Toolchain tab, select Debug, close the settings dialog, and click Generate.
Technical Articles and Newsletters

4. Click Test and run our test script against the generated MEX file.

Once the script completes, we copy the .pdb file from the build folder into the current folder.

Profiling with Code Analyst


In our profiling script, we replace the call to do_intense_computations with do_intense_computations_mex or do_intense_computations_sil. A straightforward way of doing this is to use the profiling script
as the test script to exercise the MEX file. We then click Verify Generated MEX.

We switch to CodeAnalyst and start profiling. The profiling run will last 20 seconds. After the run, we navigate to the profiling data collected for the functions within the MEX file.
Technical Articles and Newsletters

CodeAnalyst shows a summary view of the information captured during profiling. We need to find the information for the MEX file by looking through the list of modules.


Here we find the MEX file running as part of the MATLAB process. We double-click on the entry to access the detailed profiling information.
Technical Articles and Newsletters

The profiling data shows that that the convolution operation takes approximately 10 times longer than the FFT operation.

Summary
In this example we saw how to set up an environment for profiling MEX files to accelerate MATLAB code and standalone C code for embedded targets. Using AMD CodeAnalyst, we profiled the running
code without having to modify existing MATLAB code. We quickly determined which functions in our MATLAB code were responsible for most of the computation and thus could be performance
bottlenecks. We can now investigate the MATLAB code, look for opportunities to optimize it, and then rebuild and profile the MEX code again.

About the Author


Paul Peeling is a consultant engineer who specializes in signal processing, machine learning, and code generation for embedded hardware. He works with MATLAB and Simulink users to
develop algorithms and model systems in multiple domains, and deploy the code to real-time targets. Paul holds a Ph.D. in statistical signal processing from the University of Cambridge.
Published 2017 - 93068v00

Technical Articles and Newsletters

Products Used
• MATLAB

• Embedded Coder

• MATLAB Coder

Learn More
• The Joy of Generating C Code from MATLAB

• MEX Generation for Faster Simulation

• MathWorks Consulting Services

View Articles for Related Capabilities


• Technical Computing

• Embedded Code Generation

• Algorithm Development

mathworks.com
© 1994-2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or
registered trademarks of their respective holders.

Join the conversation


Technical Articles and Newsletters

Fitting and Extrapolating U.S. Census Data

By Cleve Moler, MathWorks

“Growth of U.S. Population Is at Slowest Pace Since 1937." This New York Times headline prompted me to revisit an old chestnut: fitting and extrapolating census data. In the process, I have added a
couple of nonlinear fits, namely, the logistic curve and the double exponential Gompertz model.

The experiment is older than MATLAB®. It started as an exercise in Computer Methods for Mathematical Computations, by Forsythe, Malcolm, and Moler, published 40 years ago. We were using Fortran
back then. The data set has been updated every ten years since the book was published. Today, MATLAB graphics make it easier to vary the parameters and see the results, but the underlying
mathematical principle remains unchanged:

* Using polynomials of even modest degree to predict the future by extrapolating data is a risky business.

The famous New York Yankees catcher and budding computational scientist Yogi Berra once said, "It's tough to make predictions, especially about the future." We’re going to use polynomials, splines,
exponentials, and the census app in Cleve’s Laboratory to do just that.

The Data
The data for our experiment comes from the decennial census of the U.S. for the years 1900 to 2010 (numbers are in millions):

1900 75.995
1910 91.972
1920 105.711
1930 123.203
1940 131.669
1950 150.697
1960 179.323
1970 203.212
1980 226.505
1990 249.633
2000 281.422
2010 308.746

The task is to extrapolate the size of the population beyond 2010. Using the censusapp, let's see how an extrapolation of just seven years, from 2010 to 2017, matches the Census Bureau model. Before
you read any further, pause and make your own guess.
The Census App
Here's the opening screen of the censusapp. The plus and minus buttons change the extrapolation year in the title. If you go beyond 2030, the plot zooms out.

Twelve decades of census data. Let’s extrapolate seven more years.

The app’s pull-down menu offers seven models:

census data
polynomial
pchip
spline
exponential
logistic
gompertz

Forty years ago, we only had polynomials.

The Target Value


The United States Census Bureau website provides a dynamic population clock that operates continuously. Here is the snapshot taken at noon, EDT, on Census Day, April 1, 2017. This is the
designated time to capture the census value for the year.
The population clock on April 1, 2017.

So, the target value for extrapolating the census data to 2017 is 324.790 million.

Using Polynomials
Polynomials like to wiggle. Constrained to match data within a particular interval, they go crazy outside that interval. In this experiment, there are 12 data points. The censusapp lets you vary the
polynomial degree between 0 and 11. Polynomials with degree less than 11 approximate the data in a least squares sense. The polynomial of degree 11 interpolates the data exactly. As the degree
increases, the approximation of the data becomes more accurate, but the behavior beyond 2010 (or before 1900) becomes more violent. Here are degrees 2 and 7, 9, 11, superimposed on one plot.

Polynomials of degree greater than two are not suitable for extrapolation.
The quadratic fit is the best behaved. When evaluated at year 2017, it misses the target by 7.5 million, but it fails to predict the decreasing rate of growth observed by the Census Bureau. (Of course,
there is no reason to believe that the U.S. population grows in time like a second-degree polynomial.)

The interpolating polynomial of degree 11 tries to escape even before it gets to 2010, and it goes negative late in 2014.

Extrapolating with Splines


MATLAB has two piecewise cubic interpolating polynomials: spline and pchip. The classic spline is smooth because it has two continuous derivatives. Its competitor, pchip, sacrifices a continuous
second derivative to preserve shape and avoid overshoots. Neither of these polynomials is intended for extrapolation, but we will use them anyway.

Their behavior beyond the interval is determined by their end conditions. The classic spline uses the so-called not-a-knot condition. It is actually a single cubic in the last two subintervals. That cubic is
also used for extrapolation beyond the endpoint. pchip uses just the last three data points to create a different shape-preserving cubic for use in the last subinterval and beyond.

Let's zoom in on spline and pchip.

pchip happens to produce a reasonable extrapolation; spline does not.

Both are predicting a decreasing rate of growth beyond 2010, just like the Census Bureau. But spline is painting a gloomy picture. The value of 314.6 million for 2017 is 10 million below the population
clock value, and is near the maximum. On the other hand, pchip gets lucky, and its 2017 value of 325.1 million comes within 0.3 million of the population clock value. Looking into the future, pchip
reaches a maximum of 360.2 million in 2047. That’s a prediction to ponder.

Three Exponentials
As I said, there is no good reason to model population growth by a polynomial, piecewise or not. But because we can expect a growth rate proportional to the size of the population, there is good reason
to use an exponential.

bt
p(t) ≈ α e

Many authors have proposed ways to modify this model to avoid its unbounded growth. I have added two of these to the censusapp. One is the logistic model.

−ct
p(t) ≈ α/(1 + b e )

The other is the Gompertz double exponential model, named after Benjamin Gompertz, a 19th-century, self-educated British mathematician and astronomer.

−ct
−b e
p(t) ≈ α e

In both models the growth is limited because the approximating term approaches α as t approaches infinity.

In all three of the exponential models, the parameters α , b , and possibly c , appear nonlinearly. In principle, I could use lsqcurvefit to search in two or three dimensions for a least squares fit to the
census data. But I have an alternative: By taking one or two logarithms, I obtain a separable least squares model where, at most, one parameter, α , appears nonlinearly.

For the exponential model, take one logarithm.

log p ≈ log α + bt

Fit the logarithm of the data by a straight line and then exponentiate the result. No search is required.

For the logistic model, take one logarithm.

log (α/p − 1) ≈ log b − ct

For any value of α , the parameters log b and c appear linearly and can be found without a search. So, use a one-dimensional minimizer to search for α . I could use fminbnd or its textbook version,
fmintx, from Numerical Methods with MATLAB.

For the Gompertz model, take two logarithms.

log log α/p ≈ log b − ct

Again, do a one-dimensional search for the minimizing α , solving for log b and c at each step.

I should point out that taking logarithms changes the fit criterion. I am doing a least squares fit to the log of the data, not to the actual data.

Results
Here are the three resulting fits, extrapolated over more than 200 years to the year 2250.

Exponential models extrapolating over 200 years.

The pure exponential model reaches 5 billion by that time, and is growing ever faster. I think that's unreasonable.

The value of α in the Gompertz fit turns out to be 4309.6, so the population will be capped at 4.3 billion. But it has only reached 1.5 billion 200 years from now. Again, unlikely.

The value of α in the logistic fit turns out to be 756.4, so the predicted U.S. population will slightly more than double over the next 200 years. Despite the Census Bureau's observation that our rate of
growth has slowed, we are not yet even halfway to our ultimate population limit.

I'll let you be the judge of that prediction.

Published 2017 - 93130v00

Products Used
• MATLAB
Learn More
• Cleve’s Laboratory

• Cleve’s Corner Blog: Splines and Pchips

• U.S. Census Bureau Population Clock

View Articles for Related Capabilities


• Technical Computing

• Mathematical Modeling

• Data Analysis

mathworks.com
© 1994-2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or
registered trademarks of their respective holders.

Join the conversation


Technical Articles and Newsletters

Speeding Up Signal Processing Algorithm Simulation in Simulink Models

By Akash Gopisetty, MathWorks

Signal processing system designs often have high computational complexity due to the algorithm or data-intensive applications involved. Building and simulating these complex systems can be time-
consuming. The Dataflow domain feature in Simulink® provides a way to reduce model simulation times. This feature accelerates simulation by automatically partitioning Simulink models and executing
them in parallel using the CPU cores available on the host computer.

This article shows you how to set up Dataflow in three simple steps. We then demonstrate Dataflow in action, using a radio model as an example, and compare model simulation times with and without
Dataflow enabled.

The models used in this example are available for download.

Types of Parallelism Used by Dataflow


To partition models and execute them in parallel, Dataflow uses one of the following combinations of data and task parallelism (Figure 1):

• Explicit parallelism processes different data sets through different algorithms.

• Unfolding parallelism processes consecutive frames of a data stream through the same algorithm.

• Pipelining parallelism processes different parts of the same data through different algorithms.
Technical Articles and Newsletters

Figure 1. Types of parallelism used by Dataflow.

Setting Up Dataflow
To enable the Dataflow domain in a Simulink model, you first implement a subsystem. The way you do this depends on how far your design has progressed.

If you are just beginning the design process, use the Dataflow Subsystem Block in DSP System Toolbox™ (Figure 2). This block is preconfigured and ready to use. You just drag it into the Simulink
model and populate it with algorithmic components.
Technical Articles and Newsletters

Figure 2. Dataflow subsystem in the DSP System Toolbox block library.

If you have already built your design model, place the blocks modeling the algorithm that you would like to parallelize in a subsystem and set up Dataflow as follows:

1. Select the subsystem you just created.

2. Select the Set execution domain check box from the Execution tab of the Property Inspector.
3. Set the Domain option to Dataflow.
Technical Articles and Newsletters
Inside the subsystem, the > icon on the bottom left indicates that the subsystem is set to the Dataflow domain.

The Dataflow domain first profiles the model by running it on a single thread and then automatically partitions the subsystem for multithreaded execution.

Dataflow in Action
Our example model simulates a radio transmitter and receiver. It contains digital up and down converters to adjust the signal frequencies, and implements a modulator and demodulator (Figure 3). The
input is a speech recording sampled at 8 kHz. The outputs are two spectrum analyzers and an audio sink.


Figure 3. Radio model with a single-channel audio input.
First, we measure the time taken to simulate this model without enabling Dataflow1. With the output blocks commented out, we can focus on simulating the algorithm, and are not bound by the fixed
amount of time needed to run the scopes and audio output. Technical Articles and Newsletters
We measure simulation time using the tic-toc commands:

modelname = 'mono_radiomodel';
tic;
simData = sim(modelname);
t = toc

The execution time to run the model is 3.67 seconds.

Now let’s introduce Dataflow. We’ll place the blocks representing the algorithm into a subsystem and set the domain to Dataflow (Figure 4).


Figure 4. Dataflow enabled on the radio model with a single-channel audio input.
Technical Articles and Newsletters
The Dataflow assistant displays suggested model setting changes (Figure 5).

Figure 5. Dataflow assistant showing suggested changes to model settings.


Technical Articles and Newsletters
One change recommended by the assistant is to add latency. Latency is typically added to a model when Dataflow identifies an opportunity for parallelism to increase throughput. The delays added
along the signal lines are indicated with a z-n label.

We accept the changes and save the model with Dataflow enabled as mono_radiomodel_dataflow.

We then measure the execution time of the new subsystem using the same tic-toc commands that we used before.

modelname = 'mono_radiomodel_dataflow';
tic;
simData2 = sim(modelname);
t_Dataflow = toc

The execution time with Dataflow enabled is 2.5 seconds, which is 1.7 times faster than normal, single-thread execution. The speedup is due to the compiler optimizations, model settings changes, and
latency added by Dataflow.

However, the model was executed on just one thread, and the speedup is not significant. This is because most of the computational load is concentrated in the up- and down-converter blocks. Dataflow
works best when the computational load is spread across the model, providing more opportunities to create parallel threads. In the next section, we extend our model and show how implementing
Dataflow further improves simulation performance.

Working with Larger Models


We increase the computational complexity of the model by introducing a multichannel audio input signal. This doubles the amount of data that needs to be processed and gives Dataflow more avenues
to optimize simulation performance. Figure 6 shows the model modified with a stereo audio, which takes 18.6 seconds to run. By enabling the signal dimensions information overlay, we see that the
signal input does indeed have two audio channels.
Technical Articles and Newsletters


Figure 6. Radio model with a stereo input multichannel audio signal.

After turning on Dataflow and rerunning the model, we observe an execution time of 4.5 seconds—an almost four-fold speedup—with the model being run on five concurrent threads (Figure 7).
Technical Articles and Newsletters

Figure 7. Dataflow assistant showing the latency and number of threads for model execution.

Multithreaded Code Generation with Dataflow


Dataflow supports both single-core and multicore C/C++ code generation with Simulink Coder™ and Embedded Coder®. You first enable the Allow tasks to be executed concurrently on target
parameter in the Solver pane of the Simulink model and then generate code using Ctrl + B. Code generated for desktop targets is multithreaded via OpenMP. Code generated for Embedded
Coder targets is multithreaded via POSIX.

Figure 8 shows OpenMP C code generated from our radio model, including concurrent tasks created by Dataflow.
Technical Articles and Newsletters

Figure 8. Multithreaded code generated with Dataflow and OpenMP.

Limitations of Dataflow
While Dataflow helps speed up most simulations, it might not be applicable to all models—for example, smaller, less complex models or models with the computational load concentrated in a few blocks.
In these cases, the speed-up achieved by Dataflow does not offset the overheads needed to synchronize and execute the model on parallel threads. As the radio model example showed, Dataflow does
best when the computational load is spread evenly across the model, because an evenly spread load provides more opportunities to partition the model for parallel execution.

In terms of modeling limitations, as of Release 2020b Dataflow does not support continuous blocks, variable-sized signals, or virtual Simulink buses for multithreaded simulation.

Summary
The Dataflow domain lets you identify modeling patterns in a Simulink model that can be distributed into multiple threads and executed in parallel. This approach takes advantage of the processing
power available on the host CPU, optimizes throughput, and reduces model simulation time. The Dataflow domain is most effective when the computational load is spread out across the model so that
parallelism can be introduced, and it works only with discrete signals.

1 ® ® ®
All simulations were run on a Windows desktop computer with Intel Xeon CPU W-2133 @ 3.6 GHz 6 Cores 12 threads processor.
Published 2021

Technical Articles and Newsletters

Products Used
• Simulink

• DSP System Toolbox

• Embedded Coder

• Simulink Coder

Learn More
• Dataflow Domain - Overview

• Multicore Simulation and Code Generation of Dataflow Domains - Example

• How to Run Simulink Simulations Faster Using Dataflow (3:06) - Video

View Articles for Related Capabilities


• Embedded Code Generation

• Algorithm Development

• System Design and Simulation

• Simulation and Model-Based Design

• Parallel Computing

View Articles for Related Industries


• Communication Devices

• Consumer Electronics
mathworks.com
Technical Articles and Newsletters
© 1994-2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or
registered trademarks of their respective holders.

Join the conversation


Single Hydraulic Cylinder Simulation
This example shows how to use Simulink® to model a hydraulic cylinder. Yo can apply these concepts to applications where you
need to model hydraulic behavior. See two related examples that use the same basic components: four cylinder model and two View MATLAB Command
cylinder model with load constraints.

• Note: This is a basic hydraulics example. You can more easily build hydraulic and automotive models using Simscape™ Driveline™ and Simscape Fluids™.

• Simscape Fluids provides component libraries for modeling and simulating fluid systems. It includes models of pumps, valves, actuators, pipelines, and heat
exchangers. You can use these components to develop fluid power systems such as front-loader, power steering, and landing gear actuation systems. Engine
cooling and fuel supply systems can also be developed with Simscape Fluids. You can integrate mechanical, electrical, thermal, and other systems using
components available in the Simscape product family.

• Simscape Driveline provides component libraries for modeling and simulating one-dimensional mechanical systems. It includes models of rotational and
translational components, such as worm gears, planetary gears, lead screws, and clutches. You can use these components to model the transmission of
mechanical power in helicopter drivetrains, industrial machinery, vehicle powertrains, and other applications. Automotive components, such as engines, tires,
transmissions, and torque converters, are also included.

Analysis and Physics of the Model


Figure 1 shows a schematic diagram of the basic model. The model directs the pump flow, Q, to supply pressure, p1, from which laminar flow, q1ex, leaks to exhaust.
The control valve for the piston/cylinder assembly is modeled as turbulent flow through a variable-area orifice. Its flow, q12, leads to intermediate pressure, p2, which
undergoes a subsequent pressure drop in the line connecting it to the actuator cylinder. The cylinder pressure, p3, moves the piston against a spring load, resulting
in position x.

Figure 1: Schematic diagram of the basic hydraulic system

At the pump output, the flow is split between leakage and flow to the control valve. We model the leakage, q1ex, as laminar flow (see Equation Block 1).

Equation Block 1
We modeled turbulent flow through the control valve with the orifice equation. The sign and absolute value functions accommodate flow in either direction (see
Equation Block 2).

Equation Block 2

The fluid within the cylinder pressurizes due to this flow, q12 = q23, minus the compliance of the piston motion. We also modeled fluid compressibility in this case
(see Equation Block 3).

Equation Block 3
We neglected the piston and spring masses because of the large hydraulic forces. We completed the system of equations by differentiating this relationship and
incorporating the pressure drop between p2 and p3. Equation Block 3 models laminar flow in the line from the valve to the actuator. Equation block 4 gives the force
balance at the piston.

Equation Block 4

Modeling
Figure 2 shows the top level diagram of the model. The pump flow and the control valve orifice area are simulation inputs. The model is organized as two
subsystems: the 'Pump' and the 'Valve/Cylinder/Piston/Spring Assembly'.

Opening the Model and Running the Simulation


To open this model, type sldemo_hydcyl at MATLAB® terminal (click on the hyperlink if you are using MATLAB Help). Press the "Play" button on the model toolbar
to run the simulation.

The model logs relevant data to MATLAB workspace, into the Simulink.SimulationOutput object out. The signal logging data is stored in the out object, in a structure
called sldemo_hydcyl_output. Logged signals have a blue indicator (see the model). For more information, see View and Access Signal Logging Data.
Figure 2: Single cylinder model and simulation results

'Pump' Subsystem
Right-click the Pump masked subsystem and select Mask > Look Under Mask. The pump model computes the supply pressure as a function of the pump flow and
the load (output) flow (Figure 3). Qpump is the pump flow data (saved in the model workspace). A matrix with column vectors of time points and the corresponding
flow rates [T, Q] specifies the flow data. The model calculates pressure p1 as indicated in Equation Block 1. Because Qout = q12 is a direct function of p1 (via the
control valve), an algebraic loop is formed. An estimate of the initial value, p10, enables a more efficient solution.
Figure 3: The pump subsystem

We masked the 'Pump' subsystem in Simulink to allow the user to easily access the parameters (see Figure 4). The parameters to be specified are T, Q, p10, and C2.
We then assigned the masked block the icon shown in Figure 2, and saved it in a Simulink library.

Figure 4: Entering pump parameters


'Valve/Cylinder/Piston/Spring Assembly' Subsystem
Right-click the 'Valve/Cylinder/Piston/Spring Assembly' subsystem and select Mask > Look Under Mask to see the Actuator subsystem (see Figure 5). A system of
differential-algebraic equations models the cylinder pressurization with the pressure p3, which appears as a derivative in Equation Block 3 and is used as the state
(integrator). If we neglect piston mass, the spring force and piston position are direct multiples of p3 and the velocity is a direct multiple of p3's time derivative. This
latter relationship forms an algebraic loop around the 'Beta' Gain block. The intermediate pressure p2 is the sum of p3 and the pressure drop due to the flow from the
valve to the cylinder (Equation Block 4). This relationship also imposes an algebraic constraint through the control valve and the 1/C1 gain.

The control valve subsystem computes the orifice (Equation Block2). It uses as inputs the upstream and downstream pressures and the variable orifice area. The
'Control Valve Flow' Subsystem computes the signed square root:

Three nonlinear functions are used, two of which are discontinuous. In combination, however, y is a continuous function of u.

Figure 5: The valve/cylinder/piston/spring subsystem

Results
Simulation Parameters

We simulated the model using the following data. The information is loaded from a MAT-file - sldemo_hydcyl_data.mat, which is also used for the other two
hydraulic cylinder models. The users can enter data via the Pump and Cylinder Masks shown in Figures 4 and 6.
T = [0 0.04 0.04 0.05 0.05 0.1 ] sec

Q = [0.005 0.005 0 0 0.005 0.005] m^3/sec


Figure 6: Entering valve/cylinder/piston/spring assembly parameters

Plotting Simulation Results

The system initially steps to a pump flow of 0.005 m^3/sec=300 l/min, abruptly steps to zero at t=0.04 sec, then resumes its initial flow rate at t=0.05 sec.

The control valve starts with zero orifice area and ramps to 1e-4 sq.m. during the 0.1 sec simulation time. With the valve closed, all of the pump flow goes to
leakage so the initial pump pressure increases to p10 = Q/C2 = 1667 kPa.

As the valve opens, pressures p2 and p3 build up while p1 decreases in response to the load increase as shown in Figure 7. When the pump flow cuts off, the spring
and piston act like an accumulator and p3 decreases continuously. Then the flow reverses direction, so p2, though relatively close to p3, falls abruptly. At the pump
itself, all of the back-flow leaks and p1 drops radically. The behavior reverses as the flow is restored.

The piston position is directly proportional to p3, where the hydraulic and spring forces balance. Discontinuities in the velocity at 0.04 sec and 0.05 sec indicate
negligible mass. The model reaches a steady state when all of the pump flow again goes to leakage, now due to zero pressure drop across the control valve (which
means p3 = p2 = p1 = p10).
Figure 7: Simulation Results: System Pressures
Figure 8: Simulation Results: Hydraulic Cylinder Piston Position

Closing the Model


Close the model and clear generated data.

Related Examples
• Four Hydraulic Cylinder Simulation
• Two Cylinder Model with Load Constraints

More About
• Decide How to Visualize Simulation Data
Microcontroller with GPIO, ADC and DAC Connections
This example shows how to model the interface between a microcontroller unit (MCU) and a physical system. Here the
microcontroller's GPIO, ADC and DAC connections are used to control a DC motor and connected load with limited angle travel. View MATLAB Command
Load angle measurement is via a potentiometer sensor. This measurement is calibrated by initially ramping the rotor position until
the photodiode detects the zero-angle light pulse from the LED. Once calibrated the MCU commands a 0.1Hz 45 degree amplitude sinusoid.

Model

Controller Subsystem
GPIO 1 Subsystem

Motor Driver Subsystem


Photodiode Subsystem

Potentiometer Subsystem
Simulation Results from Simscape Logging
The plot below shows the performance of the motor control system. At the start of simulation, the controller spins the motor until it finds a known position of the motor
shaft (0 degrees). After that, the controller tracks the reference signal.
Strain Gauge and Wheatstone Bridge
This model shows how to model a strain gauge and measurement amplifier. The strain gauge forms one leg of a Wheatstone
bridge, which is connected to a differential amplifier. A second op-amp is then used to both amplify and apply a low-pass filter to the View MATLAB Command
measurement signal. The op-amps are modeled at a system level, with the user specifying parameters such as open-loop
bandwidth, gain and maximum slew rate. In this circuit, the dynamics are primarily set by the low-pass filter. The op-amp bandwidth and maximum slew rate have
little impact on the step response.

Model

Simulation Results from Simscape Logging


This code plots the actual and measured strain from the model of ee_strain_gauge resulting from two tests. The first test sets the resistor and capacitor in the low
pass filter to the maximum value of their tolerance ranges. The second test sets the values for those components to the minimum of their tolerance ranges. The plot
shows the effects this has on the strain measurement.
Linear Voltage Regulator with Thermal Effects
This example shows a low-cost voltage regulator circuit whose performance depends on both load current and temperature. Bias
resistor R1 ensures that the voltage at the transistor base is close to the rated zener voltage. The regulator output voltage is also View MATLAB Command
approximately at this voltage, the base-emitter voltage being a few tenths of a volt. The precise base-emitter voltage depends on the
transistor working point (which in turn depends on the load) and also the temperature. Resistor R2 only serves to provide some protection in the event of a transient
output short circuit.

This type of model can be used to validate that selected circuit components result in an adequate level of voltage regulation. It can also be used to size the heatsink
required to keep the transistor junction temperature within the permitted operating range. By modeling both electrical and thermal properties, understanding of the
trade-offs between electrical and thermal parameter choices is gained.

Better regulation can be achieved by using feedback. See example Linear Voltage Regulator with Feedback (>> ee_voltreg_linear_feedback).

Model

Simulation Results from Simscape Logging


The plot below shows the output of the voltage regulator holding close to the desired output of 10 V. It also shows the temperature of the NPN case and its heatsink
as the cyclic load turns on and off.
Linear Voltage Regulator with Feedback
This example shows a simple voltage regulator circuit constructed from discrete components. A fluctuating supply is modeled as
20V DC plus a 1V sinusoidal variation. The zener diode D1 sets the non-inverting input of the op-amp to 3.2V, and hence as the op- View MATLAB Command
amp has a large gain, the op-amp inverting input and output are also at 3.2V. Hence the regulator voltage output is regulated to be
3.2*(1000+470)/470=10V. The NPN bipolar transistor is required to provide higher currents than is possible from a typical op-amp. The model can be used to check
circuit operation, and to support selection of components to achieve the desired voltage regulation.

Model

Simulation Results from Simscape Logging


The plot below shows the output of the voltage regulator holding at a constant 10V even as the input voltage fluctuates.
Fourier Transforms
The Fourier transform is a mathematical formula that relates a signal sampled in time or space to the same signal sampled in
frequency. In signal processing, the Fourier transform can reveal important characteristics of a signal, namely, its frequency Try This Example
components.
View MATLAB Command
The Fourier transform is defined for a vector x with n uniformly sampled points by

n−1

jk
yk + 1 = ω x j + 1.
j=0

ω = e
/
−2πi n
is one of n complex roots of unity where i is the imaginary unit. For x and y , the indices j and k range from 0 to n − 1 .

The fft function in MATLAB® uses a fast Fourier transform algorithm to compute the Fourier transform of data. Consider a sinusoidal signal x that is a function of
1
time t with frequency components of 15 Hz and 20 Hz. Use a time vector sampled in increments of of a second over a period of 10 seconds.
50

Ts = 1/50;
t = 0:Ts:10-Ts;
x = sin(2*pi*15*t) + sin(2*pi*20*t);
plot(t,x)
xlabel('Time (seconds)')
ylabel('Amplitude')
Compute the Fourier transform of the signal, and create the vector f that corresponds to the signal's sampling in frequency space.

y = fft(x);
fs = 1/Ts;
f = (0:length(y)-1)*fs/length(y);

When you plot the magnitude of the signal as a function of frequency, the spikes in magnitude correspond to the signal's frequency components of 15 Hz and 20 Hz.

plot(f,abs(y))
xlabel('Frequency (Hz)')
ylabel('Magnitude')
title('Magnitude')
The transform also produces a mirror copy of the spikes, which correspond to the signal's negative frequencies. To better visualize this periodicity, you can use the
fftshift function, which performs a zero-centered, circular shift on the transform.

n = length(x);
fshift = (-n/2:n/2-1)*(fs/n);
yshift = fftshift(y);
plot(fshift,abs(yshift))
xlabel('Frequency (Hz)')
ylabel('Magnitude')
Noisy Signals
In scientific applications, signals are often corrupted with random noise, disguising their frequency components. The Fourier transform can process out random noise
and reveal the frequencies. For example, create a new signal, xnoise, by injecting Gaussian noise into the original signal, x.

rng('default')
xnoise = x + 2.5*randn(size(t));

Signal power as a function of frequency is a common metric used in signal processing. Power is the squared magnitude of a signal's Fourier transform, normalized
by the number of frequency samples. Compute and plot the power spectrum of the noisy signal centered at the zero frequency. Despite noise, you can still make out
the signal's frequencies due to the spikes in power.

ynoise = fft(xnoise);
ynoiseshift = fftshift(ynoise);
power = abs(ynoiseshift).^2/n;
plot(fshift,power)
title('Power')
xlabel('Frequency (Hz)')
ylabel('Power')

Computational Efficiency
Using the Fourier transform formula directly to compute each of the n elements of y requires on the order of n floating-point operations. The fast Fourier transform
2

algorithm requires only on the order of nlogn operations to compute. This computational efficiency is a big advantage when processing data that has millions of data
points. Many specialized implementations of the fast Fourier transform algorithm are even more efficient when n is a power of 2.

Consider audio data collected from underwater microphones off the coast of California. This data can be found in a library maintained by the Cornell University
Bioacoustics Research Program. Load and format a subset of the data in bluewhale.au, which contains a Pacific blue whale vocalization. Because blue whale calls
are low-frequency sounds, they are barely audible to humans. The time scale in the data is compressed by a factor of 10 to raise the pitch and make the call more
clearly audible. You can use the command sound(x,fs) to listen to the entire audio file.

whaleFile = 'bluewhale.au';
[x,fs] = audioread(whaleFile);
whaleMoan = x(2.45e4:3.10e4);
t = 10*(0:1/fs:(length(whaleMoan)-1)/fs);
plot(t,whaleMoan)
xlabel('Time (seconds)')
ylabel('Amplitude')
xlim([0 t(end)])

Specify a new signal length that is the next power of 2 greater than the original length. Then, use fft to compute the Fourier transform using the new signal length.
fft automatically pads the data with zeros to increase the sample size. This padding can make the transform computation significantly faster, particularly for sample
sizes with large prime factors.

m = length(whaleMoan);
n = pow2(nextpow2(m));
y = fft(whaleMoan,n);

Plot the power spectrum of the signal. The plot indicates that the moan consists of a fundamental frequency around 17 Hz and a sequence of harmonics, where the
second harmonic is emphasized.
f = (0:n-1)*(fs/n)/10; % frequency vector
power = abs(y).^2/n; % power spectrum
plot(f(1:floor(n/2)),power(1:floor(n/2)))
xlabel('Frequency (Hz)')
ylabel('Power')

See Also
fft | fft2 | fftn | fftshift | fftw | ifft | nextpow2

Related Topics
• 2-D Fourier Transforms
Linear LED Driver
This example shows a LED driver based on a linear current regulator. The scope shows the light and current output and the supply
voltage. The output comes into regulation for a supply voltage greater than about 12V. View MATLAB Command

Model

Simulation Results from Simscape Logging


The plot below shows the output of the current regulator used in an LED driver circuit. Once the supply voltage reaches 12V, the driver circuit regulates its output.
The plot below shows the driver efficiency and LED current as functions of the supply voltage.
Parameterize the Lookup Table-Based MOSFET from SPICE
This example shows how to use the SPICE simulation results of a metal–oxide–semiconductor field-effect transistor (MOSFET) to set the parameter
values of an N-Channel MOSFET (Lookup table-based) in Simscape™. Then, it compares the N-Channel MOSFET characteristics in Simscape with View MATLAB Command
the SPICE netlist simulation results.

Open the N-Channel MOSFET (Lookup Table-Based) Model

Open the MOSFET Subcircuit


The subcircuit contains a SPICE model of an N-Channel power transistor. To open it, in the MATLAB command window, enter edit IAUC100N04S6L014.cir.

Create a Transfer Characteristic Netlist


You can create a SPICE netlist that specifies the target operating range for the subcircuit. The IAUC100N04S6L014_idvgs.net netlist simulates the transfer characteristic with drain-
source voltage list.

* Transfer characteristic of MOSFET IAUC100N04S6L014


.opt DampInductors=0 Thev_Induc=1 Gfarad=0 Gfloat=0 reltol=1e-05 abstol=1e-05 vntol= 1e-05 Gmin=0 cshunt=0 cshuntintern=0 gshunt=0 topologycheck=0

X1 dut1 dut2 dut3 dut4 dut5 IAUC100N04S6L014


V1 dut1 0 2
V2 dut2 0 pwl(0 0 20 4.5)
V3 dut3 0 0
V5 dut5 0 27
.step V1 list 2 5 8 11 14
.tran 1m 20
.lib IAUC100N04S6L014.cir
.end
Set Lookup Table Parameters for Transfer Characteristic
To obtain the required MOSFET transfer characteristics, run the simulation in SPICE. The ee_mosfet_tabulated_setparam script uses the simulation results stored in the
IAUC100N04S6L014_idvgs1.raw raw-files to set the parameter values for the N-Channel MOSFET (Lookup Table-Based).

Compare Transfer Characteristic


The plot below compares the transfer characteristic of the N-Channel MOSFET (Lookup table-based) with the SPICE subcircuit simulation results.

Create an Output Characteristic Netlist


To parameterize an N-Channel MOSFET (Lookup table-based), you can also use an output characteristic SPICE data. The IAUC100N04S6L014_idvds.net netlist simulates the
transfer characteristic with gate-source voltage list.

* Output characteristic of MOSFET IAUC100N04S6L014


.opt DampInductors=0 Thev_Induc=1 Gfarad=0 Gfloat=0 reltol=1e-05 abstol=1e-05 vntol= 1e-05 Gmin=0 cshunt=0 cshuntintern=0 gshunt=0 topologycheck=0

X1 dut1 dut2 dut3 dut4 dut5 IAUC100N04S6L014


V1 dut1 0 pwl(0 0 20 15)
V2 dut2 0 2
V3 dut3 0 0
V5 dut5 0 27
.step V2 1 4 0.5
.tran 2m 20
.lib IAUC100N04S6L014.cir
.end
Set Lookup Table Parameters for Output Characteristic
The IAUC100N04S6L014_idvds1.raw raw file stores the output characteristics simulated in SPICE. You can change the raw file path and plot type in Define Conditon or by using
the set_param function.

Compare Output Characteristic


The plot below compares the output characteristic of the N-Channel MOSFET (Lookup table-based) with the SPICE subcircuit simulation results.
Supercapacitor Charging and Discharging Behavior
This example shows the voltage output by a Supercapacitor block as it is charged and then discharged. To charge the
Supercapacitor, a current of 100 mA is input to the Supercapacitor for 100 seconds. The Supercapacitor is then rested for one View MATLAB Command
minute. For the next hour, to discharge the Supercapacitor, a load of 50 mA is stepped on for one second in every 50 seconds. The
Supercapacitor is then rested until the end of the simulation. The scope displays the Supercapacitor charging/discharging current and voltage.

Model
Ultracapacitor With Converter
This example shows how a DC-DC converter can be used to maintain a constant load voltage when drawing power from an
ultracapacitor. Initially the converter supplies power to the load, and as it does so, the capacitor voltage drops. The protection circuit View MATLAB Command
disconnects the load when the capacitor voltage drops below a threshold of 4V. At 10 seconds the generator is turned on, and
power is supplied to both the load and to the capacitor to recharge it.

Model

Low Charge Protection Circuit Subsystem


Simulation Results from Simscape Logging
The plot below shows voltage supplied to a resistive load from an DC-DC converter and a generator. The DC-DC converter supplies power to the load. A low charge
protection circuit disconnects the load when the ultracapacitor voltage drops below 4V. At 10 seconds the generator turns on, supplying power to the load and
charging the ultracapacitor.
Modeling an Integrated Circuit
This example shows two ways to create a model of an integrated circuit that can be used in conjunction with other Simscape™
Electrical™ blocks. The first approach is to build a behavioral model using Simscape Foundation Library PS blocks and/or View MATLAB Command
Simulink® blocks. The second is to build an implementation model from basic Simscape Electrical blocks. To look under the masks
and view the details, select the relevant block and type ctrl-U.

The behavioral model has the advantage of being simpler and potentially running faster. The approach can be extended to complex algorithms as might be
implemented on a PIC or ASIC. Note that the model includes a first order lag to model the 1ns propagation delay. In many applications, this time constant will be
much faster than the overall circuit dynamics, and may not be of interest. However, removing it potentially introduces an algebraic loop if the gate inputs depend in
anyway on the gate output. An alternative is to implement the algorithm (the NOR gate in this case) using only PS blocks rather than Simulink blocks.

The implementation model implements a representation of the actual MOSFET gates used to implement the NOR function. Note that although it is a more
representative model of the actual device, it still has limitations. A key challenge is selecting appropriate parameters for the MOSFET blocks based on the datasheet.
Here all MOSFETS are assumed to have the same parameters which will not always be the case. The main disadvantage of using an implementation model is that
simulation speed is likely to be much slower than the behavioral model.

Model
2-Input NOR (Behavioral Model) Subsystem

2-Input NOR (Implementation Model) Subsystem


Simulation Results from Simscape Logging
The plots below show the inputs and outputs for the two implementations of the NOR circuit. The behavioral model and implementation model have nearly identical
outputs.
PWM Circuit Using 555 Timer
This example shows a pulse-width-modulated (PWM) output implemented using a 555 Timer in astable mode. The duty cycle is set
by a potentiometer, P1. The potentiometer is controlled during run-time via Duty Cycle Control Knob. The scope shows the resultant View MATLAB Command
output from the 555 Timer. To end the simulation, click on the Stop button.

Model

Simulation Results from Scopes


Solar Power Inverter
This example shows how to determine the efficiency of a single-stage solar inverter. The model simulates one complete AC cycle for
a specified level of solar irradiance and corresponding optimal DC voltage and AC RMS current. Using the example model View MATLAB Command
ee_solar_characteristics, the optimal values have been determined as 342V DC and 20.05A AC for an irradiance of 1000W/m^2
and panel temperature of 20 degrees Celsius. Inverter efficiency is determined in two independent ways. The first compares the ratio of AC power out to DC power in
over one AC cycle. The second calculates losses by component by making use of Simscape™ logging. The small difference in calculated efficiency value is due to
differences between trapezoidal integration used by the script and the greater accuracy achieved by the Simulink® variable-step solver.

Model

Simulation Results from Simscape Logging


The plots below show the current output from the inverter and the power dissipated by two of the MOSFETs.
The table below shows the power dissipated by individual components in the ee_solar_inverter model. These totals were calculated from simulation results using
logged Simscape variables and the losses calculation utility ee_getPowerLossSummary.

Efficiency = 96.7342%
Losses in watts by component are as follows:
LoggingNode Power
____________________________ _____

{'ee_solar_inverter.MOS2' } 18.61
{'ee_solar_inverter.MOS4' } 17.01
{'ee_solar_inverter.MOS1' } 15.14
{'ee_solar_inverter.MOS3' } 13.29
{'ee_solar_inverter.Diode4'} 3.53
{'ee_solar_inverter.Diode2'} 2.9
{'ee_solar_inverter.Diode3'} 2.05
{'ee_solar_inverter.Diode1'} 1.4
{'ee_solar_inverter.CL' } 0.4
Thermistor-Controlled Fan
This model shows how fundamental thermal, mechanical and electrical components can be used to model a thermistor-controlled
fan. The heat-generating device starts producing 2 watts at time zero, and then at 40 seconds this increases to 20 watts. The View MATLAB Command
thermistor therefore heats up, and its resistance decreases thereby increasing the voltage across the PWM reference pins. This
increases the PWM frequency which in turn increases average motor current, and the fan speeds up. The additional fan speed increases the convective cooling of
the device, moderating the temperature increase of the device.

This is a system-level model such as might be used for selecting an appropriate thermistor characteristic. The convective heat transfer coefficient used to model
nominal cooling (i.e. when the fan isn't running) would typically be determined by experiment. Knowing the temperature difference and having an estimate of the
device area, the heat transfer coefficient can be calculated. The coefficient for the fan-assisted cooling could then be estimated by running the motor at maximum
RPM, and again measuring the temperature difference. The nominal cooling term just also be taken into account when calculating the fan-cooling coefficient.

The Controlled PWM Voltage and H-Bridge blocks have two modes of operation, namely Averaged and PWM. As this is a system-level model, and the thermal time
constants are measured in seconds, the Averaged mode of operation is used. The PWM mode replicates the PWM control signal which would typically operate at a
few kilohertz.

Model
Simulation Results from Simscape Logging
The plot below shows the electrical, mechanical, and thermal behavior of the thermistor controlled motor. As the temperature of the thermistor changes, the voltage
applied to the motor changes, which alters the speed of the motor and the convective heat transfer from the case. The system reaches steady state after a short
period of time.
PWM-Controlled DC Motor
This model shows how to use the Controlled PWM Voltage and H-Bridge blocks to control a motor. The DC Motor block uses
manufacturer datasheet parameters, which specify the motor as delivering 10W mechanical power at 2500 rpm and no-load speed View MATLAB Command
as 4000 rpm when run from a 12V DC supply. Hence if the PWM reference voltage is set to its maximum value of +5V, then the
motor should run at 4000 rpm. If it is set to +2.5V, then it should run at approximately 2000 rpm. The Simulation model parameter is set to Averaged for both the
Controlled PWM Voltage and H-Bridge blocks, resulting in fast simulation. To validate the averaged behavior, change the Simulation mode parameter to PWM in both
blocks.

Model

Simulation Results from Simscape Logging


The plot below shows the current passing through the motor and the speed of the motor shaft.
NPN Bipolar Transistor Characteristics
This example shows generation of the Ic versus Vce curve for an NPN bipolar transistor. Define the vector of base currents and
minimum and maximum collector-emitter voltages by double clicking on the block labeled 'Define Conditions (Ib and Vce)'. Run the View MATLAB Command
tests and generate plots of the curves by clicking in the model on hyperlink 'plot curves'.

This type of plot can be compared against a manufacturer datasheet to confirm a correct implementation of the transistor parameters. You can also use this model to
examine the transistor characteristics in the reverse region by specifying a range of negative Vce values. In this region, the gain is defined by the Reverse current
transfer ratio BR parameter. Increase this parameter above one to produce a reverse current gain.

To explore the properties of a PNP bipolar transistor, open model ee_pnp.

Model

Simulation Results from Simscape Logging


The plot below shows collector current (Ic) versus collector-emitter voltage (Vce) characteristics for different levels of base current (Ib).
Technical Articles and Newsletters

Estimating the Frequency Response of a Power Electronic Model: Sinestream vs. Pseudo-Random Binary Sequence (PRBS)

By Antonino Riccobono and Arkadiy Turevskiy, MathWorks

This article is the second in a two-part series. Part 1, Estimating the Frequency Response of a Power Electronics Model, introduced a six-step workflow for estimating the frequency response of an
open-loop boost converter.

Power electronics engineers can use frequency response estimation (FRE) tools available in Simulink Control Design™ to linearize switch-mode power electronic converters modeled, for example, with
Simscape Electrical™ components. With FRE, you select the relevant portion of the converter model and inject a perturbation signal of controllable amplitude and frequency content into the system in
steady state. You can then compute the frequency response or a transfer function that represents the system dynamics near the operating point.

Both narrowband and wideband signals are available in Simulink Control Design (Figure 1). Sinestream is a narrowband perturbation signal because its frequency content is limited to a few frequency
points. Random, chirp, and pseudo-random binary sequence (PRBS) are wideband perturbation signals, as their frequency content is distributed over a certain frequency spectrum.
Technical Articles and Newsletters

Figure 1. Perturbation signals available in the Estimation tab of the Model Linearizer in Simulink Control Design.

This article compares FRE for an open-loop buck converter with sinestream and with PRBS, focusing on estimation time, number of estimated frequency points, and estimation accuracy.
Buck Converter Example Technical Articles and Newsletters
A buck converter is a power electronics topology that can supply a load with a DC voltage lower than the DC supply voltage. It is widely used in many applications with different power ratings, including
consumer electronics products, electric automobiles, more-electric ships and aircraft, renewables, and LED drivers.

Figure 2 shows a switch-mode buck converter modeled with Simscape Electrical™ components. It operates in continuous conduction mode (CCM)—that is, the inductor current never goes to zero in
steady state. The converter operates in open loop, driven by a PWM Generator block with a constant duty cycle. To mimic a real-world embedded controller, sampling is included in the model. The
linearization input and output analysis points are set to identify the control-to-output transfer function.


Figure 2. Buck converter model showing sampling times (green and red), as well as input and output analysis points for frequency response estimation (within the blue rectangles).

Sinestream or PRBS? Setting Up the Comparative Analysis


Sinestream consists of a sequence of sine waves with increasing frequencies. To cover the desired frequency range, the sine wave input needs to be swept at controllable frequency increments. Each
frequency excites the system for a certain number of periods. The estimation time can be long if many frequency points are required or if frequency response needs to be estimated at low frequencies.

Pseudo-random binary sequence (PRBS) reduces the estimation time. PRBS is a deterministic signal that commutes between two values and has white-noise-like properties. A PRBS signal is
inherently periodic, with a maximum period length of 2n-1, where n is the PRBS order.

Figure 3 shows the sinestream signal injected at the output of the Duty Cycle block of the buck converter. It has been set with the Model Linearizer app to have 15 logarithmically spaced frequencies
from 100 Hz to 20 kHz, each with a peak amplitude of 0.02 (2% duty cycle). Each frequency is represented by four periods.
Technical Articles and Newsletters

Figure 3. A sinestream waveform.

Figure 4 shows a single-period PRBS signal set in Model Linearizer with order 11 and (peak-to-peak) amplitude of 0.04. The sampling time for both sinestream and PRBS, set to 10 µs, must match the
control sampling time.
Technical Articles and Newsletters


Figure 4 Left: PRBS signal. Right: zoomed-in view.

To generate the plots shown in Figure 3 and Figure 4, create the perturbation objects in the Model Linearizer app, move the objects in_sine1 and in_prbs1 to the MATLAB® workspace (Figure 5), and
then use the following commands:

>> in_sine1.plot
>> in_prbs1.plot
Technical Articles and Newsletters

Figure 5. Moving sinestream and PRBS objects (blue) and frd objects (red) to the MATLAB workspace.

Estimation Time
The estimation time is the sum of the elapsed wall clock time (the time it takes to run the simulation with the injected sinestream or PRBS signal) plus the frequency response calculation time (the time to
Technical Articles and Newsletters
calculate the fast Fourier transform [FFT] of the output over the input). Since calculation time is usually significantly shorter than elapsed wall clock time, our buck converter example will focus on the
latter. Elapsed wall clock time depends on simulation time.

In our example, the simulation time for the sinestream signal is given by four times of each of 15 periods, with each period corresponding to one of the selected logarithmically spaced frequencies. You
can calculate it as follows:

>> in_sine1.getSimulationTime

ans =
0.1265

The simulation time for PRBS is given by the maximum period length 2n-1 multiplied by the sampling time. For the PRBS signal in_prbs1 shown in Figure 4, n = 11 and the sampling time is 10 µs. You
can calculate it as follows:

>> in_prbs1.getSimulationTime

ans =
0.0205

Note that you need to move the objects in_sine1 and in_prbs1 to the MATLAB workspace (Figure 5) to execute the above commands.

Number of Estimated Frequency Points


The number of frequency points in the estimated frd object depends on which input signal is used for the estimation.

If you use a sinestream signal, the frequencies in the estimated frd object are the frequencies specified in that signal. You can verify which frequencies are present with the MATLAB Variable Editor
(Figure 6) after launching the following command:

>> f_SineStream = estsys_SineStream.Frequency;


Technical Articles and Newsletters

Figure 6. The 15 frequencies of f_SineStream in rad/s in the Variable Editor.

If you use PRBS, the frequency points are determined by the FFT computation. As the Variable Editor shows (Figure 7), 1024 frequency points are computed after launching the following command:

>> f_PRBS = estsys_PRBS.Frequency;


Technical Articles and Newsletters

Figure 7. The 1024 frequencies of f_PRBS in rad/s in the Variable Editor.


Technical Articles and Newsletters
Notice that the vector f_PRBS contains 1023 positive frequencies as well as the frequency point ‘0’. The negative frequencies are discarded in the FFT computation process.

Estimation Accuracy
With the objects estsys_SineStream and estsys_PRBS moved to the MATLAB workspace, you can obtain the Bode plot of the nonparametric estimation results with sinestream and PRBS (Figure 8). The
results are consistent, even though the estimation with PRBS seems to be coarse at high frequencies.
Technical Articles and Newsletters

Figure 8. Bode plot of the nonparametric estimation results with sinestream (red stars) and with PRBS (blue dots).
Note that while you have direct control of minimum and maximum identifiable frequencies with sinestream, this control is indirect with PRBS. In fact, the minimum identifiable frequency is given by the
Technical Articles and Newsletters
inverse of the simulation time (1/0.0205 = 48.7805 Hz), and the maximum identifiable frequency is given by the Nyquist frequency that is half of the switching frequency (100e3/2 = 50 kHz), depicted as
a vertical line in Figure 8.

We can now compute and compare the parametric estimations. As described in part 1 of this series, you can obtain the parametric model using tfest from System Identification Toolbox™.

For the parametric estimation with sinestream, you simply execute the following command to estimate a transfer function with 2 poles and no zeros:

paramsys_SineStream = tfest(estsys_SineStream, 2, 0, iodelay);

The variable iodelay takes into account the delays introduced by computation, PWM, and sampling. Figure 9 shows the Bode plot of parametric and nonparametric estimation with sinestream.
Technical Articles and Newsletters

Figure 9. Bode plot of parametric and nonparametric estimation with sinestream.

For the parametric estimation with PRBS, it is best to thin the data points to ensure equal weighting for a controllable number of frequency points to be processed by tfest. The following code creates
an frd object containing 100 logarithmically spaced frequencies between 100 Hz and 20 kHz. The function interp is available in System Identification Toolbox.
% Thin the nonparametric estimation
fmin = 100; %Hz
Technical Articles and Newsletters
fmax = 20e3; %Hz
Nfreq = 100;
f = logspace(log10(fmin),log10(fmax),Nfreq);
% Interpolate FRD data over the new frequency grid
estsys_PRBS_thinned = interp(estsys_PRBS, 2*pi*f);

Then, you can calculate the parametric model with:

paramsys_PRBS = tfest(estsys_PRBS_thinned, 2, 0, iodelay);

Figure 10 shows the Bode plot of parametric and nonparametric thinned estimation with PRBS.
Technical Articles and Newsletters

Figure 10. Bode plot of parametric and nonparametric thinned estimation with PRBS.

Finally, if you plot the parametric estimations with sinestream and with PRBS and compare them with the equivalent analytic control-to-output transfer function (Figure 11), you may notice the following:

• The discrepancy in the parametric estimation with sinestream around the resonant frequency is due to a poor initial choice of number of frequencies.
• The parametric estimation with PRBS closely matches the analytic transfer function.
Technical Articles and Newsletters

Figure 11. Bode plot of parametric estimations with sinestream and with PRBS compared with the analytic transfer function.
Conclusions and Recommendations
Technical Articles and Newsletters
FRE with PRBS is a fast way to calculate transfer functions of switch-mode power electronics converters modeled with Simscape Electrical components. However, since this method estimates a large
number of frequency points, special care is required when thinning them to maximize estimation accuracy.

FRE with sinestream generally produces accurate results. However, to accurately estimate sharp resonant characteristics, you may need to increase the number of frequencies, with a resultant increase
in estimation time.

Moreover, due to the short injection time, FRE with PRBS has great potential for online estimation. In fact, power electronics systems vary over time, and it is often necessary to complete the estimation
in a short time so that dedicated control systems can monitor estimated key transfer functions in real time and take corrective action if needed. Clearly, FRE with sinestream does not support this use
case.

Published 2020

Products Used
• MATLAB

• Simulink

• Simscape Electrical

• Simulink Control Design

• System Identification Toolbox

Learn More
• Estimating the Frequency Response of a Power Electronics Model - Article

• Estimating Transfer Function Models for a Boost Converter - Example

View Articles for Related Capabilities


• Physical Modeling

• System Design and Simulation

• Simulation and Model-Based Design

View Articles for Related Industries


• Automotive

• Industrial Automation and Machinery Technical Articles and Newsletters


• Energy Production

• Aerospace and Defense

mathworks.com
© 1994-2021 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be trademarks or
registered trademarks of their respective holders.

Join the conversation

You might also like