MathWorksNews&Notes

advertisement
MathWorks News&Notes
The Magazine for the MATLAB® and Simulink® Community
Cleve’s Corner:
Computing π
ALSO IN THIS ISSUE
NASA GN&C
Flight Software
Teaching ProblemSolving with MATLAB
Real-Time Simulation
of Physical Systems
AMIMON’s Home Digital
Interface Technology
Testing High-Speed
Optical ICs at Fujitsu
Join the conversation!
File Exchange
Download user-contributed files
MATLAB Answers
Ask and answer questions
about MATLAB and Simulink
Newsgroup
Connect with the MATLAB
and Simulink universe
Link Exchange
Share links to videos, tutorials,
articles, and other Internet resources
Blogs
Read commentary from
engineers who design, build, and
support MATLAB and Simulink
Contests
Compete in semiannual
programming challenges
An open exchange for the MATLAB and Simulink user community
mathworks.com/matlabcentral
What’s new
in MATLAB
and Simulink?
2011 Release Highlights
R2011a and R2011b offer new features in MATLAB and
Simulink, new products, and enhancements to more than
80 products.
MATLAB
New features include a startup accelerator, a spreadsheet
import tool, and optimized linear algebra functions.
MATLAB Coder, Simulink Coder, Embedded Coder
New products let you generate C and C++ from both
MATLAB and Simulink, optimize code for embedded
systems, and certify code against requirements.
System Toolboxes
New products combine MATLAB functions and Simulink
blocks for designing and simulating communications and
DSP systems.
Simulink
Workflow enhancements for Model-Based Design include
tools for configuration management, project file-sharing,
and model referencing.
See video and more details.
mathworks.com/release
6
10
fe at u r e s
6
Accelerating NASA GN&C Flight Software Development
NASA, Lockheed, and partners can simulate a 10-day Orion mission in just one day by
using Model-Based Design with Simulink.
10
Using MATLAB to Teach Problem-Solving Techniques to
First-Year Liberal Arts Students
MATLAB and an “inverted classroom” help students hone their critical thinking and
problem-solving skills.
14
Developing Wireless High-Definition Video Modems for
Consumer Electronics Devices
AMIMON’s Home Digital Interface technology sends 1080p frames 60 times per second
through walls to a device 100 feet away.
18
Accelerating Development and Testing of High-Speed Optical
Integrated Circuits at Fujitsu
By simulating IC designs before fabrication and automating tests, Fujitsu improved test
quality, speed, and reproducibility.
22
Design and PLC Implementation of Complex Industrial
Control Strategies
Use simulation to verify control strategies in a model—then reuse the model to generate
IEC 61131 structured text for deployment.
26
Real-Time Simulation of Physical Systems Using Simscape
Configure your model to achieve an optimal balance of simulation speed and accuracy.
14
18
d e pa r t m e n t s
4
MATLAB and Simulink in the World: Model-Based Design
30
Cleve’s Corner: Computing π
34
Tips and Tricks: Combining functions to construct
complex expressions
35
MATLAB and Simulink Based Books: New textbooks and
curriculum materials on system dynamics and programming
with MATLAB
36
Third-Party Products: Rapid prototyping and
26
30
Managing Editor
Linda Webb
Editor
Rosemary Oxenford
Art Director
Robert Davison
Graphic Designer
Katharine Motter
Technical Writer
Jack Wilber
Production Editor
Julie Cornell
Editors, German Edition
Thomas Andraczek
Michael Fröstl
Translators
Acclaro
Christoph Jansen
Printer
DS Graphics
Production Staff
M. Arielly, K. Calhoun, S. Hamel, L. Macdonald,
R. Marks, R. Nelson
Editorial Board
S. Gage, C. Hayhurst, S. Hirsch, S. Lehman, D. Lluch,
M. Maher, A. May, C. Moler, M. Mulligan, J. Ryan, L. Shure,
A. Tarchini, J. Tung
hardware-in-the-loop systems
about the cover
The cover features a MATLAB
visualization of 10,000 digits of π.
Cleve’s Corner (page 30) presents
MATLAB implementations of three
algorithms that compute π using exact
rational arithmetic and variableprecision floating-point arithmetic.
Contributors and Reviewers
T. Atkins, P. Bache, P. Barnard, D. Basilone, M. Behr,
G. Ben Romano, S. Benway, G. Bourdon, W. Campbell,
H. Chen, K. Cohan, D. Doherty, G. Dorman, T. Erkkinen,
N. Fernandes, J. Friedman, T. Gillis, H. Gilmore, J. Glass,
J. Henry, B. Hinkle, K. Hyman, K. Karnofsky, L. Kempler,
P. Kodati, K. Lorenc, B. McKay, S. Miller, G. Mitchell,
P. Pacheco, S. Prabhu, O. Pujado, J. Rapp, M. Ricci,
C. Ritchey, R. Rovner, G. Schreiner, R. Shenoy, A. Stothert,
R. Talbert, W. Tamblyn, A. Turevskiy, W. Walker,
J. Wendlandt, E. Wetjen, E. Wonsek, M. Woodward
Subscribe
mathworks.com/subscribe
Comments
mathworks.com/contact_us
©2011 The MathWorks, Inc.
MATLAB and Simulink are registered trademarks of The MathWorks, Inc.
See www.mathworks.com/trademarks for a list of additional trademarks.
Other product or brand names may be trademarks or registered trademarks of their respective holders.
MATLAB AND SIMULINK IN THE WORLD
Model-Based Design
Model-Based Design is enabling engineers worldwide to create increasingly complex systems within shrinking
schedules. Across industries, engineers have cut development time by 50% or more by placing a system model at the
core of the development process and using it to simulate and verify designs, create virtual prototypes, and generate
production code.
EPSON TOYOCOM
OCÉ
Reducing hardware prototypes: modeling and simulat-
Ensuring design feasibility before implementation:
ing mixed-signal devices
developing real-time prototypes
As more functionality is packed onto ever smaller consumer
electronics devices, manufacturers are turning to mixed-signal
devices to achieve stability and precision at high frequencies.
Epson Toyocom used Model-Based Design to develop a 16-bit
delta-sigma analog-to-digital converter for a mixed-signal integrated circuit. Modeling and simulation in Simulink® enabled
Epson Toyocom to make informed design decisions, verify their
design early in development, and reduce the number of hardware
prototypes, helping them complete the project within a twomonth deadline and saving the company millions of dollars.
Direct Imaging (DI) is a unique printing process developed by
Océ for black-and-white and full color. In a single pass, monocolor images generated by seven drums, each with 5000 tracks, are
combined to generate full-color prints. Océ R&D engineers built
a demonstrator that makes it possible to align the tracks of all
seven drums to within 20 microns of each other. The engineers
used Simulink and Stateflow to design, model, and simulate data
acquisition, control logic, and actuation subsystems. Simulink
Coder was used to create the control algorithms for the real-time
xPC Target™ prototype.
mathworks.com/epson-toyocom
mathworks.com/oce
ABB
Improving power electronics performance: simulating
controllers and power systems
Combining a powerful CPU with a large FPGA, ABB’s AC 800PEC
power electronic controller regulates high-power rectifiers, frequency converters for turbines, battery energy storage systems, and
other power electronic applications. After designing control algorithms for the AC 800PEC in MATLAB®, Simulink, and Stateflow®,
ABB engineers validated the algorithms by running system simulations with SimPowerSystems™. They used Simulink Coder™ to
generate almost 100% of the C code for the controller directly from
their Simulink models.
mathworks.com/abb
TRW
Verifying designs early in development: generating tests
for complete model coverage
TRW Automotive developed an innovative electric parking brake
that eliminates the need for a lever or pedal, integrates with the
vehicle’s stability control systems, and engages or disengages
based on commands from the vehicle’s onboard computers. TRW
engineers modeled and simulated the brake’s control system in
4
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Simulink and Stateflow. Test vectors generated with Simulink
Design Verifier™ enabled them to use simulation to verify the design in the first phases of development and achieve 100% coverage
of their control system models. The brake is certified for the IEC
61508 functional safety standard.
mathworks.com/trw
LOCKHEED MARTIN
Developing space-qualified communications systems:
cutting FPGA development time
Engineers at Lockheed Martin Space Systems developed a dualstage, satellite-based channelizer, or bent pipe transponder, that
can move bandwidth on demand between users and locations. Designed and tested using Model-Based Design, the channelizer was
implemented on FPGAs, enabling it to be updated after launch.
After modeling and simulating the channelizer, the engineers used
EDA Simulator Link™ and Mentor Graphics® ModelSim® to verify,
analyze, and visualize the VHDL implementation in Simulink, reducing verification time by 90%.
mathworks.com/lockheed-martin
GENERAL MOTORS ENGINEERING EUROPE
Accelerating control system development: generating
production code
GM Engineering Europe’s embedded HVAC control system calculates air temperature throughout a vehicle’s interior by simulating, in real time, the effects of ambient temperature, sun load,
heat-transfer mechanisms, convection, air flow, and heat radiation. The engineers created a model framework for the controller, performed system-level simulations, and generated code for
prototyping that was ultimately deployed on production hardware.
Model-Based Design accelerated development and enabled the
team to validate their designs and test components under various
failure conditions before hardware was available.
mathworks.com/gm-europe
Learn More
Video: Model-Based Design
mathworks.com/model-based-design
User Stories
mathworks.com/user_stories
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
5
Accelerating NASA GN&C Flight
Software Development
By Scott Tamblyn and Joel Henry, NASA, and John Rapp, Lockheed Martin
When the guidance, navigation, and control (GN&C) system for
the Orion crew vehicle undergoes Critical Design Review (CDR), more than
90% of the flight software will already be developed—a first for NASA on a
project of this scope and complexity. This achievement is due in large part to
a new development approach using Model-Based Design.
M
ost NASA GN&C projects follow
a traditional process: Domain experts and
analysts specify the behavior of the core
algorithms in detailed requirements documents. Following CDR, these documents are
handed off to the flight software engineers
for implementation into the formal flight
software. Producing the specification document alone often requires years of effort, and
because coding can begin only after the spec
is complete, it can be years before there is
any code to test.
The design and development of the
GN&C flight algorithms for Orion is a partnership between NASA, Lockheed Martin,
and other contractors. Model-Based Design
has helped these organizations work on
both the GN&C algorithm and flight software development concurrently. Simulink®
6
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
models serve as an executable specification
from which flight software is automatically
generated. As a result, the domain experts—
the GN&C analysts—work directly with the
executable algorithm models rather than
with documents that must then be interpreted by software developers (Figure 1).
Merging the design and analysis environment with the flight software development environment enables the joint team
to identify and resolve problems earlier and
has the potential to reduce overall development time by a year or more.
Laying the Groundwork for the
New Approach
While Lockheed Martin was already familiar with Model-Based Design, this approach represented a paradigm shift for
many NASA engineers and contractors. To
prepare the ground, lead GN&C and flight
software engineers collaborated in detailing
the benefits of the new development process,
and explained how it would change the roles
and responsibilities of the GN&C analysts
and flight software engineers.
Modeling standards were developed to
enable the approximately 100 engineers
from multiple organizations working on
the GN&C algorithms to develop consistent models, understand each other’s work,
and collaborate efficiently. These standards
ensure that all models are clear and readable—particularly important for a large
team using the models as documentation.
The standards were based on lessons learned
in earlier projects and on MathWorks Automotive Advisory Board (MAAB) guidelines.
Designed for deep space missions, NASA’s Orion crew
exploration vehicle will carry a new generation of
astronauts far beyond low Earth orbit to multiple destinations throughout our solar system, such as asteroids,
the moon, and eventually, Mars. Orion will replace the
space shuttle as the agency’s principal vehicle for human space exploration. Image courtesy NASA.
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
7
Figure 1. Schematic comparing our traditional design process with the approach we used to develop Orion GN&C software. Image courtesy NASA.
Developing and Integrating
GN&C Algorithms
The first step in developing the GN&C system architecture was the creation of the
‘Empty-Box Architecture’ (EBA). The EBA
contains approximately 100 functional modules, or computer software units (CSUs).
The engineer or subteam responsible for
a CSU assembles a model comprising 100
or more Simulink library blocks and components. Because the CSUs are specified as
Model Reference blocks, each unit can be
thoroughly simulated on the desktop before
it is handed off to the flight software team.
The engineer then uses Simulink Verification
and Validation™ and the Simulink Model
Advisor tool to verify that the model meets
the modeling standards. The engineer also
generates code to ensure that there are no
8
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
problems in the model that would preclude
code generation. When delivering the CSU,
the engineer provides both the Simulink
model and the test inputs and expected test
outputs from the unit tests.
To validate the overall GN&C software, as
well, the team runs the higher-level model
composed of all functional units in closedloop simulations to further debug and test
the algorithms. In these situations, NASA
relies on Trick, a high-fidelity, six-degreeof-freedom simulation infrastructure that
NASA has been refining for more than 20
years. The simulation environment includes
mathematical models of the vehicle’s sensors
(such as inertial measurement units and star
trackers) and effectors (such as reaction control systems), as well as aerodynamics, gravity, and the space environment.
The higher-level model is linked to
the Trick environment via a socket connection. This setup enables engineers to
debug their CSU algorithms in the fullfeatured Simulink environment while
running closed-loop simulations. For
example, engineers can simulate the atmospheric entry phase of flight and use
scopes in Simulink to observe signals in
their own CSU or anywhere in the EBA.
Generating Code with Embedded
Coder
Because the C++ flight code is automatically
generated from the Simulink models, most
flight software coding will be completed before CDR. In addition to saving time and reducing risk, code generation with Embedded
Coder™ provides three advantages at this stage
of the program: First, it enables us to verify
that the code that will ultimately get deployed aboard the target vehicle can be generated and that it produces the same results
as the Simulink simulations of the source
models. Second, code generation enables engineers who are accustomed to writing their
own code to inspect the generated C++ code
and even debug directly in the code. Third,
it enables analysts to dramatically realize
closed-loop run-time performance by embedding the generated code directly into the
Trick simulation infrastructure.
Simulink is ideal for running closed-loop
simulations because its interactive, visual
environment helps engineers identify and
resolve defects quickly. For full analytical
verification testing, however, simulation
speed is a more important consideration
because of the need to run hundreds of
thousands of Monte Carlo simulations for a
range of scenarios.
Closed-loop simulations employing the
generated code embedded in Trick perform
approximately 10 times faster than real
time. As a result, a full 10-day Orion mission can be simulated in just one day. Engineers have already conducted entry-stage
simulations using both approaches—using
the Simulink model to drive Trick, and
embedding the generated code into Trick.
When compared, the results of the two simulations were found to be bit-for-bit true;
they matched down to the lowest level.
Blazing a Trail
This GN&C project is blazing a new trail
for NASA in many ways. Simulink and
Embedded Coder are enabling a large team
of domain experts from NASA, Lockheed,
and other contractors to develop algorithms
for complicated trajectories and scenarios,
run simulations within a legacy simulation
environment, and generate flight software
code that will ultimately be deployed on the
vehicle.
On long-term projects like this one, it is
not uncommon for agency requirements
and priorities to shift. With the algorithms
captured in models rather than in low-level
code, the engineers are well positioned to
take the project in whatever direction it
needs to go. ■
Resources
Learn
More
Orion Crew Exploration Vehicle
www.nasa.gov/mpcv
Orion GN&C: MATLAB® and Simulink Standards
mathworks.com/orion_gnc
NASA’s X-43A Scramjet Achieves Record-Breaking
Mach 10 Speed
mathworks.com/nasa-scramjet
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
9
Using MATLAB to Teach Problem-Solving
Techniques to First-Year Liberal Arts Students
By Dr. Robert Talbert, Franklin College
The students taking CMP 150: Computer Tools for Problem Solving
at Franklin College this spring were not the ones who usually take a MATLAB®
class. Few were engineering or science majors, and fewer still had any
programming experience. Most were pursuing a degree in education, and
were taking the course because it is a prerequisite for Calculus 3.
W
hile learning MATLAB might not
seem essential to a liberal arts education,
the ability to use technology and critical
thinking to solve problems undoubtedly is.
I know that most of the students in CMP
150 will eventually forget function names,
commands, and other details, but that’s not
vital. What is important is that they learn
how to use MATLAB to solve problems by
themselves.
Course Motivation
CMP 150 was created to provide students
with programming experience in their first
year and to enable them to fulfill a requirement of our dual-degree engineering program.
For many years, mathematics majors at
Franklin College were required to take an
10
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
introductory C++ programming course.
Several former students told us that they
would have benefited from more applicable
programming experience. Many of these
recent graduates noted that, while they
don’t write software in C++, they often need
to write quick, functional blocks of code to
solve a problem or perform an analysis that
would be difficult to do using a spreadsheet.
Adding CMP 150 to our mathematics
curriculum enabled us to respond to the
feedback we received from Franklin College
graduates. It also helped us achieve a major
goal of our curriculum revision: to integrate
programming into many more courses,
including Linear Algebra, Calculus 3, and
Numerical Methods.
CMP 150 also helped the Franklin College
undergraduates enrolled in our dual-degree
engineering program with the Purdue University School of Engineering and Technology at Indianapolis, which requires three
years at Franklin College and a further two
years at Indiana University – Purdue University – Indianapolis (IUPUI). In the past,
these students took a required MATLAB
course at IUPUI. During our curriculum
revision, we decided to create our own version, covering the same topics as the Purdue
course but aligning them more closely with
the rest of our coursework.
The Inverted Classroom
CMP 150 meets just one day a week for 75
minutes. To make the most of this limited classroom time I employ an inverted
classroom model. In this model, the students watch video lectures, complete online
Most of the students in Dr. Robert Talbert’s course Computer
Tools for Problem Solving have never written a computer
program before, and virtually all are encountering MATLAB
for the first time. Dr. Talbert, who holds a Ph.D. in mathematics from Vanderbilt University, employs an inverted classroom
model in which lectures, readings, and assignments are posted
online and class time is devoted to hands-on lab work. His
pedagogy is based on the conviction that “learning a computer
tool is much more fun when you give yourself time to play and
time to make and correct mistakes — time to develop the kinds
of expert behaviors that computer people employ.”
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
11
tutorials, and do the required reading at
home. Class time is devoted to hands-on
lab exercises, with virtually no lecture. This
arrangement enables me to spend time with
the students as they work in groups of two or
three on their weekly assignments (Figure 1).
Although it took the students some time to
adjust to this way of learning, by the end of
the semester they had refined an invaluable
skill: the ability to learn and apply new concepts on their own.
The video lectures and tutorials are easily
scalable. In a course supported by teaching
assistants, the one-on-one attention I offer
could be extended to hundreds of students.
MATLAB is ideal for this approach. The
getting started videos on mathworks.com
are very well done and perfect for learning the basics of MATLAB. I didn’t see any
materials on mathworks.com that I felt I
could improve upon, so I just kept them. As
the MathWorks tutorials became more advanced, I created my own screencasts on the
new concepts covered each week, which the
students watch before coming to class. Further support is available via the MATLAB
doc command, which enables the students
to get information on any MATLAB capability directly from the command prompt.
Students found it empowering to discover
that they did not need to be told what to
type—they could learn whatever they wanted by using doc and experimenting on their
own.
I use exercises and examples from Cleve
Moler’s online textbook Experiments with
MATLAB. Otherwise, there is no required
textbook for CMP 150. Instead, I recommend that the students acquire MATLAB
and Simulink Student Version. I point out
that this is an investment that they will use
throughout their undergraduate years.
Easing into MATLAB
At first, the students find computer programming concepts difficult to grasp. I begin
the course with topics that they can relate to
immediately, using real-world data to make
12
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Figure 1. Dr. Talbert with his students in a CMP 150 lab session.
them more interesting and compelling. Because most students are familiar with plotting, and plotting and visualizing data is a
great strength of MATLAB, I begin with that
(Figure 2).
The students analyze data downloaded
from the Indiana Department of Transportation and other online sources. In one
exercise, they work with a large data set
that includes the average price of gasoline
for each month for more than 25 years. The
data is in a matrix form, with months as the
columns and years as the rows. To create
plots, the students have to learn how to manipulate the data. This exercise serves as an
excellent introduction to MATLAB matrix
operations. The students create a MATLAB
script that uses the reshape function to access price data for different months and
generates a graph of those prices. They then
use these graphs to draw conclusions about
the data.
The next section of the course deals with
statistical plotting, regression analysis,
and curve fitting. The students are familiar
with some of these topics from their calculus course, where they use a spreadsheet to
perform regression. They quickly learn that
MATLAB is much more powerful than a
spreadsheet for this kind of work, providing more precision and greater control over
the polynomial coefficients.
Experimentation and Symbolic Math
When the students are comfortable with the
MATLAB environment and have some experience with plotting, using variables, and
running scripts, I introduce basic programming constructs, including conditionals and
loops. Although programming is entirely
new to most of the students, I encourage
them to experiment. Making mistakes and
correcting them is an excellent way to learn
a new skill.
In one assignment, students write a simple program that takes a numeric grade and
produces the corresponding letter grade. A
grade of 91, for example, generates an A-.
I don’t lead the students to a particular solution; I let them devise their own. Some
gravitate to a series of if conditionals; others opt for a switch statement. When we
discuss their solutions in class, they see that
there are many ways of solving the same
problem in MATLAB.
Toward the end of the course, the students use Symbolic Math Toolbox™ to solve
problems symbolically. This past semester,
a colleague who teaches Calculus 2 told me
that some of his students were struggling
with infinite series. As a result of that conversation, I changed my plans for the next
week. I showed my class how to calculate
the partial sum of a series numerically using a MATLAB script and then asked them
to solve the same problem symbolically using the MuPAD notebook interface, which
is included with Symbolic Math Toolbox.
This exercise not only helped them understand the mathematical concepts they
were struggling with; it also provided an
excellent example of how they could apply
MATLAB and Symbolic Math Toolbox in
their coursework outside CMP 150.
Final Exams and Beyond
For the final exam, students must demonstrate competency in four areas: graphing
and visualization, working with data, mathematical analysis, and programming. They
have two hours to solve one problem in each
of these categories using MATLAB. One of
the programming problems asked them to
create a function to approximate values of
ex using a Taylor polynomial. Another option was to write a script that generates the
first N numbers in the Fibonacci sequence,
where N is an integer input to the script. I
was pleased with the students’ exam performance; it showed that they had come a long
way in just 14 weeks.
We continue to integrate MATLAB into
the rest of the curriculum. Students already use MATLAB in Calculus 3, and I’m
working with colleagues in the science and
business departments to increase their use
Figure 2. MATLAB plots generated by students.
of MATLAB. Student feedback has been
positive. A few students who’ve taken a subsequent programming class in C++ have
told me how much they miss programming
in MATLAB. Many students say that the
most valuable part of the course was learning how to tackle a new concept by themselves—how to find documentation or another source of information and stick with
it until they understand it.
Thinking critically and acquiring and
making sense of information are core intellectual skills in a liberal arts education.
MATLAB is an excellent environment for
students to develop and hone these skills
early in their college careers. ■
Resources
Learn
More
Experiments with MATLAB
mathworks.com/moler
Using MATLAB to Teach Programming to FirstYear Engineering Students at Boston University
mathworks.com/matlab-bu
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
13
Developing Wireless High-Definition Video
Modems for Consumer Electronics Devices
By Guy Dorman, AMIMON
Consumer electronics devices capable of delivering high-definition
(HD) video signals are growing rapidly in number and variety. DVD players
and cable or satellite set-top boxes have been joined by Blu-ray players and
video game consoles, with PCs, video cameras, and even mobile phones close
behind. While each wave of innovation has improved video quality, it has also
added to the tangle of cables connected to high-definition televisions (HDTVs)
and created a need for more video inputs.
A
MIMON has developed Wireless
Home Digital Interface (WHDI™) technology that enables HDTVs to interface wirelessly to all HD video sources while providing the same quality as a wired connection.
Developed using MATLAB®, WHDI technology can deliver 3 Gbps, enabling 1080p
frames to be sent 60 times per second
through walls to a device 100 feet away. Because the frames are uncompressed, latency
is as low as 1 msec, making WHDI ideal for
game consoles that require extremely brief
response times. WHDI devices not only
eliminate the need for video cables; they
can also act as a wireless switch, connecting
multiple video sources to multiple HDTVs
and displays.
We relied on MATLAB to verify our designs early in development by simulating
14
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
the WHDI algorithms, and later by comparing the results produced by hardware
implementations with MATLAB simulation results.
Challenges of Delivering Wireless,
Uncompressed, High-Definition
Video
From an engineering perspective, transmission chains for video are more demanding
than transmission chains for data packets.
Data packets can be retransmitted without
affecting the user’s experience. With video,
there is no retransmission; each frame must
be passed across the channel when the source
delivers it. Because the viewer will notice any
errors in the video, worst-case performance,
not average performance, must be the gauge
of quality.
Wireless video products that use alternative technologies have significant drawbacks.
Some use compression, which not only adds
a significant amount of latency but also requires a more powerful and costly processor.
Others transmit in the very high-frequency
60 GHz band, which requires direct line-ofsight between the transmitter and the receiver, and thus cannot be used to transmit from
room to room. In addition, the 60 GHz technology does not support multicast transmission schemes in which one source is transmitted to multiple receivers.
For AMIMON engineers, the challenge
was to develop video processing and modulation algorithms that would enable us to
transmit uncompressed 1080p frames at 60
frames per second using the 5 GHz unlicensed band and just 40 MHz of bandwidth.
WHDI is the first standard to enable universal,
codec-independent, multiroom HD video connectivity
through the delivery of uncompressed HD video. With
WHDI, users can connect any video source in the home
to any display device—even to a device that is100 feet
away and in another room. Because WHDI is a multicast protocol, one audio-video source can be connected
to several displays.
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
15
Figure 1a. DLPHY
transmitter block diagram for 20 MHz mode
and 40 MHz mode.
Figure 1b. Video encoder block diagram.
Developing the Algorithms
Because the technology we were developing was so new, we needed to try innovative
techniques. The MATLAB environment is
ideal for this kind of development because we
can very quickly try out new ideas and run
simulations to evaluate them. As a result, we
were able to try several schemes that would
otherwise have been too time-consuming to
evaluate. For example, we needed to design
a motion classifier, which detects whether
an 8x8 pixel block is static or dynamic. This
straightforward implementation required the
last frame to be kept in memory for comparison against the new frame. This frame buffer
contains a large number of pixels. Using such
a large memory buffer would increase the
product cost significantly. By using MATLAB,
we tried several schemes that store a signature
of each 8x8 pixel block. The signature from
the last frame was compared with the sig-
16
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
nature from the current frame to determine
whether motion was present. We tried several
signatures. For each signature under test we
ran simulations on real movies to quantify the
false alarm rate and the miss detection rate.
The transmit and receive components of
the system are partitioned into video processing and modulator modules (Figures 1a
and 1b). The modulator must squeeze a great
deal of data into a relatively narrow band of
the spectrum. (The 40 MHz bandwidth requirement is driven by FCC regulations and
by our design goals of using a commonly
available RFIC that operates at 5 GHz with
40 MHz of bandwidth and allowing simultaneous transmission of many WHDI systems
as well as Wi-Fi systems in the same room.)
In MATLAB, we developed algorithms
for the modulator that use multi-input,
multi-output (MIMO) technology. With this
design, we transmit four streams simultane-
ously using four separate antennas. On the
receiving side we have five antennas, with
the extra antenna used to compensate for
fade-out. We tailored the video processing
component to work with this special modulator.
The video processor and modulator are
further partitioned into approximately 25
functional blocks, each modeled and simulated separately in MATLAB. For example,
the video processing module includes discrete cosine transform (DCT) algorithms
that process frames in 8x8 pixel blocks, while
the modulator includes inverse fast Fourier
transform (IFFT) blocks to implement the
orthogonal frequency division multiplex
(OFDM) modulation.
For another block we developed finite
impulse response (FIR) filters using
Signal Processing Toolbox™ and then used
Optimization Toolbox™ to identify an optimal
set of filter parameters that would bring the
design into compliance with FCC regulations.
Simulation and Verification
Verification of our design started early. After
developing the algorithms in floating point to
maximize development speed, we converted
them to fixed point for maximum simulation
fidelity. Once a functional block was modeled
with MATLAB, the engineer simulated the
block by providing test stimuli inputs, capturing the output, and comparing the output
with expected results.
A team of six engineers developed individual blocks in parallel until the entire
system could be integrated and simulated
together. The input to this full system simulation in MATLAB is a single-frame image
stored as a bitmap file. The simulation performs all the video processing and modulation algorithms on the transmit side and
then performs the reverse algorithms on
the receiver side to reconstruct the image.
At the end of the simulation we verify that
the resultant image matches the input image with high fidelity. During simulation we
capture the input and output of individual
subsystems and reuse them to verify the RTL
implementation.
Once a block has been tested via simulation in MATLAB, VLSI engineers use the
MATLAB algorithm as a reference to develop the RTL code. Using a test-bench automation technology, the engineer then verifies the implementation by comparing the
results produced by the RTL implementation
with the test vectors generated by MATLAB.
The RTL block is stimulated with the same
test inputs as the MATLAB code, and the results are analyzed to see if they are bit-exact
matched.
In the next verification step we download
the RTL onto an FPGA board and run the
algorithms in real time on real channels using actual RF devices and antennas. On the
receiver side we have a large memory bank
in which we capture the input signals from
Figure 2. Second-generation WHDI audio-video modules. Top: The WHDI Stick, which enables wireless viewing of tablet and notebook content on a TV. Bottom: Transmitter and receiver modules of a
WHDI wireless video modem.
the receive antennas. When we identify
anomalies in the received signal, we analyze
the data captured by injecting the received
signal into the receiver MATLAB simulation
and determining the source of the problem.
This step enables us to improve our design
to compensate for the kind of channel fades
and noises that the device will encounter
in real-life settings. Finally, we tape out the
verified RTL implementation and send it for
fabrication as an ASIC chip.
Second- and Third-Generation
WHDI Technology
The second generation of WHDI devices
(Figure 2) is now entering production, and
several leading consumer electronics manufacturers are incorporating the technology
into their products. For third-generation devices, we plan to support 2k-by-4k video resolution and 3D technologies in video while
reducing the device’s cost and extending its
range. We continue to use MATLAB to optimize the video processing and modulation
algorithms and verify our ASIC implementation. We are also exploring opportunities
to generate the RTL directly from MATLAB
algorithms. ■
Resources
Learn
More
Automatic Hardware Implementation of
Digital Filters for an Audio Codec
mathworks.com/audio-codec
Philips Consumer Lifestyle Develops
One-Piece Surround Sound System
mathworks.com/philips
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
17
Accelerating Development and Testing
of High-Speed Optical Integrated Circuits
at Fujitsu
By William Walker, Fujitsu Laboratories of America
At Fujitsu Laboratories of America, we use MATLAB® and
Instrument Control Toolbox™ to perform automated tests and data analysis.
This approach enabled our engineering team to accelerate our production
schedules and improve the quality, speed, and reproducibility of our tests
during product verification.
Verifying a 40 Gbps Optical
Transponder
Automated verification played a key role
in a recent project—the development of a
serializer/deserializer (SERDES) capable
of handling 40 Gbps. The SERDES chip set
serves as the foundation for Fujitsu’s optical network transponders (Figure 1). It is
a low-power, mixed-signal CMOS device
with digital logic as well as much more
complex analog circuitry for the limiting
amplifiers (LAs) and clock data recovery
(CDR) components. The system specifications require bit-error rates (BERs) of less
than one error per trillion bits.
Prior to fabrication, we extensively simulate the system, but no matter how extensive
our simulation, some aspects of the design,
such as varactors, inductors, and field-
18
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
effect transistors (FETs), can only be verified on silicon. When these analog devices
are fabricated, their RF parameters can
differ significantly from those we used in
our simulations. These discrepancies can
be a result of the physical layout of the design or of the fabrication process. When
they are outside the tolerances accounted
for in the design, the chip is unlikely to
meet our quality standards.
We rely on automated testing to quickly
and accurately characterize the devices
on chip and extract the relevant analog
and RF parameters. By quantifying the
discrepancies between our design and the
silicon returned from the foundry, we can
refine the design and improve the chip’s
overall performance.
Test Automation
In our labs we deploy a wide range of test
equipment, including signal generators,
source-monitor units, spectrum analyzers,
vector network analyzers, and digital oscilloscopes (Figure 2).
Manual tests, and even semi-automated
tests using vendor instrument control software, are time-consuming, tedious, and
labor-intensive. Automatically controlling
different vendors’ software is a very challenging task, especially when equipment
from different vendors is part of the same
test suite. More importantly, it is difficult
to obtain reproducible test results when an
engineer operates the test equipment controls by hand.
For these reasons, each piece of our test
equipment is controlled using MATLAB
Foundry SERDES test chips.
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
19
scripts and Instrument Control Toolbox.
Although equipment vendors supply software to operate their instruments, and
some even ship with built-in Microsoft®
Windows® PCs, we find that Instrument
Control Toolbox is a more effective solution, as it provides a consistent interface to
all instruments from a single host computer. Bypassing the vendor interfaces and instead writing MATLAB scripts to perform
tests requires a little more effort in the
earlier stages, but that investment pays off
many times over throughout the project.
Most importantly, using Instrument
Control Toolbox from a central host computer enables all the instruments to be operated together in the same test suite, and
we can initiate a test suite just by running a
script. A test suite typically makes a series
of measurements under different operating conditions—for example, measurements at different frequencies—and uses
multiple pieces of equipment to measure
different device properties.
The data from a test needs to be processed immediately to make a go/no-go
decision about subsequent tests. For example, if a short-circuit is detected, there is
no point in continuing on to the next test.
Our MATLAB based software is capable of
sophisticated data analysis, enabling us to
make complex go/no-go decisions. Only
by integrating data analysis and software
control of instruments can we achieve this
level of automation.
The object-oriented programming capabilities of the MATLAB language have
proved particularly useful in our test environment. We create a MATLAB class for
each test instrument. These classes make
it easier to save state information during
a test and return to it later if we have to
interrupt a test for any reason. When we
acquire a new test instrument, we can create a class for it by altering an existing
MATLAB class for a similar piece of
equipment. Because the classes share a
20
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Figure 1. A block diagram of the deserializer.
common interface, we are usually up and
running with any new instrument within
a day. This approach also makes it easier
and faster for us to create new test scripts.
Device Testing
To achieve the accuracy we need from our
circuit simulations, we test and characterize on-chip devices. This process relies on
MATLAB and Instrument Control Toolbox
to collect and process volumes of test data.
By automating the tests using MATLAB,
we can control the precise sequence and
timing of the steps executed for each test
procedure. Parameter sweeps become
straightforward to script and execute. Test
results are recorded automatically, eliminating human error, and the steps used
to obtain them are logged. For example,
we have a script that collects data from
the vector network analyzer and records
scattering parameters (S-parameters) at a
range of frequencies.
Our test setup enables us to use multiple
pieces of test equipment without physically
changing the connection to the device under test. For example, we can measure Sparameters and the power spectrum of the
device on different instruments using the
same physical connection. This makes our
testing much faster. We can schedule sev-
Figure 2. Part of Fujitsu’s test lab.
eral tests to run sequentially and then go
to lunch or work on another task. When we
return, the results are waiting for us, ready
to be analyzed (Figure 3).
As well as improving our testing process, test automation makes it practical to
do some types of testing. In many cases,
manual testing is simply not feasible. For
example, characterizing an FET manually
silicon. Our long-term goal is to have a
single tape-out with no respins. Using our
automated verification process, we have
already reached our near-term objectives
of reduced development time and rapid,
accurate device characterization. ■
Figure 3. A team member analyzing test results.
would take 10 times longer than with auto­
mated scripts. Moreover, if we repeated
the characterization manually, we would
probably get different results because of
slight differences in the test setup process.
By contrast, we can use the same automated script and get consistent results every
time. In fact, the results are so reliable that
we use them to identify test equipment
that is aging and in need of recalibration.
Circuit Testing
We also use MATLAB and Instrument Control Toolbox to initiate and manage built-in
self-tests via the chip’s JTAG (IEEE 1149.1)
and I2C interfaces.
For example, a typical script for a chip
just back from the foundry would start
with simply powering the chip up and
measuring the current draw. If the device
is drawing too much current, we know that
it has a short circuit, and the test terminates. If not, the MATLAB script proceeds
to verify the test logic using a predefined
procedure before beginning basic tests of
the device.
Because our SERDES chip operates at
such high data rates, using industrial testers to perform BER tests is prohibitively
expensive. Instead, we have integrated
pseudo-random bit sequence (PRBS) generators and bit error rate test (BERT) circuits into our SERDES ICs. MATLAB
scripts use the I2C interface to instruct the
PRBS what pattern to send to the CDR and
for how many cycles. At the end of the test,
the script reads the error count from BERT
registers and logs the data.
Analyzing the Results and
Looking Ahead
We use the device characterization results
from our automated tests to improve our
device modeling and design. We make
changes to our simulation models to more
closely reflect the measured data and then
revise the design. Because the next iteration of the design is based on more accurate
data, its performance more closely matches
our specification.
Foundry costs continue to rise, and
few companies can afford to debug in
Resources
Learn
More
Early Verification of Digital-Analog
Designs Using System-Level Cosimulation
mathworks.com/early-verification
Accessing Instruments Using Interface Objects
mathworks.com/interface-objects
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
21
Design and PLC Implementation of Complex
Industrial Control Strategies
By Parasar Kodati, Tom Erkkinen, and Arkadiy Turevskiy
Programmable logic controllers (PLCs) are used for control problems ranging from relatively simple, single-input single-output control loops to
systems with multiple coupled loops and complex supervisory algorithms. For
simple control problems, such as a single proportional-integral-derivative (PID)
loop, engineers can implement a PID controller and tune gains as the machine
is running. For more complex control problems, coding and verifying control
logic on PLCs is much more challenging. Designers must determine the values
for multiple controller parameters and make sure that all the parts of the control
algorithm work together as intended. Tuning a complex controller on the hardware prototype or on the actual process is not only time-consuming; it involves
considerable risk of damaging the equipment.
T
he solution is to use simulation to design and verify complex control strategies in a
model. The same model can then be used for
automatically generating IEC 61131 structured text to program PLCs for deployment.
This article demonstrates this approach using
a steel rolling mill system as an example.
Steel Rolling Mill System: Control
Design Goals
A steel rolling mill produces a sheet of uniform thickness from a slab of steel. It typically consists of several rolling stages, with
rollers in each stage compressing the sheet
of steel passing through it (Figure 1). In between the roller stages, looper stages maintain the tension in the sheet and prevent
tearing and formation of slack.
To simulate a multistage process, we
first model and control a single rolling mill
22
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
stage. The more general configuration can
be analyzed by connecting several of these
simpler setups.
The control system for our simple mill
must meet the following requirements:
• Maintain a thickness of 8 mm +/- 0.1
mm in the produced steel at the exit of
the last roller
• Maintain the required throughput to 1
m/s +/- 0.1 m/s at the exit of the last roller
• Keep the tension in the material to
1.75 N/M^2 x 10^5 after 100 secs for
each roller
• Detect failures in sensors and actuators
and either recover from them or safely
shut down
Creating the Plant Model
We begin by creating a Simulink® model
of the rolling mill that we will use to
develop and test our controller. We model
the process in two steps, first modeling
the individual rolling stages and then the
looper between them. At the rolling stage,
a hydraulic actuator is used to create a roll
compressive force that compresses the steel
strip. The rolling torque, created by a motor drive, helps control the rolling speed.
Using SimMechanics™, Simscape™, and
SimHydraulics® we can model the mechanical, electrical, and hydraulic elements of the
roller, respectively, without having to derive
the equations explicitly.
Rolling Mill Stage
Looper Stage
Figure 1. Schematic of a rolling mill process.
AGR: Automatic gauge regulator
ASR: Automatic speed regulator
LHC: Looper height controller
CRCC: Current reference calculation controller
Ref.
theta
Hydr. valve
opening
Ro
llin
for g
ce
Ro
sp llin
ee g
d
Ref. thickness
thickness
Ref.
Omega
thickness; speed
voltage
Plate
Omega
Ref. Sigma
tension
Torque
current
theta
Physical modeling tools used to model
the plant
Figure 2. Multiloop control architecture. Theta = looper angle, sigma = plate tension,
omega = plate speed.
Figure 3. PID Tuner. You can fine-tune your
design by using the slider.
We use SimMechanics to model the
looper, representing the looper and the steel
strips before and after it as three bodies
connected by joints. We then combine the
rolling stage and looper stage models in one
Simulink system model.
are used to model other aspects of the process, such as mass conservation and transport delays across different mill stages.
Designing and Verifying the
Controllers
The next step is to use the plant model to
design the controllers. Figure 2 shows the
multiloop architecture of a typical control
system for a multistage rolling mill process.
The control system consists of the following compensators:
• AGR—controls the opening of the hydraulic valve to create rolling compression force to control strip thickness
• ASR—commands voltage to the DC motor that creates the rolling torque and
therefore controls the strip speed
• LHC—sets the rotational speed reference of the rollers to indirectly achieve
the desired material tension
• CRCC—commands current to the looper motor to position the looper to maintain material tension
Note that all loops are coupled. For example, the hydraulic actuator controlled by
the AGR compensator affects not only strip
thickness but also strip speed. LHC and
ASR compensators work together to maintain the required tension and strip speed.
We first design compensators that control the operation of a single roller. We
begin by linearizing the nonlinear model
using Simulink Control Design™. We then
tune the controller using the PID design
tools in Simulink Control Design to compute the controller gains. The tuner (Figure 3) automatically calculates the PID
gains given a desired response time. With
Simulink Design Optimization™ we finetune the controller gains so that the system
performs well in the presence of nonlinearities. The overall design is verified by running the nonlinear simulation. Note that
the plant model serves two purposes: We
use the linearized plant model generated by
Simulink Control Design to tune our compensators, and we use the full, nonlinear
plant model to verify our controller design
using closed-loop simulation.
Modeling and Simulating a
Multistage Process
Using custom library blocks, we reuse the
rolling mill stage and the looper stage subsystems as components in the multistage
process (Figure 4). Additional subsystems
Designing and Verifying Fault
Detection Logic
In addition to feedback compensators,
process controllers must include supervisory and fault detection and recovery logic
to, for example, monitor the condition of
the sensors and actuators in the system.
Our focus is on the fault recovery logic
that detects failures in hydraulic valves and
takes corrective action. Specifically, our
logic will distribute the overall thicknessreduction target to individual thickness
setpoints of the stages in a multistage process. When the hydraulic compression of
one stage fails, the logic checks to see if the
other stages can compensate for the failed
stage. If they can, the thickness reduction
setpoints of the working stages are recalculated to achieve the overall thicknessreduction target.
We use Stateflow® to develop this logic
(Figure 5). Note that this logic is a simplified representation of what would have
to be developed for the actual process
control because it assumes that the failed
stage does not provide any compression
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
23
Continuous
Mill stage 1
powergui
Vout_2
Pvel_in1
Vin_2
Mill stage 2
Pvel_out1
Vout_2
Tout_2
Tin_2
Pvel_in2
Pthick_out0
Vin_2
Vout_2
Tout_2
Tin_2
Mass conservation for stage 1
Pthick_out1
Pvel_in3
Vin_2
Mass conservation for stage 2
Pthick_out1
Pthick_out0
Mill stage 3
Pvel_out2
Pvel_out3
Tout_2
Tin_2
Pthick_out2
Mass conservation for stage 3
Pthick_out2
Pvel_in1
Pthick_out3
−T−
−T−
Pvel_out1
Pthick_out0
Pvel_out2
−T−
Pthick_out0
Pvel_out3
Pvel_in2
Pthick_out0
Pvel_in3
−T−
PID(s)
Coiler
−T−
PID Controller1
PID(s)
−T−
PID Controller2
PID(s)
PID Controller3
theta_12
Laccum_1
theta_23
theta_34
Laccum_2
tension_12
tension_23
Looper stage 1−2
Laccum_3
tension_3e
Looper stage 2−3
Figure 4. Simulink model showing multiple rolling mill stages with inter-stand looper stages.
but allows the material to pass through. In
the actual setup, a much more comprehensive and complicated logic would be needed.
We can test the logic by artificially introducing failures into our Simulink model.
Figure 6 shows the simulation results of the
fault tolerance logic. When a stage fails, the
supervisory controller checks to see if the
load can be distributed to the remaining
healthy stages. If it can, then new setpoints
for thickness reduction are commanded
to the individual stage AGRs. If it cannot,
then the process is shut down by halting the
sheet movement.
Implementing the Controller
on a PLC
We use Simulink PLC Coder™ to automatically generate IEC 61131 structured text
from our controller. This portable structured
text can then be imported into the IDE used
for our target PLC hardware. Figure 7 shows
IEC 61131 structured text generated from
the fault detection and accommodation
logic. Note that the generated structured text
is well commented and can be easily traced
back to the model.
Automatic code generation eliminates
errors that may get introduced with manual coding and helps ensure that the final
structured text produces numerical results
24
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Figure 5. Fault-tolerant setpoint distribution implemented in Stateflow.
Looper stage 3−end
Figure 6 (left). Simulation results
showing the system recovery from stage
failures: Stages 2 and 3 compensated
when stage 1 failed. When stage 2 failed,
the system was shut down, as the overall
thickness reduction target could not be
handled by stage 3 alone.
Figure 7 (below). IEC 61131 structured
text generated using Simulink PLC Coder.
Comments with references back to the
Stateflow chart are shown in blue.
END _ IF;
Setpoint _ IN _ STAGE _ 1 _ FAILED:
(* During 'STAGE _ 1 _ FAILED': '<S1>:119' *)
IF (stage3 _ sensor <= 0) OR (stage2 _ sensor <= 0) THEN
(* Transition: '(<S1>:150' *)
(* Transition: '(<S1>:152' *)
IF stage2 _ sensor > 0 THEN
(* Transition: '<S1>:155' *)
is _ c2 _ Setpoint := Setpoint _ IN _ STAGES _ 1 _ 3 _ FAILED;
(* Entry 'STAGES _ 1 _ 3 _ FAILED': '<S1>:120' *)
rtb _ stage1 _ setpoint := L0;
rtb _ stage2 _ setpoint := L0 – overall _ target;
distributed _ target := rtb _ stage2 _ setpoint;
ELSE
(* Transition: '<S1>:154' *)
IF stage3 _ sensor > 0 THEN
(* Transition: '<S1>:159' *)
is _ c2 _ Setpoint := Setpoint _ IN _ STAGES _ 1 _ 2 _ FAILED;
(* Entry 'STAGES _ 1 _ 2 _ FAILED': '<S1>:121' *)
rtb _ stage1 _ setpoint := L0;
rtb _ stage2 _ setpoint := L0;
distributed _ target := L0 – overall _ target;
ELSE
guard _ 0 := TRUE;
END _ IF;
END _ IF;
ELSE
guard _ 0 := TRUE;
END _ IF;
on the PLC that closely match the results
we saw in simulation. Simulink PLC Coder
produces a test bench that lets us compare
test execution results from the IDE with the
original simulation results.
If we wanted to test the fully implemented PLC hardware and software using
hardware-in-the-loop testing, we could
generate C code from the plant model using
Simulink Coder™ and run it on a real-time
simulator, such as xPC Target™, connected
to the PLC control system. ■
Resources
Learn More
Video: Simulink PLC Coder Overview
mathworks.com/slplccoder-video
AVL Develops Dynamic Controller for
Engine Conditioning System Using Embedded
Code Generation for PLCs
mathworks.com/avl-userstory
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
25
Real-Time Simulation of Physical Systems
Using Simscape
By Steve Miller and Jeff Wendlandt
Replacing a physical system like a vehicle, plane, or robot with a
real-time simulation of a virtual system drastically reduces the cost of testing
control software and hardware. In real-time simulation, the inputs and outputs in
the virtual world of simulation are read or updated synchronously with the real
world. When the simulation time reaches 5, 50, or 500 seconds, exactly the same
amount of time has passed in the real world. Testing can take place 24 hours a
day, 7 days a week, under conditions that would damage equipment or injure
personnel, and it can begin well before physical prototypes are available.
R
eal-time simulation of physical systems requires finding a combination of
model complexity, solver type, solver settings, and simulation hardware that permits
execution in real time and delivers results
sufficiently close to the results obtained from
desktop simulation. Changing these items
will often speed up the simulation but reduce
the accuracy, or vice-versa. Simscape™ provides several capabilities that make it easier
to configure your models for real-time simulation. This article shows how to configure
a Simscape model of a pneumatic actuation
system for real-time simulation (Figure 1).
The steps described apply regardless of the
real-time hardware used.
26
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Moving from Desktop to Real-Time
Simulation
Configuring the Simscape model for realtime simulation involves five steps:
1. Obtain reference results with a variablestep solver.
2. Examine the step sizes during simulation.
3. Choose a fixed-step solver and configure a
fixed-cost simulation.
4. Find the right balance between accuracy
and simulation speed.
5. Simulate the model on the real-time
platform.
1. Obtaining Reference Results
with a Variable-Step Solver
A variable-step solver shrinks the step size
to accurately capture events and dynamics in
the system. Since this reduces the amount of
time that the real-time target has to calculate
the results for that time step, a variable-step
solver cannot be used for real-time simulation. Instead, an implicit or explicit fixedstep solver must be used.
To ensure that the results obtained with
the fixed-step solver are accurate, we compare them with reference results obtained by
simulating the system with a variable-step
solver and tightening the error tolerances
until the simulation results stop changing
(Figure 2). The recommended variable-step
solvers for Simscape models are ode15s and
ode23t.
2. Examining the Step Sizes During
Simulation
A variable-step solver varies the step size to
stay within the error tolerances and to react
Reference Results
PS S
Spool
Power (kW)
Solver
Configuration
Flow
P
B
B
B
A
A
B
Pipe 1
B
S
R
RPM
B
A
1
out
kW
C
RPM
Pipe 2
Directional 5−way
valve
Pneumatic
Atmospheric
Reference
Pneumatic Vane
Motor
Friction
Load
Desktop Settings
Stiff
Real Time Settings
Less Stiff
R
S
A
Pressure
Source
A
xPC
xd(mm)
A
R
C
f(x)=0
Volumetric
flow (m^3/min)
Figure 2. Plot of reference results obtained from
variable-step simulation.
Step Size vs. Time
Figure 1. Simscape model of a pneumatic actuation system to be configured for real-time simulation.
to zero crossing events. If the solver abruptly
reduces the step size to a small value, such
as 1e-15s, this indicates that the solver is
trying to accurately identify a zero crossing
event such as a reverse in flow or closing of a
switch. A fixed-step solver may have trouble
capturing these events at a step size large
enough to permit real-time simulation.
We use the following MATLAB® commands to generate a plot showing how the
time step varies during the simulation:
semilogy
(tout(1:end-1),diff(tout),’-*’);
title
(‘Step Size vs. Simulation Time’,’Fon
tSize’,14,’FontWeight’,’bold’);
xlabel
(‘Simulation Time(s)’,’FontSize’,12);
ylabel
(‘Step Size(s)’,’FontSize’,12);
The plot indicates that we should adjust
the friction model (see Figure 1, Friction
Load) to make the system model real-time
capable (Figure 3).
3. Choosing a Fixed-Step Solver
and Configuring a Fixed-Cost
Simulation
We must use a fixed-step solver that provides
robust performance and delivers accurate
results at a step size large enough to permit
real-time simulation. We compare the simulation results generated by an implicit fixedstep solver and an explicit fixed-step solver
for the same model at different step sizes
(Figure 4). For our example model, the implicit solver provides more accurate results.
For real-time simulation, overruns that
occur when the execution time is longer
than the sample time must be prevented
(Figure 5). To do this, we run a fixed-cost
simulation, limiting the number of iterations per time step.
As Figure 5 shows, iterations are often
necessary for each Simscape physical network for both explicit and implicit solvers.
The iterations in Simscape are limited by
setting the checkbox “Use fixed-cost runtime consistency iterations” and entering
the number of nonlinear iterations in the
Solver Configuration block. For the best
balance between accuracy and cost, we
recommend initially setting the number of
nonlinear iterations to two or three.
By using the local solver option in Simscape,
we can use an implicit fixed-step solver on
the stiff portions of the model and an explicit fixed-step solver on the remainder of the
model (Figure 6). This minimizes the number of computations performed per time
step, making it more likely that the model
will run in real time.
Motor RPM
Figure 3. Top: Plot of step size during simulation. Bottom: Plot of motor speed. The zero crossing events coincide with the speed of the motor
approaching or leaving 0 RPM, indicating that
the friction model may need to be adjusted to
make the system model real-time capable.
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
27
Accuracy of Implicit and Explicit Fixed-Step Solvers
Variable Step
Fixed Step Implicit, Ts = 1e-3 sec
Flow Rate
Fixed Step Explicit, Ts = 1e-3 sec
Fixed Step Explicit, Ts = 5e-4 sec
Time (s)
Figure 4. Plot comparing simulation results when the model is simulated with a variable-step solver,
an implicit fixed-step solver, and an explicit fixed-step solver. The explicit solver requires a smaller time
step than an implicit solver to achieve a comparable level of accuracy.
Solution
Iteration 1
Iteration 2
Iteration 3
___ True Solution
Simulation Time
Time required to calculate
solution per iteration.
Simulation overrun because too
many iterations are required.
Real Time
Figure 5. How an overrun occurs. Top: More iterations are sometimes required to obtain an accurate
solution. Bottom: Simulation overrun occurs because iterations can’t be completed within the time step,
which is held constant for a fixed-step simulation.
4. Balancing Accuracy and
Simulation Speed
During each time step, the real-time system
reads the inputs, calculates the simulation
results for the next time step, and writes the
outputs. If this task takes less time than the
28
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
specified time step, the processor remains
idle during the remainder of the step.
The challenge is to find settings that
provide accurate results while permitting
real-time simulation (Figure 7). In each
case, there is a tradeoff of accuracy versus
speed. Choosing a computationally intensive solver, increasing the number of nonlinear iterations, or reducing the step size
increases accuracy and reduces idle time,
raising the risk that the simulation will not
run in real time. On the other hand, adjusting these settings in the opposite direction
increases the amount of idle time but reduces accuracy.
By using the Simscape Backward Euler
local solver and limiting the number of iterations to two, we obtain accurate simulation results for our Simscape model at an
acceptable simulation speed.
5. Simulating the Model on the
Real-Time Platform
Our model ran in real time on a 700 MHz
processor and used only 62% of the available
step size to perform the necessary calculations. The results obtained from the real-time
simulation were identical to those obtained
using the same solver settings during the
desktop simulation. These results were also
very close to the reference results obtained
using a variable-step solver (Figure 8).
Extending This Approach
The approach described in this article is not
limited to one type of model. We applied this
approach to more than 30 models spanning a
range of applications and physical domains.
These models contain hydraulic, electrical,
mechanical, pneumatic, and thermal elements, and include applications such as hydromechanical servovalves, brushless DC
motors, hydraulic pipelines with water hammer effects, and pneumatic actuation systems with stick-slip friction. All models were
able to run in real time on an Intel® Core 2
Duo E6700 (2.66 GHz) that was running
xPC Target™. The maximum percentage of a
step spent in simulation execution was less
than 18%, leaving a wide safety margin for
processing I/O and other tasks. The average
percentage spent in simulation execution
was 3.9%, and the minimum was 6e-4%. ■
Local implicit
fixed-step solver #1
Explicit fixed-step solver
Comparing Simulation Results
Simscape
Physical
Network
Controller
Simscape
Physical
Figure 8. Plot comparing reference results obtained with variable-step solver and simulation
results after configuring for real-time simulation.
Network
Local implicit
fixed-step solver #2
Figure 6. Diagram showing use of multiple solvers on a single model. Using local solvers lets you
configure implicit solvers on the stiff portions of the model and explicit solvers on the remainder of the
model, minimizing execution time while maintaining accuracy.
Maximum Possible Step Size
Larger step sizes result in poor accuracy and robustness
Affected by solver choice and # of nonlinear iterations
Chosen Step Size
Minimum Possible Step Size
Smaller step sizes result in overrun
Execution Time
Safety Margin
Affected by solver choice
and # of nonlinear iterations
Affected by
step size
Simulation
Execution
Processing
I/O and
Other Tasks
Idle
Step Size
Figure 7. The tradeoff involving solver choice, number of nonlinear iterations, and step size. For any
given model, these settings must be chosen to deliver maximum accuracy and robustness with enough
idle time to provide sufficient safety margin.
Resources
Learn
More
Video: Configuring Simscape Models for
Real-Time Simulation
mathworks.com/simulating-realtime
Interactive Model: Real-Time Simulation of
a Hybrid-Electric Vehicle
mathworks.com/hybrid-vehicle
Real-Time Simulation of Physical Systems
Using Simscape
mathworks.com/simscape-paper
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
29
CLEVE’S CORNER
Computing π
By Cleve Moler
Computing hundreds, or trillions, of digits of π has long been used to stress hardware, validate software, and establish
bragging rights. MATLAB® implementations of the most widely used algorithms for computing π illustrate two different styles
of arithmetic available in Symbolic Math Toolbox™: exact rational arithmetic and variable-precision floating-point arithmetic.
L
ast August, two computer hobbyists, Alexander Yee and Shigeru
Kondo, announced that they had set a world record by computing
5 trillion digits of π (Figure 1). Their computation took 90 days on a
“homebrew” PC. Yee is now a graduate student at the University of
Illinois. His computing software, “y-cruncher,” began as a class project at Palo Alto High School. Kondo is a systems engineer who assembles personal computers at his home in Japan. The machine that
Cleve's Corner: Computing π
he built for this project (Figure 2) has two Intel® Xeon® processors
Computing hundreds, or trillions, of digits of π has long been used to stress hardware, validate software,
and
establish
braggingof
rights.
of the most
used algorithms
with
a total
12 MATLAB
cores,implementations
96 gigabytes
ofwidely
RAM,
and 20for external hard
computing π illustrate two different styles of arithmetic available in Symbolic Math Toolbox: exact
rational
variable-precisioncapacity
floating-point of
arithmetic.
disksarithmetic
with aandcombined
32 terabytes.
Last August, two computer hobbyists, Alexander Yee and Shigeru Kondo, announced that they had
The computation of 5 trillion digits is a huge processing task
set a world record by computing five trillion digits of π. Their computation took 90 days on a homebrew
PC. Yee is now a graduate student at the University of Illinois. His computing software, “y-cruncher”,
where
the time required for the data movement is just as important
began as a class project at Palo Alto High School. Kondo is a systems engineer who assembles personal
computers at his home in Japan. The machine that he built for this project (Figure 1) has two Intel Xeons
as
the
time
required
for
the
arithmetic.
with a total of 12 cores,
96 gigabytes of
RAM,
and 20
external hard disks with a combined capacity of 32
terabytes.
y-cruncher uses several different formulas for computation and
The computation of five trillion digits is a huge processing task where the time required for the data
verification.
The primary
toolforisthea arithmetic.
formidable formula discovered by
movement
is just as important
as the time required
y-cruncher
usesGregory
several different
formulas for computation
and verification. The primary tool is a
David
and
Chudnovsky
in 1987:
formidable formula discovered by David and Gregory Chudnovsky in 1987.
The Chudnovsky brothers, who were the subject of two fascinating articles in the New Yorker and a
NOVA documentary, have also built “home brew” computers in their apartment in Manhattan. The
massively parallel machine that they assembled from commodity parts in the 1990s was considered a
supercomputer at the time.
The Chudnovsky brothers, who were the subject of two fascinating articles in The New Yorker and a NOVA documentary, have also
High-Precision Arithmetic in Symbolic Math Toolbox
built homebrew computers in their apartment in Manhattan. The
Symbolic Math Toolbox provides two styles of high-precision arithmetic, sym and vpa.
massively parallel machine that they assembled from commodity
The sym function initiates exact rational arithmetic: Arithmetic quantities are represented by
quotients
large integers.
length increasesaassupercomputer
necessary, limited only by computer
parts and
in roots
theof1990s
wasInteger
considered
at the time.
time and storage requirements. Quotients and roots are not computed unless the result is an exact
integer.
High-Precision Arithmetic in Symbolic Math Toolbox
Symbolic
Math
Toolbox
provides
tworoundoff
styles
ofat the
high-precision
arithArithmetic
operations,
including
divisions and
roots, can involve
errors
level of the
specified accuracy.For example, the MATLAB statement
metic: sym and vpa.
p = rat(pi)
The sym function initiates exact rational arithmetic: Arithmetic
quantities are represented by quotients and roots of large integers.
Integer length increases as necessary, limited only by computer
time and storage requirements. Quotients and roots are not computed unless the result is an exact integer.
Figure 1. A log plot of the data from the Wikipedia article “Chronology of
computation of pi” showing how the world record for number of digits has
increased over the last 60 years. A linear fit to the logarithm reveals a Moore’s
Law phenomenon. The number of digits doubles about every 22.5 months.
The vpa function initiates variable-precision floating-point
arithmetic: Arithmetic quantities are represented by decimal fractions of a specified length together with a power-of-10 exponent.
Arithmetic operations, including divisions and roots, can involve
roundoff errors at the level of the specified accuracy. For example,
the MATLAB statement
The vpa function initiates variable-precision floating-point arithmetic: Arithmetic quantities are
represented by decimal fractions of a specified length together with a power-of-ten exponent.
30
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
p = rat(pi)
produces three terms in the continued fraction approximation of π
p = 3 + 1/(7 + 1/16)
Then the statement
sym(p)
yields the rational expression
355/113
which is an attractive alternative to the familiar 22/7. On the other hand,
the statement
vpa(p,8)
produces the 8-digit floating-point value
produces three terms in the continued fraction approximation of π
p =
3 + 1/(7 + 1/16)
3.1415929
Then the statement
sym(p)
The Chudnovsky Algorithm
Our
MATLAB programs implement three of the hundreds of possible
355/113
algorithms
for computing
π. OnThe
Chudnovsky
which
is an attractive alternative
to the familiar 22/7.
the other
hand, the statementalgorithm (Figure 3)
vpa(p,8)
uses
exact rational arithmetic until the last step. Each term in the
produces
the 8-digit floating-point
value
Chudnovsky
series
provides about 14 decimal digits, so to obtain d
3.1415929
digits
requires [d/14] terms. For example, the statement
yields the rational expression
Figure 2. Shigeru Kondo’s homebrew PC, which currently holds the world
record for computing digits of π.
function P = chud _ pi(d)
% CHUD _ PI Chudnovsky algorithm for pi.
The Chudnovsky Algorithm
% chud _ pi(d) produces d decimal digits.
Our MATLAB programs implement three of the hundreds of possible algorithms for computing π.
The Chudnovsky
algorithm (Figure 2) uses exact rational arithmetic until the last step. Each term in the
chud_pi(42)
Chudnovsky series provides about 14 decimal digits, so to obtain d digits requires
terms. For
example, the statement
k = sym(0);
chud_pi(42)
uses
exact rational computation to produce
uses exact rational computation to produce
s = sym(0);
sig = sym(1);
n = ceil(d/14);
for j = 1:n
s = s + sig * prod(3*k+1:6*k)/prod(1:k)^3 * ...
and then the final step uses variable-precision floating-point arithmetic with 42 digits to produce
and
then the final step uses variable-precision floating-point arithmetic
3.14159265358979323846264338327950288419717
with
42 digits
to the
produce
One interesting
fact about
digits of π is revealed by
chud_pi(775)
or
3.14159265358979323846264338327950288419717
vpa(pi,775)
One interesting fact about the digits of π is revealed by
chud_pi(775)
(13591409+545140134*k) / 640320^(3*k+3/2);
k = k+1;
sig = -sig;
end
S = 1/(12*s);
P = vpa(S,d);
Figure 3. MATLAB implementation of the Chudnovsky algorithm, using
sym to initiate exact rational arithmetic.
or
vpa(pi,775)
These both produce 775 digits, beginning and ending with
3.141592653589793238 ...... 707211349999998372978
We see not only that chud_pi is working correctly but also that
there are six 9s in a row around position 765 in the decimal expansion of π (Figure 4).
Computing 5000 digits with chud_pi requires 358 terms and
takes about 20 seconds on my laptop. The final symbolic expression
contains 12,425 characters.
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
31
=
=
bn+1 = �𝑎𝑎𝑛𝑛 𝑏𝑏𝑛𝑛
=
until a==
n and bn agree to a desired accuracy. For
example,
arithmetic
mean ofaccuracy.
1 and 9 isFor
5, the
until
andthe
bnagree
agree
to aa desired
desired
example,
the
arithm
until
aannand
and
bmean
to
accuracy.
Forexample,
example,
the
arithm
nagree
geometric
is
3,
and
the
agm
is
3.9362.
until
a
b
to
a
desired
accuracy.
For
the
arithme
n
n
geometric
mean
is
3,
and
the
agm
is
3.9362.
geometric
mean
is
3,
and
the
agm
is
3.9362.
geometric
mean isproperties
3, and theof
agm
3.9362.
The powerful
theisagm
lie not just in
The
powerful
properties
ofresults
the agm
lie not just in the final value
theThe
final
value
but
also
in
the
generated
powerfulproperties
propertiesofofthe
theagm
agmlielienot
notjust
justininthe
the
final
valu
The
powerful
final
value
along
the
way.
Computing
isisjust
one
compu
along
theway.
way.Computing
Computingπππis
justone
oneexample.
example.ItItItinvolves
along
the
just
example.
involves
comp
along the way. Computing π is just one example. It involves comput
involves computing
(
)
((
))
M = agm(1,1/√2)
During the iteration, keep track of the changes,
During
the
iteration,
keep
track
ofthe
thechanges,
changes,
During
the
iteration,
keep
track
During
the
iteration,
keep
track
of track
theof
changes,
During
the
iteration,
keep
of the
changes,
Duringthe
theiteration,
iteration,keep
keeptrack
trackofofthe
thechanges,
changes,
During
cn = an+1 - an
an+1 - an
c
ncn==an+1
Finally,
letlet- an
Finally,
Finally,
let
Finally,
let
Finally,
Finally,1let
let
Finally,
let
𝑛𝑛 2
S = 1 – ∑∞
𝑛𝑛=0 2 𝑐𝑐𝑛𝑛
14
∞ 𝑛𝑛 𝑛𝑛 2 2
∞
∑
S
=
–
𝑐𝑐𝑛𝑛
2
S = 4– ∑𝑛𝑛=0
𝑛𝑛=02 𝑐𝑐𝑛𝑛
Then4
Then
Then
Then
Then
Then
Then
𝑀𝑀2
2
𝜋𝜋
=
𝑀𝑀𝑀𝑀2
These both produce 775 digits, beginning and ending with
𝜋𝜋𝜋𝜋== 𝑆𝑆𝑆𝑆
Our MATLAB 𝑆𝑆
function for the agm algorithm (Figure 3) uses variable- precision floating-point
arithmetic from the very beginning. If we used symbolic rational arithmetic, we would end up with a
Our
MATLAB
function
the
agm
algorithm
(Figure
uses
variableprecision
floating-point
3.141592653589793238 ...... 707211349999998372978
Our
MATLAB
function
forfor
the
agm
algorithm
(Figure
3) 3)
uses
precision
floating-point
nested
sequence
of square
roots.
After
just two
iterations
wevariablewould have
arithmetic
from
very
beginning.
If we
used
symbolic
rational
arithmetic,
would
end
with
arithmetic
from
thethe
very
beginning.
If we
used
symbolic
rational
arithmetic,
wewe
would
end
upup
with
a a
nested
sequence
square
roots.
After
two
iterations
would
have
nested
sequence
of of
square
roots.
After
justjust
two
iterations
wewe
would
have
2
Our MATLAB function for the agm algorithm (Figure 5) uses
variable-precision
floating-point
arithmetic
from the very beginning.
We see not only that chud_pi is working correctly but also that there are six
9s�in
around
√2a row
22
1
If wefunction
usedforsymbolic
rational
we would
end up with a nest√2
2 3)arithmetic,
Our MATLAB
the agm algorithm
(Figure
uses√2
variable- precision
floating-point
√2
position 765 in the decimal expansion of π (Figure 4). arithmetic
⎛
��
+
+1 ⎞
from the very beginning. If we used symbolic
end up with a
Figure 4. 10,000 digits of π, visualized in MATLAB. Can you see the six
√2
8arithmetic,
4⎞we would
1⎞
√2
222+rational
⎛roots.
ed sequence
of After
square
After
just
two
iterations
we would have
⎛two
+
+
nested sequence
of square roots.
just
iterations
we would
have
+
22
consecutive 9s in the eighth row?
88 44
⎝ 20 seconds on
⎠ my
Computing five thousand digits with chud_pi requires 358 terms and takes about
⎝⎝
⎠⎠
laptop. The final symbolic expression contains 12,425 characters.
2
�√2
The Algebraic-Geometric Mean Algorithm
TheAlgebraic-Geometric
Chudnovsky formula is a power
series:
Each new term in the partial
The
Mean
Algorithm
2
22
1
√2
√2 ��
√2 1
2 + 1⎞
√2
− �√2 −112�2 − 2 ⎛√2 −
11
4⎞
4− �
√28 − 222 +11
√24 − 2� − 2⎛⎛
⎞
− � 4− 2
� −2
8− 22 + 44
8
44
4
2
⎝
⎠
⎝⎝
⎠⎠ to 𝜋𝜋. The
The decimal value of this monstrosity is 3.14168, so
it is not yet a very good approximation
These both
produce
775 digits,
beginning
endingof
withaccuracy. The algebraic-geometric
sum
adds
a fixed
number
ofand
digits
3.141592653589793238
......
707211349999998372978
mean
algorithm
is
completely
different;
it is quadratically
convergent:
The Chudnovsky formula is a power
series: Each
new term
in the
partial
sumis 3.14168,
adds ait isfixed
number
of to 𝜋𝜋. The
complexity
doubles
with each
iteration.
The
decimal
value
monstrosity
a very
good
approximation
The
decimal
value
of of
thisthis
monstrosity
is 3.14168, so so
it is notnot
yetyet
a very
good
approximation
to 𝜋𝜋. The
We
see
not
only
that
chud_pi
is
working
correctly
but
also
that
there
are
six
9s
in
a
row
around
complexity
doubles
with
each
iteration.
Each of
new
iteration doubles
the number of correct digits.
Thealgorithm
agm al- complexity
digits
accuracy.
The
algebraic-geometric
mean
is
completely
different;
it
is
quadratically
doubles
with
each
iteration.
Such exact symbolic expressions are computationally unwieldy and inefficient. With vpa, however, the
position 765 in the decimal expansion of π (Figure 4).
quadratic
convergence
can be seen
in
the successive unwieldy
iterates: and inefficient. With vpa, however, the
Such
exact
symbolic
expressions
computationally
gorithm has a Each
long history
dating backdoubles
to Gauss and
Such
exact
symbolic
expressions
areare
computationally
unwieldy
and inefficient.
convergent:
new iteration
theLegendre.
numberItsofabilcorrect
digits.
The
agm
algorithm
has
a longWith vpa, however, the
Computing five thousand digits with chud_pi requires 358 terms and takes about 20 seconds on my
quadratic
convergence
seen
in the
successive
iterates:
quadratic
convergence
cancan
bebe
seen
in the
successive
iterates:
3.2
laptop.
The
final symbolic
expression
contains 12,425independently
characters.
ity
to
compute
π
was
discovered
by
Richard
Brent
and
history dating back to Gauss and Legendre. Its ability toThecompute
π was discovered independently by
3.142
3.2
decimal3.2
value
of this monstrosity is 3.14168, so it is not yet a very good approximation to . The
The Algebraic-Geometric
Mean
Algorithm
3.142
Eugene
Salamin
in
1975.
complexity doubles
each iteration.
Thewith
decimal
value of this monstrosity is 3.14168, so it is not yet a very
3.142
Richard
Brent and
Eugene Salamin in 1975.
The Chudnovsky
formula is
a power of
series:
Eachnumbers,
new term in the(a+b)/2,
partial sum adds
fixed number
of Such exactgood
symbolicapproximation
expressions are computationally
unwieldy
and inefficient.doubles
With vpa,with
however,
the iteration.
The
arithmetic
mean
two
is aalways
greater
to π. The
complexity
each
digits of accuracy. The algebraic-geometric mean algorithm is completely different; it is quadratically quadratic convergence can be seen in the successive iterates:
convergent:
Eachgeometric
new iteration doubles
the number
ofTheir
correct digits.
The agm algorithm has a long mean,
than
their
mean,
√ab.
arithmetic-geometric
Such
exact
symbolic
expressions
are
computationally
unwieldy
The
arithmetic
meanItsof
two
numbers,
(a+b)/2,
greater than their geometric mean,
.
3.2
history
dating
back to Gauss and Legendre.
ability
to compute
π was discovered
independentlyis
byalways
or
agm(a,b),
is
computed
3.142 and inefficient. With vpa, however, the quadratic convergence can
Richard
Brent and Eugene
Salamin in 1975.by repeatedly taking arithmetic and geoTheir arithmetic-geometric mean, or agm(a,b), is computed
by repeatedly taking arithmetic and
3.1415927
metric
means.
with
a
=
a
and
b
=
b,
iterate
be seen in the successive iterates:
3.141592653589793
The arithmetic
meanStarting
of two numbers,
(a+b)/2,
is
always
greater
than
their
geometric mean, √𝑎𝑎𝑎𝑎.
0
0
geometric means. Starting with a = a and b = b, iterate
0
Their arithmetic-geometric mean, or agm(a,b), is computed by 0repeatedly taking arithmetic
and
geometric means. Starting with a0 = a and b0 = b, iterate
3.1415926535897932384626433832795
3.141592653589793238462643383279502884197169399375105820974944592
3.2
3.142
The quadratic
convergence makes agm very fast. To compute 100,000 digits requires only 17 steps
2
and about 2.5 seconds on my laptop.
3.1415927
bn+1 == �𝑎𝑎𝑛𝑛 𝑏𝑏𝑛𝑛
The BBP Formula
3.141592653589793
Yee spot-checked his computation with the BBP formula. This formula, named after David Bailey,
3.1415926535897932384626433832795
Jonathan Borwein,
and Simon Plouffe and discovered by Plouffe in 1995, is a power series involving
until an and bn agree to a desired accuracy. For
inverse
powers
of 16.
until
a
b
agree
to
a
desired
accuracy.
For
example,
the
arithmetic
mean of 1 and 9 is 5, the
until
a
and
b
agree
to
a
desired
accuracy.
For
example,
the
arith3.1415926535897932…79502884197169399375105820974944592
n nand
n
n arithmetic mean of 1 and 9 is 5, the
example, the
geometric
mean
is
3,
and
the
agm
is
3.9362.
metic
mean of
1 andis9 3,
is 5,
thethe
geometric
is 3, and the agm
geometric
mean
and
agm ismean
3.9362.
is 3.9362.
The sixth entry in this output has 64 correct digits, and the tenth
Thepowerful
properties
ofagm
thelieagm
agm
lie not
not
just
invalue
powerful
properties
the
lie
just
in
the finalhasvalue
1024.but also in the results generated
The
properties
of theof
not just
in the
final
thealso
final
value
butgenerated
also inπthe
results
generated
along
theinway.
Computing
is just
one
example.
but
the results
along
the
way.
ComputingItπinvolves
is just computing
The quadratic convergence makes agm very fast. To compute 100,000
along
the way.
Computing
π is just one example. It
digits requires only 17 steps and about 2.5 seconds on my laptop.
one
example.
It involves
computing
an+1 ==
𝑎𝑎𝑛𝑛 + 𝑏𝑏𝑛𝑛
involves computing
(
)
M =the
agm(1,1/√2)
During
iteration, keep track of the changes,
32
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
Finally, let
The tenth entry is this output would have 1024 correct digits.
function P = agm _ pi(d)
% AGM _ PI Arithmetic-geometric mean for pi.
% agm _ pi(d) produces d decimal digits.
Our MATLAB function for the agm algorithm (Figure 3) uses variable- precision floating-point
arithmetic
from the very beginning. If we used symbolic rational arithmetic, we would end up with a
digits(d)
nested sequence of square roots. After just two iterations we would have
a = vpa(1,d);
b = 1/sqrt(vpa(2,d));
s = 1/vpa(4,d);
p = 1;
n = ceil(log2(d));
for k = 1:n
c = (a+b)/2;
b = sqrt(a*b);
s = s - p*(c-a)^2;
p = 2*p;
The decimal
of this monstrosity is 3.14168, so it is not yet a very good approximation to . The
a value
= c;
complexity doubles with each iteration.
end
Such exact symbolic expressions are computationally unwieldy and inefficient. With vpa, however, the
P = a^2/s;
quadratic convergence can be seen in the successive iterates:
3.2
3.142 5. MATLAB implementation of the arithmetic-geometric mean
Figure
3.1415927
algorithm,
using digits and vpa to initiate variable-precision floating3.141592653589793
3.1415926535897932384626433832795
point
arithmetic.
3.141592653589793238462643383279502884197169399375105820974944592
The tenth entry is this output would have 1024 correct digits.
The
BBP Formula
The quadratic
convergence makes agm very fast. To compute 100,000 digits requires only 17 steps
and
about
2.5 seconds on myhis
laptop.
Yee spot-checked
computation with the BBP formula. This forThe
BBP Formula
mula,
named
after David Bailey, Jonathan Borwein, and Simon
Plouffe
and discovered
bywith
Plouffe
1995,This
is aformula,
power
series
Yee spot-checked
his computation
the BBPin
formula.
named
afterinvolving
David Bailey,
Jonathan Borwein, and Simon Plouffe and discovered by Plouffe in 1995, is a power series involving
inverse
powers
of
16:
inverse powers of 16.
The remarkable property of the BBP formula is that it allows the
computation of several consecutive hexadecimal digits in the base
16 expansion of π without computing the earlier digits and without
using extra-precision arithmetic. A formula for the hex digits starting at position d is obtained by simply multiplying this formula by
16d and then taking the fractional part.
I can’t resist concluding that BBP can be used to compute just a
piece of π.
Our BBP program is too long to be included here, but all three
programs, chudovsky_pi, agm_pi, and bbp_pi, are available for
download on MATLAB Central. ■
References
Alexander J. Yee and Shigeru Kondo, “5 Trillion Digits of Pi,”
August 2, 2010.
www.numberworld.org/misc_runs/pi-5t/details.html
Richard Preston, “The Mountains of Pi,” The New Yorker,
March 2, 1992.
www.newyorker.com/archive/1992/03/02/1992_03_02_036_TNY_
CARDS_000362534
Richard Preston, “Capturing the Unicorn,” The New Yorker,
April 11, 2005.
www.newyorker.com/archive/2005/04/11/050411fa_fact
“Brothers Chudnovsky,” PBS, NOVA, July 26, 2005.
www.pbs.org/wgbh/nova/physics/chudnovsky-math.html
David Bailey, Jonathan Borwein, Peter Borwein, and Simon Plouffe,
“The Quest for Pi,” Mathematical Intelligencer 19, pp. 50-57, 1997.
http://crd.lbl.gov/~dhbailey/dhbpapers/pi-quest.pdf
Jonathan M. Borwein and David H. Bailey, Mathematics by
Experiment: Plausible Reasoning in the 21st Century, AK Peters,
Natick, MA, 2008.
“Chronology of computation of pi,” Wikipedia, March 9, 2011.
http://en.wikipedia.org/wiki/Chronology_of_computation_of_π
Learn More
Download: MATLAB Implementations of
the Chudnovsky, agm, and BBP Algorithms
mathworks.com/computing-pi
Cleve's Corner Collection
mathworks.com/clevescorner
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
33
TIPS AND TRICKS
Combining Functions Using Anonymous Functions
By Loren Shure
Anonymous functions let you create simple functions as variables without having to store the functions in a file. You can
construct complex expressions by combining multiple anonymous functions. Here are some sample combinations.
Function Composition
In this example we will create a single function by having one function call another.
Suppose we want to compute the standard deviation of the mean of some data—
for example, std(mean(x)). We can construct separate anonymous functions to
compute the mean and standard deviation
and then combine them:
f = @mean;
Conditional Function Composition
Now let’s look at a more complicated composition. Suppose that we want to compute
the expression: y = sin(x) – mean(x) + 3, but
we don’t always want to subtract the mean or
add 3. We dynamically build one function to
compute y, which subtracts the mean or adds
3 only when we want it to.
Let’s start by building function handles
for computing the sine, subtracting the
mean, and adding 3:
Let’s try this on the data x that we created
earlier:
mf3mean = myfunc(x);
Whatever functions we combine with the
original function, we always have a function handle to evaluate. We can use it to
specify additional information as we build
up an appropriate function for our calculation.
g = @std;
fCompg = @(x) g(f(x));
x = 0:pi/100:pi/2;
myfunc = @sin;
To ensure that the function composition works as expected, we evaluate the first
function and use its output as input to the
second. We then check that this two-step
process is equivalent to the one-step evaluation of the result that we obtained from
function composition:
x = rand(10,4);
fx = f(x);
gfx = g(fx);
gfx2 = fCompg(x);
gfsEqual = isequal(gfx,gfx2)
gfsEqual = 1
We could create a generalized composition operator g(f) and use that instead:
meanValue = @mean;
three = @(x) 3;
While the variable containing each function handle retains its name, the function
it describes can change. Note that this example works only when x is a row or column
vector. For multidimensional data, the expressions would be more complicated, and
we would use bsxfun.
We combine these functions conditionally. For simplicity, let’s say we want to add
3 but don’t want to subtract the mean. In a
more realistic example, we would use logical comparisons to determine which functions to apply:
A Versatile Technique
Using anonymous functions is a versatile
technique that you might find useful in a
wide range of calculations, from the simplest
to the most complex. We’ve looked at just
two examples. In fact, the number of possibilities is limitless. ■
if false
compose = @(g,f)@(x)g(f(x))
fCompg2 = compose(g,f)
gfcx = fCompg2(x);
gfcEqual = isequal(gfx, gfcx)
gfcEqual = 1
34
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
myfunc = @(x) myfunc(x) - meanValue(x);
end
if true
myfunc = @(x) myfunc(x) + three(x);
end
Learn More
Loren on the Art of MATLAB®
http://blogs.mathworks.com/loren
MATLAB AND SIMULINK BASED BOOKS
System Dynamics
Curriculum Materials
With an emphasis on mathematical modeling
and simulation, system dynamics is a multidomain discipline used in many fields, including engineering, biology, and the social
sciences. MathWorks has collaborated with
McGraw-Hill to develop a set of curriculum
materials to support this core undergraduate
course. The materials use industry-standard
software tools to model thermal, hydraulic,
and electromechanical systems.
Based on the textbook System Dynamics, 2e
by William Palm III, they include models developed using Simulink® and Simscape™, five
sets of lecture slides that provide a step-bystep guide to creating each model, and more
than 40 MATLAB® and Simulink examples illustrating concepts from the text. An instructor
evaluation copy of the textbook is available
upon request.
Teaching MATLAB Programming to First-Year Students
“Learning MATLAB changed the meaning of scientific computing for me. I used to think in
terms of machine-specific compilers and tables of numbers as output. Now, I expect and enjoy interactive calculation, programming, graphics, animation, and complete portability across
platforms—all under one roof.” —Rudra Pratap, Indian Institute of Science
First-year science and engineering students who have a solid grasp of MATLAB programming are well prepared to tackle upper-level courses and projects. MATLAB is
widely used in many industries for algorithm development, data visualization, data analysis, and numeric computation. For this reason, universities worldwide have chosen to teach
MATLAB early in the curriculum to prepare student for careers in industry and academia.
Recent textbooks based on MATLAB include:
Getting Started with MATLAB: A Quick
MATLAB 고급 GUI 개발
Introduction for Scientists and Engineers
(MATLAB: Advanced GUI Development)
By Rudra Pratap, Oxford University Press
By Scott T. Smith, A-Jin Publishing Co., Ltd.
Language: English
Language: Korean
Essentials of MATLAB Programming, 2e
使える!MATLAB/Simulink プログラミング
By Stephen J. Chapman, Cengage Learning
(Ready to Use! MATLAB/Simulink
Language: English
Programming)
By Takanobu Aoyama, Kodansha Scientific
MATLAB 7 für Ingenieure: Grundlagen und
Language: Japanese
Programmierbeispiele, 5e
(MATLAB 7 for Engineers: Basics and
ABC de MATLAB y Simulink para Ciencias
Programming Examples, 5e)
Aplicadas e Ingeniería
By Florian and Frieder Grupp, Oldenbourg-Verlag
(ABCs of MATLAB and Simulink for Applied
Language: German
Sciences and Engineering)
By Gustavo Damián Gil, Editorial C.E.I.T.
MATLAB高效编程技巧与应用: 25个案例分析
Language: Spanish
(Efficient Programming Techniques and
Applications in MATLAB: 25 Case Studies)
By Wu Peng, BUAA Press
Download the materials:
mathworks.com/instructor-materials
Language: Chinese
Resources
Learn
More
1400+ MATLAB and Simulink Based Books
mathworks.com/books
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
35
THIRD-PARTY PRODUCTS
Rapid Prototyping and Hardware-in-the-Loop Systems
Third-party solutions integrate Simulink® models with real-time systems for design and verification. Rapid prototyping
systems help engineers optimize designs by connecting models to actual devices or prototypes and running them in real
time. Hardware-in-the-loop (HIL) systems help them validate controllers by simulating the system without using physical
prototypes. Some third-party solutions provide real-time hardware for xPC Target™ for use across a range of industries.
Others address the specific demands of automotive and aerospace applications.
Speedgoat real-time target machines. Speedgoat specializes in real-time
testing solutions optimized for Simulink
and xPC Target. Products include hardware
for xPC Target Turnkey, a complete realtime testing solution that combines xPC
Target with high-performance real-time
target machines and I/O modules. Speedgoat target machines and I/O modules meet
a wide range of performance, I/O connectivity, form factor, and environmental requirements and support a broad spectrum
of applications and industries.
Speedgoat www.speedgoat.ch
ETAS® LABCAR. The LABCAR HIL system provides a virtual test environment for
automotive ECUs, enabling developers to
test their designs under realistic operating
36
MathWorks News&Notes | 2 0 1 1 – 2 0 1 2
and fault conditions and under improbable
or dangerous states. LABCAR is an open,
PC-based platform with integrated, modular
hardware options and extensible Simulink
models for vehicle dynamics and subsystems, including diesel and gasoline engines,
electric motors, transmissions, and brakes.
Integrated software components, including
an operator-centric view and calibration
tools, expand these capabilities.
ETAS www.etas.com
dSPACE® Simulator. dSPACE Simulator
is a modular HIL system that lets engineers test
automotive electronic control units (ECUs)
and software in a virtual environment without
using actual vehicles or prototypes. Engineers
can run their Simulink or SimDriveline™
models on the HIL system by generating code
using Simulink Coder™. dSPACE also offers integrated Automotive Simulation Models, specialized Simulink models for diesel engines,
gasoline engines, vehicle dynamics, and other
automotive applications. dSPACE offers a variety of modular hardware systems for HIL,
such as the dSPACE Full-Size and SCALEXIO
systems, as well as many I/O options.
dSPACE GmbH www.dspace.com
Concurrent Computer SIMulation
Workbench. SIMulation Workbench
(SimWB) is a framework for developing and
executing complex HIL simulations. SimWB
lets developers interactively configure, control, log, and play back simulation runs.
Simulink models and generated code can be
imported directly into SimWB. Model parameters can be extracted from the code and
updated in real time. SimWB runs on Concurrent iHawk™ COTS multicore platforms
running RedHawk™ Linux®. SimWB supports a wide range of COTS I/O boards for
popular industry protocols, such as ARINC
429, MIL-STD-1553, Flexray, and CANbus.
Concurrent Computer Corporation
real-time.ccur.com
Learn More
Third-Party Products and Services
mathworks.com/connections
Technical Tips and Demos
on Your Desktop
Live and recorded webinars in 19 languages
Explore more than 300 topics, including:
■■ System design and simulation
■■ Data acquisition
■■ Physical modeling
■■ Data analysis
■■ Discrete-event simulation
■■ Mathematical modeling
■■ Rapid prototyping
■■ Algorithm development
■■ Embedded code generation
■■ Parallel computing
■■ HDL code generation and verification
■■ Desktop and web deployment
■■ Verification, validation, and test
mathworks.com/webinars
mathworks.com
91936v00 10/11
Download