Professional Documents
Culture Documents
Using MATLAB Live Scripts to Teach Optimal Control and Dynamic Programming Online
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.
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.
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.
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.
Published 2021
Products Used
• MATLAB
Learn More
• Signals and Systems Top 10 Student Projects (35:31) - Video
• 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.
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.
function z = do_intense_computations( x )
% do_intense_computations perform computationally intensive operations
%#codegen
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.
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.
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.
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.
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.
Products Used
• MATLAB
• Embedded Coder
• MATLAB Coder
Learn More
• The Joy of Generating C Code from MATLAB
• 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.
“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.
census data
polynomial
pchip
spline
exponential
logistic
gompertz
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.
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.
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.
log p ≈ log α + bt
Fit the logarithm of the data by a straight line and then exponentiate the result. No search is required.
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.
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.
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.
Products Used
• MATLAB
Learn More
• Cleve’s Laboratory
• 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.
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.
• 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
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
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:
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
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).
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.
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.
Figure 8 shows OpenMP C code generated from our radio model, including concurrent tasks created by Dataflow.
Technical Articles and Newsletters
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
Products Used
• Simulink
• Embedded Coder
• Simulink Coder
Learn More
• Dataflow Domain - Overview
• Algorithm Development
• Parallel Computing
• 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.
• 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.
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'.
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.
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.
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
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
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
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
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
Model
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
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
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
Model
Model
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
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.
Model
Estimating the Frequency Response of a Power Electronic Model: Sinestream vs. Pseudo-Random Binary Sequence (PRBS)
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).
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 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.
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:
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:
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:
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
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);
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
Learn More
• Estimating the Frequency Response of a Power Electronics Model - Article
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.