0% found this document useful (0 votes)
6 views472 pages

MATLAB and Simulink in Action Programming, Scientific Computing and Simulation

The document is a preface and introduction to the book 'MATLAB and Simulink in Action' by Xue Dingyü and Pan Feng, which focuses on programming, scientific computing, and simulation using MATLAB. It outlines the authors' extensive experience with MATLAB, their educational methodologies, and the structure of the book, which includes practical exercises and mini-projects to enhance learning. The book aims to provide a comprehensive resource for students and researchers in engineering and scientific disciplines to effectively utilize MATLAB for problem-solving.

Uploaded by

Soumitra Bhowmik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views472 pages

MATLAB and Simulink in Action Programming, Scientific Computing and Simulation

The document is a preface and introduction to the book 'MATLAB and Simulink in Action' by Xue Dingyü and Pan Feng, which focuses on programming, scientific computing, and simulation using MATLAB. It outlines the authors' extensive experience with MATLAB, their educational methodologies, and the structure of the book, which includes practical exercises and mini-projects to enhance learning. The book aims to provide a comprehensive resource for students and researchers in engineering and scientific disciplines to effectively utilize MATLAB for problem-solving.

Uploaded by

Soumitra Bhowmik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 472

Xue Dingyü

Pan Feng

MATLAB and
Simulink in Action
Programming, Scientific
Computing and Simulation
MATLAB and Simulink in Action
Xue Dingyü · Pan Feng

MATLAB
and Simulink
in Action
Programming, Scientific Computing and Simulation
Xue Dingyü   Pan Feng
College of Information Science and Information Science and Engineering
Engineering Northeastern University
Northeastern University Shenyang, Liaoning, China
Shenyang, Liaoning, China

ISBN 978-981-99-1175-2 ISBN 978-981-99-1176-9 (eBook)


https://doi.org/10.1007/978-981-99-1176-9

Translation from the Chinese Simplified language edition: “MATLAB/Simulink实用教程——编程、


计算与仿真” by Dingyü Xue and Feng Pan, © Tsinghua University Press 2022. Published by Tsinghua
University Press. All Rights Reserved.

© The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature Singapore
Pte Ltd. 2024

This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether
the whole or part of the material is concerned, specifically the rights of reprinting, reuse of illustrations,
recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or
information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar
methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Singapore Pte Ltd.
The registered company address is: 152 Beach Road, #21-01/04 Gateway East, Singapore 189721, Singapore

Paper in this product is recyclable.


V

This work is dedicated to:


My wife, Yang Jun,
and daughter, Xue Yang,
—Xue Dingyü

My wife, Wu Wei
daughter, Pan Feiyu, and son, Pan Pengyu
—Pan Feng

We thank them for their understanding, support and love.


Preface

MATLAB language is now a prominent professional computer language in aca-


demic world and a great amount of engineering disciplines. It is my opinion that if a
student in science and engineering discipline studies and masters such a mainstream
computer’s tool earlier, he will get tremendous benefits in other course studies and
after-class activities, and uses MATLAB to solve practical problems. For instance,
he may have a brand-new viewpoint in course studies, and explores practical prob-
lems actively, or even he may find creative solutions to many unsolved problems.
Based on my practical educational experience, I proposed a three-step method-
ology for scientific computing problems at the First MathWorks’ Asian Faculty and
Research Summit in Tokyo, in 2015. The first step is to understand in human lan-
guage what is the physical meaning of the mathematical problem to be solved; the
second one is to input the problem into a computer, in a language understanda-
ble by the computer; the third step is to call the appropriate solver or his own
code to find the solutions directly. With such a methodology in mind, the ordinary
researchers may solve the scientific computing problems easily, in a short period of
time, even if the problem belongs to a field that the user has never heard of. Signif-
icant amount of examples are provided in the book, and basically the problems are
solved with the three-step methodology.
I started using MATLAB in my research in my doctorate studies in Sussex Uni-
versity in 1988. I designed a MATLAB-based feedback control teaching-aid fron-
tend named Control Kit, which was used in the laboratories in Sussex University.
Later its revised version became a commercial software in Rapid Data Ltd, in Eng-
land. In 1993, when I took up a faculty post in Northeastern University in China,
I started introducing MATLAB into education, and published my first influential
book Computer-aided Control Systems Design: MATLAB and Applications in 1996
in Tsinghua University Press, which was one of the earliest MATLAB textbooks in
the world. The book was selected as one title in the National Elite Textbook Pro-
gram in China, and the course based on it was enrolled in the National Elite Course
Program and National Resources-sharing Course Program.
With the increasing popularizing acceptance of MATLAB in various scien-
tific and engineering disciplines, in 2002, I felt the need to initiate a new dedicated
course, not only teaching MATLAB programming, but also covering all the engi-
neering mathematics courses, based on the direct solutions with MATLAB. The
book Advanced Applied Mathematical Problem Solutions with MATLAB was pub-
lished in 2004 in Tsinghua University Press. The course was named one of the
National First-class Undergraduate Courses in 2020. English editions of the above
books were published in SIAM, CRC, Wiley and World Scientific publishers.
With 30 more years of teaching and research accumulations, I published a series
of six volumes Prof. Xue Dingyü’s Lecture Hall in Tsinghua University Press, and
the English editions were published later in de Gruyter. These books concentrated
on introducing MATLAB programming and Simulink modeling, aiming at solving
scientific computing problems in many branches of applied mathematics, such as
calculus, linear algebra, optimization and differential equations.
Preface
VII 
This book can be regarded as the concentrated version of the series, thanks to
the suggestions from Director Sheng Dongliang, Tsinghua University Press. The
development of this book experienced the evolution process from thin to thick, then
from thick back to thin. The evolution time lasts about 20 years, and the thickness
of the book is expanded from 500 pages to 1700 pages, then concentrated into this
400-page version. Balanced materials are prepared in the book on the three parts:
MATLAB programming, scientific computing and system simulation. The ­English
edition is mainly translated from the Chinese edition, while in certain places,
updates are made.
To the authors’ experience, in order to learn well a computer language such as
MATLAB, there is no other way to go, rather than adequate practice. Significant
number of exercises are provided in the book. One or two mini-projects are also
provided in each chapter for the readers to enhance their knowledge and capabili-
ties, by practicing with more challenging problems.
Based on the book, a full set of PPT files and other educational resources are
prepared. English version of the online video course of the National First-class
Undergraduate Course is also available on requests.
My sincere tribute goes to my supervisors, the late Prof. Ren Xingquan of
Northeastern University, China, and Prof. Derek Atherton of Sussex University,
England. It was they who introduced me into the paradise of system simulation and
MATLAB programming, and initiated my interesting and challenging academic
life. Tribute also goes to my senior colleague, the late Prof. Xu Xinhe, Northeastern
University, for his kindness help and specific guidance, which enabled me spending
large amount of time on course reforms and textbook development.
Special thanks go to Prof. Chen YangQuan of University of California, Merced
for nearly 30 years of sincere cooperation and meaningful discussions on enormous
number of topics. The contributions of my colleagues, former students and friends
are acknowledged. Some talks with them had become important materials in this
book. The support from MathWorks’ book program is also acknowledged.

Xue Dingyü
Shenyang, China
April 2023

The study guide of this textbook could be accessed via:7 http://sn.pub/thGR7v or


by scanning the QR code below. This website provides links to recorded teaching vid-
eos, MATLAB toolbox for the book, interactive slide decks files in Powerpoint doc-
uments, and solution manuals by the authors.
IX

Contents

I MATLAB Programming

1 Introduction to MATLAB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 Demonstrations on Scientific Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.1 Solutions of Scientific Computing Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.2 Limitations of Regular Computer Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Introduction to MATLAB Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.1 A Brief History of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.2 Advantages of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.3 Three-Step Solution Method in Scientific Computing Problems . . . . . . . . . . . . . . . . . . . 10
1.4 Outlines of the Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2 Essentials in MATLAB Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


2.1 Simple Manipulations of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.1 Main Interface of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.2 Working Folder of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.3 Online Help in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1.4 Display Format in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.1.5 Workspace and Management in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.1.6 Other Facilities in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.2 Data Types in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2.1 Reserved Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2.2 Variable Names and Naming Regulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.3 Double Precision Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2.4 Symbolic Data Type and Symbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.2.5 Generating Arbitrary Symbolic Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.2.6 Other Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.2.7 Data Types Recognition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.3 MATLAB Statement Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.3.1 Fundamental Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.3.2 Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.3.3 Colon Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.3.4 Submatrix Extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.3.5 Man–Machine Interactive Functions in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.4 Fundamental MATLAB Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.4.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.4.2 Transcendental Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.4.3 Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.4.4 Relational Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
X Contents

2.4.5 String Manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42


2.4.6 Processing Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.5 File Processing in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.5.1 Assessing MATLAB Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.5.2 File Read and Write Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.5.3 Assessing Microsoft Excel Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
2.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
2.7 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

3 MATLAB Flow Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53


3.1 Loop Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.1.1 For Loop Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.1.2 While Loop Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.1.3 Nesting Loop Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.1.4 Vectorized Programming and loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.2 Conditional Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2.1 Simple Conditional Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2.2 Ordinary Form of Conditional Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.2.3 Other Flow Control Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.2.4 Vectorized Computing of Piecewise Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.3 Switch Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.4 Trial Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
3.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
3.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

4 MATLAB Functions Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73


4.1 MATLAB Script Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.1.1 MATLAB Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.1.2 MATLAB Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.2 Fundamental Structures of MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.2.1 Why MATLAB Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.2.2 MATLAB Function Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
4.2.3 Naming Regulations of MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.2.4 Numbers of Input and Output Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.2.5 Input Arguments Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.2.6 Recursive Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.2.7 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.3 Variable Transfers in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.3.1 Extractions of Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
4.3.2 Local and Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
4.3.3 Accessing MATLAB Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4.4 Debugging in MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
4.4.1 MATLAB Function Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.4.2 Pseudocode Technique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
4.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
4.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Contents
XI 
5 MATLAB Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5.1 Simple Two-Dimensional Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.1.1 Data-based Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.1.2 Function Expression-based Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.1.3 Plots of Parametric Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
5.1.4 Plots with Two y Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.1.5 Graph Decorations and Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.1.6 Extracting Data from Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
5.2 Special Two-Dimensional Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
5.2.1 Polar Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
5.2.2 Representation of Discrete Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
5.2.3 Statistical Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.2.4 Filled Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
5.2.5 Logarithmic Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
5.2.6 Dynamic Trajectory and Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
5.2.7 Graphics Window Divisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
5.3 Three-Dimensional Plots in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
5.3.1 Three-Dimensional Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
5.3.2 Three-Dimensional Parametric Equation Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.3.3 Three-Dimensional Surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.3.4 Viewpoint Setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
5.3.5 Surface of Parametric Equations with Two Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
5.3.6 Three-Dimensional Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.4 Implicit Function Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
5.4.1 Two-Dimensional Implicit Function Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.4.2 Three-Dimensional Implicit Function Surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
5.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

6 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137


6.1 Essential Concepts in Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
6.2 Classes and Objects Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
6.2.1 Class Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
6.2.2 Input and Display of Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
6.2.3 Overload Functions for Addition and Subtraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
6.2.4 Overload Function of Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
6.2.5 Overload Function of Power Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
6.2.6 Overload Function for Like-Term Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
6.3 Interface Design of Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
6.3.1 User Interface Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
6.3.2 Simple Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
6.3.3 Programming and Applications of Standard Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . 149
6.3.4 App Designer Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
6.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
6.5 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
XII Contents

II Scientific Computing

7 Calculus and Integral Transforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161


7.1 Analytical Solution of Calculus Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
7.1.1 Limit of Univariate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
7.1.2 Limits of Multivariate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
7.1.3 Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
7.1.4 Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
7.2 Series Approximation of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
7.2.1 Taylor Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
7.2.2 Fourier Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
7.2.3 Series Sums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
7.2.4 Product of Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
7.2.5 Convergence of Infinite Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
7.3 Numerical Calculus Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
7.3.1 Numerical Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
7.3.2 Numerical Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
7.4 Introduction to Integral Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
7.4.1 Laplace Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
7.4.2 Numerical Laplace Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
7.4.3 Fourier Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
7.4.4 z Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
7.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

8 Linear Algebra and Matrix Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217


8.1 Special Matrices Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
8.1.1 Zeros, Ones and Identity Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
8.1.2 Random Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
8.1.3 Diagonal Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
8.1.4 Representation of Special Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
8.2 Matrix Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
8.2.1 Simple Analysis of Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
8.2.2 Inverse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
8.2.3 Moore–Penrose Generalized Inverses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
8.2.4 Eigenvalues and Eigenvectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
8.3 Matrix Transform and Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
8.3.1 Similarity Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
8.3.2 Companion Matrix Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
8.3.3 Transforming Matrices into Diagonal or Jordanian Ones . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
8.3.4 Triangular Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
8.3.5 Cholesky Factorization of Symmetrical Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
8.3.6 Singular Value Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
8.4 Matrix Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
8.4.1 Matrix Exponential Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
8.4.2 Matrix Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Contents
XIII 
8.4.3 Arbitrary Matrix Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
8.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
8.6 A Mini-Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

9 Algebraic Equation Solutions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249


9.1 Linear Algebraic Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
9.1.1 General Form of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
9.1.2 Numerical and Analytical Solutions of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
9.1.3 Infinite Solution Constructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
9.1.4 Least Squares Solutions of Conflict Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
9.1.5 XA = B Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
9.2 Solutions of Special Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
9.2.1 Kronecker Transform of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
9.2.2 AXB = C Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
9.2.3 Lyapunov Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
9.2.4 Sylvester Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
9.3 Solutions of Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
9.3.1 Graphical Solutions of Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
9.3.2 Quasi-Analytical Solutions of Polynomial-Type Equations . . . . . . . . . . . . . . . . . . . . . . . . . . 266
9.3.3 Quasi-Analytical Solutions of Quadratic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
9.3.4 Numerical Solutions of Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
9.3.5 Control Parameters in Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
9.4 Nonlinear Matrix Equations with Multiple Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
9.4.1 Ideas and Implementation of Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
9.4.2 Matrix Equation Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
9.4.3 Solutions of Pseudo-Polynomial Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
9.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
9.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

10 Ordinary Differential Equation Solutions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283


10.1 Analytical Solutions of ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
10.1.1 Linear ODEs with Constant Coefficients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
10.1.2 High-Order Linear ODE Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
10.1.3 Time-Varying Linear ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
10.1.4 Nonlinear ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
10.2 Initial Value ODE Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
10.2.1 Standard Form of First-Order Explicit ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
10.2.2 Direct Solutions of ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
10.2.3 Validation of ODE Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
10.2.4 ODE Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
10.2.5 Stiff ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
10.3 Special ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
10.3.1 Differential–Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
10.3.2 Implicit Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
10.3.3 Delay Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
10.4 Boundary Value Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
XIV Contents

10.4.1 Mathematical Forms of Boundary Value Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309


10.4.2 Solutions of BVPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
10.4.3 BVPs with Undetermined Coefficients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
10.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
10.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320

11 Optimization Problem Solutions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323


11.1 Unconstrained Optimization Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
11.1.1 Standard Form of Unconstrained Optimization Problems . . . . . . . . . . . . . . . . . . . . . . . . . . 324
11.1.2 Solutions of Unconstrained Optimization Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
11.1.3 Precision Control in Unconstrained Optimization Solutions . . . . . . . . . . . . . . . . . . . . . . . . 326
11.2 Linear and Quadratic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
11.2.1 Linear Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
11.2.2 Quadratic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
11.2.3 Problem-Based Description and Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
11.3 Nonlinear Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
11.3.1 Mathematical Form of Nonlinear Programming Problems . . . . . . . . . . . . . . . . . . . . . . . . . . 333
11.3.2 Direct Solutions of Nonlinear Programming Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
11.3.3 Local and Global Optimum Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
11.4 Attempting to Global Optimum Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
11.4.1 Introduction to MATLAB Global Optimization Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
11.4.2 A New Global Unconstrained Optimization Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
11.4.3 A New Global Constrained Optimization Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
11.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
11.6 Mini-Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352

12 Data Processing and Statistics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353


12.1 Data Interpolations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
12.1.1 One-Dimensional Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
12.1.2 Two- and Multidimensional Interpolations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
12.1.3 Spline Interpolations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
12.1.4 Spline-Based Numerical Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
12.2 Fitting Mathematical Models from Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
12.2.1 Polynomial Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
12.2.2 Least Squares Curve Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
12.2.3 Neural Network-Based Data Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
12.3 Statistical Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
12.3.1 Probability Density and Distribution Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
12.3.2 Pseudorandom Number Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
12.3.3 Mean and Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
12.3.4 Outlier Detections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
12.4 Hypothesis Tests and Variance Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
12.4.1 Hypothesis Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
12.4.2 Variance Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
12.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Contents
XV 
12.6 A Mini-Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384

III System Simulation

13 Modeling and Simulation with Simulink. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387


13.1 Simulink Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
13.1.1 Block Library and Blank Model Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
13.1.2 Simulink Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
13.2 Commonly Used Block Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
13.2.1 Input and Output Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
13.2.2 Continuous and Discrete Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
13.2.3 Computing Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
13.2.4 Examples in Simulink Modeling and Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
13.3 Simulink Parameters Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
13.3.1 Solver Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
13.3.2 Input and Output Parameter Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
13.3.3 Pre-processing of Model Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
13.4 Modeling and Solutions of ODEs with Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
13.4.1 Suggested Simulink Modeling Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
13.4.2 Low-Level Modeling Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
13.4.3 Vectorized Modeling Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
13.4.4 Standard Framework for ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
13.4.5 Modeling of ODE Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
13.4.6 Modeling of Implicit ODEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
13.4.7 Modeling of Delay Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
13.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
13.6 A Mini-Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

14 More on Simulink Modeling and Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421


14.1 Command-Line Methods in Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
14.1.1 Simulation Parameter Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
14.1.2 Invoke Simulation Process with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
14.1.3 Input and Output Data Structures in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
14.1.4 Parallel Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
14.2 Accurate and Fast Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
14.2.1 Zero-Crossing Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
14.2.2 Algebraic Loop Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
14.2.3 Fast Restart Mode in Simulink Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
14.3 Subsystems and Block Masking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
14.3.1 Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
14.3.2 Icon Design of Masked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
14.3.3 Block Masking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
14.4 S-Function Programming and Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
XVI Contents

14.4.1 State Space Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441


14.4.2 S-Function Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
14.4.3 S-Function Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
14.4.4 S-Function Response Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
14.4.5 S-Function Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
14.4.6 S-Function Block Masking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
14.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
14.6 A Mini-Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455

Supplementary Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454


MATLAB Functions Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
Subject Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
1 I

MATLAB Programming
3 1

Introduction to MATLAB
Contents

1.1 Demonstrations on Scientific Computing – 4


1.1.1 Solutions of Scientific Computing Problems – 4
1.1.2 Limitations of Regular Computer Languages – 6

1.2 Introduction to MATLAB Language – 8


1.2.1 A Brief History of MATLAB – 8
1.2.2 Advantages of MATLAB – 9

1.3 Three-Step Solution Method in Scientific Computing


Problems – 10
1.4 Outlines of the Book – 12

1.5 Exercises – 13

1.6 Mini-Projects – 15

References – 16

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_1
4 Chapter 1 · Introduction to MATLAB

Scientific computing problems are inevitable in scientific research. The researchers


1 usually build up mathematical models in their research, then by solving the mathemat-
ical models, the solutions of the problems can be found. Specific knowledge is needed
to build up mathematical models in certain areas. If the models are already estab-
lished, the methods presented in this book can be used to find analytical or numerical
solutions. A brief introduction on professional computer languages such as MAT-
LAB is presented first in this chapter, followed by the development of MATLAB.
In 7 Sect. 1.1, examples are used to show why professional computer languages
are used to tackle scientific computing problems, where manual methods are not
possible to find the solutions. Also, limitations of ordinary computer languages are
demonstrated with examples, where many trivial things must be considered, otherwise
it may contain potential bugs. In 7 Sect. 1.2, introduction to the development of
MATLAB language is illustrated. In 7 Sect. 1.3, the three-step method in the solutions
of scientific computing problems is presented. In 7 Sect. 1.4, the basic structure and
outlines of the book are presented.

1.1 Demonstrations on Scientific Computing


In the solution of scientific computing problems, manual formulation is of course
useful. Unfortunately, not all the problems can be solved manually. Computers should
be utilized to help the users to find the solutions. There are basically two categories
of computer solution methods. One is to use computer to implement well-established
numerical methods, based on the given numerical analysis algorithms, subroutines
in the software packages and program implementation of user’s own algorithms can
be created. The other one is to use dedicated professional computer languages to
solve the problems directly. These types of computer languages include MATLAB,
Mathematica [1], Maple [2] and so on. They are classified as computer math languages.

1.1.1 Solutions of Scientific Computing Problems


Before systematically introducing MATLAB programming and applications, several
illustrative examples are presented, indicating that the problems cannot be solved
in conventional methods, but can easily be solved by professional computer math
languages such as MATLAB.

 Example 1.1
Consider an “Olympic math” problem: What is the last digit in 20232023 ?
Solutions If computer tools are not adopted, the mathematicians can only get the last digit,
not anything else. In fact, such a solution is almost useless, since in daily life, people do
not care what the last digit is, if he spends some money to buy things. What he interests in
is how many digits, what is the first digit, or what is the number. These questions cannot
be answered in this problem, without the use of computers. With MATLAB, the exact
number is 1070707· · · 4567, and there are 6689 digits in all, which fills more than 2 pages
in the book.
1.1 · Demonstrations on Scientific Computing
5 1
>> a=sym(2023)^2023, vpa(a) % where 2023 is defined in symbolic form


 Example 1.2
Are you able to solve the equations?

 ⎨ x + 3y3 + 2z2 = 1/2
x + y = 35
x2 + 3y + z3 = 2
2x + 4y = 94, ⎩ 3
x + 2z + 2y2 = 2/4.

Solutions The first equation is the so-called chick−rabbit cage problem. The equation can
easily be solved without computers. If MATLAB is used, even if you do not know how to
solve the equation by hand, you can still solve it with the following statements:
>> syms x y; % declare symbolic variables
[x0,y0]=vpasolve(x+y==35,2*x+4*y==94) % solve equation
With high-standard computer languages such as MATLAB, the solutions of the second
equation are as simple as the chick−rabbit cage problem. Just describe the equations by
symbolic expressions, then call vpasolve() function to solve the equation directly. All the
27 solutions can be found. If the solutions are substituted back to the equations, the error
found is as small as 10−34 .
>> syms x y z; % describe the equations in symbolic expressions
f1(x,y,z)=x+3*y^3+2*z^2-1/2; f2(x,y,z)=x^2+3*y+z^3-2; % description
f3(x,y,z)=x^3+2*z+2*y^2-2/4; [x0,y0,z0]=vpasolve(f1,f2,f3) % solution
size(x0), norm([f1(x0,y0,z0) f2(x0,y0,z0) f3(x0,y0,z0)]) % validation
If computers and powerful tools are not available, the second equation cannot be
solved. 

 Example 1.3
In college mathematics, the concepts of differentiation and integral are presented. High-
order derivatives of functions are usually required in applications. If a function f (x) =
sin x/(x2 + 4x + 3) is known, how to find d4 f (x)/dx4 ?
Solutions The fourth-order derivative of the function can be derived manually, of course.
With the knowledge in mathematics, the first-order derivative df (t)/dx can be found first,
then, second-, third-order derivatives can be found. Finally, the fourth-order derivative can
be derived. By the repeated use of the formula, higher order derivatives can also be derived.
The process is much easier to implement on computers. With MATLAB, the problem can
be solved directly with a simple command.
>> syms x; f=sin(x)/(x^2+4*x+3); % describe the original function
y=diff(f,x,4) % use diff() function to find derivative
The result obtained is
6 Chapter 1 · Introduction to MATLAB

d4 f (t) sin x (2x + 4) cos x (2x + 4)2 sin x


1 dx4
=
x2 + 4x + 3
+ 4 
x2 + 4x + 3
 2
− 12
(x2 + 4x + 3)3
+

sin x (2x + 4)3 cos x (2x + 4) cos x


12 − 24 + 48 2 +
(x2 + 4x + 3)2 (x2 + 4x + 3)4 (x + 4x + 3)3
(2x + 4)4 sin x (2x + 4)2 sin x sin x
24 − 72 2 + 24 2 .
(x + 4x + 3)
2 5 (x + 4x + 3)4 (x + 4x + 3)3

It is obvious that even manual method can be used, the solution like this is too com-
plicated to get. A slight carelessness in the solution process may lead to erroneous results.
Therefore, computers should be adopted in solving these problems. It only takes about
three seconds to accurately find d100 f (x)/dx100 . 

 Example 1.4
Many branches in mathematics such as linear algebra, integral transforms, statistics and
numerical analysis are taught in universities. After examinations, if similar problems are
encountered in study and work, are you still able to solve the problems? In this book, a
brand-new solution pattern to the problems is illustrated. 

1.1.2 Limitations of Regular Computer Languages


Before systematically learning MATLAB, the readers may already have some knowl-
edge on other languages such as C or Fortran. Needless to say, that these computer
languages play important part in science and engineering. They were also the low-
level supporting language for MATLAB and similar languages. For scientists and
engineers, it is not adequate to solve mathematical computing and simulation prob-
lems merely with languages such as C. C language cannot be used to derive formulas,
or find analytical solutions, only numerical programs can be written. On the other
hand, numerical methods in the textbooks are not always good choice in solve sci-
entific computing problems. Besides, apart from the above limitations, if low-level
programming languages are used, the program thus written may be too long to vali-
date. Even though the results are found, sometimes they are not trust worthy, and the
solutions may not be reliable. In this section, two examples are posed to demonstrate
the limitations in C programming languages.

 Example 1.5
In 1205, Italian mathematician Leonardo Fibonacci posed a mathematical problem. “A
man puts a pair of rabbits in a place surrounded on all sides by a wall. How many pairs of
rabbits can be produced from that pair in a year if it is supposed that every month each pair
begets a new pair which from the second month on becomes productive?” [3]. This problem
is later referred to as Fibonacci sequence. The first two elements are a1 = a2 = 1, and the
subsequent terms can be evaluated recursively from ak = ak−1 + ak−2 , k = 3, 4, · · · . Use
computer to find the total pairs of rabbits 10 years later, that is, the 120th term.
Solutions In C language programming, before using variables, the data type must be
assigned first. Since the entities in this example are integers, it is natural to select int
and long for the entities. Here int is selected. The following C program can be written:
1.1 · Demonstrations on Scientific Computing
7 1
main()
{ int a1, a2, a3, i;
a1=1; a2=1; printf("%d %d ",a1,a2);
for(i=3; i<=120; i++){a3=a1+a2; printf("%d ",a3); a1=a2; a2=a3;
}}
With a few statements above, it seems that the problem is solved. Unfortunately, there
is a bug in the problem. In the execution of the code, negative terms are displayed after
24 terms. Later on, sometimes the terms are negative, some are positive. It is obvious that
the program is wrong. What is the problem? It is known that the range of int integer type
is (−32767, 32767). If the term is beyond that range, wrong results are generated. Even
though long integer type can be adopted, it may only last 10 more terms, the negative
terms appear again. It can be seen that with C language, if some details are not carefully
considered, erroneous results may be found.
It is not necessary to consider these trivial things if MATLAB is adopted. With the
following commands, the first 120 terms can be found.
>> a=[1 1]; for i=3:120, a(i)=a(i-1)+a(i-2); end; a(end)
In fact, there are also problems in the above program, since the default double data
type only preserves 15 effective digits, if the number has more digits, some digits are
neglected, which leads to imprecise results. With symbolic data type in MATLAB, only
change the first statement to a =sym([1,1]), the exact value of a120 can be found, which
is 5358359254990966640871840. The result cannot be found under double precision frame-
work using any numerical algorithm. If the weight of each pair of rabbits is 1 kilogram, the
total weight is close to the mass of the earth! 

 Example 1.6
Write a universal C program to multiply two matrices A and B.
Solutions If A is an n × p matrix, and B is a p × m matrix. It is known in linear algebra
that C matrix can be found, whose elements are

p

cij = aik bkj , i = 1, · · · , n, j = 1, · · · , m.
k=1

Based on the above algorithm, the following C program can be written, whose kernel
part is implemented in a triple loop structure.
for (i=0: i<n; i++){ for (j=0; j<m; j++){
c[i][j]=0; for (k=0; k<p; k++) c[i][j]+=a[i][k]*b[k][j];
}}
It seems that the universal matrix product program can be implemented in this way,
but wait, there is a deadly bug. The conditions whether the two matrices can be multiplied
together are NOT at all considered in the code. Normally when two matrices can be mul-
tiplied together, the number of columns in A matrix should be the same as the number of
rows in matrix B. It is natural to add the following judgement statement:
if column number of A does not equal row number of B, display error message
In fact, the newly added statement introduces a new bug, since if one of A or B is a
scalar, A and B can be multiplied unconditionally. However, the newly added if statement
8 Chapter 1 · Introduction to MATLAB

produces an error message. Other if statements should be added to test scalar cases for A
1 or B matrices, and add corresponding processing statements.
Even though all the above bugs are fixed, this is still not a universal one, since com-
plex matrices cannot be handled. Much more statements should be introduced to process
complex matrix cases.
It can be seen from the example that the user must be very careful with languages such as
C, otherwise there might be bugs, and even yields misleading results. If MATLAB is used,
there is no need to consider this type of trivial things, since the product of matrices A and
B can be found with C = A ∗ B directly. If it is does not yield a result, an error message
is given to explain why they cannot be multiplied. 

It can be seen from the above examples that, low-level programming languages
may have potential bugs in solving scientific computing problems. Therefore, simpler
and more reliable dedicated computer languages such as MATLAB should be adopted
in scientific research, since the researcher can be freed from trivial things, so as to
master better to problems to be solved, and avoid knowledge bias. This is of course
the most widely accepted methodology for the researchers.

1.2 Introduction to MATLAB Language


MATLAB language is the most widely used computer languages in scientific com-
puting, automatic control and system simulation. The development of MATLAB is
introduced here in this section, followed by the introduction to the advantages of
MATLAB.

1.2.1 A Brief History of MATLAB


In the earlier days before computer math languages such as MATLAB appeared, sci-
entific computing problems were mainly solved using Fortran language and dedicated
mathematics software packages. The leading software packages include EISPACK
[4, 5], LINPACK [6], NAG [7] and so on. In 1978, Prof. Cleve Moler, the Chair-
man of the Department of Computer Science, the University of New Mexico, found
that the use of the then most advanced EISPACK and LINPACK packages is rather
complicated. He conceived and developed an interactive language, and he named it
MATLAB (for matrix laboratory) [8].
A control engineer Jack Little and Moler co-founded a company MathWorks in
1984, concentrating on the development of MATLAB. The commercial MATLAB
made its first debut on the IEEE Conference on Decision and Control in December
1984. By that time, numerical computation facilities were badly needed in the state
space control theory. It soon attracted the attention of scholars and engineers in the
control community. Various control-oriented toolboxes appeared. MATLAB had
huge impact among control scientists and engineers, very soon it becomes de facto
the standard computer language in the control community worldwide. With various
demands in control and related areas, MATLAB language made huge sustainable
progress and the facilities are made stronger and stronger. It can be said that, MAT-
1.2 · Introduction to MATLAB Language
9 1
LAB is a language developed and advocated by a mathematician, but made popular
among the researchers and engineers in control community.
Nowadays, MATLAB has become the top-selected computer languages in many
fields in science and engineering. There are many milestones in its 30 more years of
development. In 1990, block diagram-based simulation environment Simulink was
released. In 1992, MATLAB 4.0 was released, fully support Microsoft Windows
interface programming; MATLAB 5.0 was released in 1996, where more data types
such as cells, structured data and class are supported. In 2004, MATLAB 7.0 was
released, where multi-domain physical modeling and simulation schemes are sup-
ported. In 2012, MATLAB 8.0 was released, where App programming and support
are supported. In 2016, MATLAB 9.0 was released, with live editor and other useful
facilities are supported. With the evolution of MATLAB, the programming environ-
ment and programming facilities are significantly improved, and the covering fields
are wider and wider. Nowadays, MATLAB releases two versions each year, with ver-
sion a in March and version b in September. The most recent one is version 2023b,
alternatively version 23.2.

1.2.2 Advantages of MATLAB


MATLAB language can be regarded as a universal programming language. Com-
pared with other computer languages, MATLAB has the following advantages:
(1) Concise and efficiency. MATLAB language is a highly integrated language.
The statements are concise. It comes with powerful built-in facilities, such that tens
or hundreds lines of source code in ordinary C or Fortran can be solved with a couple
of lines in MATLAB. It is highly reliable and easy to maintain. The efficiency in
solving scientific problems is significantly promoted.
(2) Facilities in scientific computing. Complex matrices are used as the basic units
in MATLAB, such that matrix computation is straightforward. Besides, it has pow-
erful facilities in solving directly optimization, calculus, differential equations, data
processing, statistics problems directly with dedicated solvers. Symbolic framework
is also supported in MATLAB, such that formula derivation and analytical solutions
in mathematical problems can be made easily.
(3) Graphical facilities. With the simple and straightforward graphical facilities
supported in MATLAB, and experimental and simulation data can be displayed
in various forms, such as curves and surfaces. The curves and surfaces of various
implicit functions can be made easily. Graphical user interfaces and Apps can also be
programmed easily in MATLAB, from which universal tools are easily developed.
(4) Toolboxes and blocksets. In almost all fields in applied mathematics and control
engineering fields, there are dedicated toolboxes and blocksets. These tools are usually
developed by the well-known scholars with high reputation in the relevant fields. The
results from the tools are reliable and trust worthy. With the rapid popularity and
progress of MATLAB, more and more toolboxes appear in many other engineering
fields, which promotes the application of MATLAB in many different fields.
(5) Dynamical simulation facilities. Block diagram-based modeling and simulation
facilities are supported in Simulink. Complicated system models can easily be estab-
10 Chapter 1 · Introduction to MATLAB

lished and accurate simulation results can be found. The physical modeling facilities
1 in Simulink allow the user to build simulation model of electrical, mechanical and
control components under the same framework.

1.3 Three-Step Solution Method in Scientific Computing Problems


The three-step solution method for scientific computing was proposed and advocated
by the author [9]. The three steps are what, how and solve. In the “what” step, concen-
tration is made on linguistic description of the mathematical problem and its physical
interpretation. Even though the user has no knowledge on the mathematics branch,
the physical interpretation of the problem can be roughly understood. In the “how”
step, the user needs to know to describe the whole problem in MATLAB. In the
“solve” step, the user needs to know which solver to use to find the solution directly.
If there is no existing solver, the user needs to write a universal solver to the problem.
Two practical examples are used to illustrate the three-step method in scientific
computing problems. In the first one, a solution to a linear programming problem is
demonstrated, and in the latter one, artificial neural network is used in fitting samples.

 Example 1.7
Solve the following linear programming problem using the three-step method.

min

−2x1 − x2 − 4x3 − 3x4 − x5 .
⎨ 2x2 +x3 +4x4 +2x5 54
x s.t. 3x1 +4x2 +5x3 −x4 −x5 62

x1 ,x2 0, x3 3.32, x4 0.678, x5 2.57

Solutions Some readers may have not yet learnt optimization-related courses. But do not
worry. Even though you have not learnt any related theory, you can still use the three-step
method to find the solution of the problem.
(1) What. In this step, the physical meaning of the mathematical expression should be
understood first. In this particular problem, the problem can be understood as follows.
Under the simultaneous inequality constraints

⎨ 2x2 + x3 + 4x4 + 2x5  54
3x + 4x2 + 5x3 − x4 − x5  62
⎩ 1
x1 , x2  0, x3  3.32, x4  0.678, x5  2.57,

how to find a set of decision variables xi such that the value of the objective function
f (x) = −2x1 − x2 − 4x3 − 3x4 − x5 is minimized. Therefore, even though the reader has no
knowledge on optimization, the meaning of the mathematical formula can be understood.
(2) How. The user should learn how to use MATLAB to describe the mathematical
problem. After a few minutes of learning on linear programming solutions, the following
commands describe the entire problem in a variable P:
1.3 · Three-Step Solution Method in Scientific Computing Problems
11 1
>> clear; P.f=[-2 -1 -4 -3 -1]; % objective function
P.Aineq=[0 2 1 4 2; 3 4 5 -1 -1]; P.Bineq=[54 62]; % constraints
P.solver='linprog'; P.lb=[0;0;3.32;0.678;2.57]; % lower bound
P.options=optimset; % describe the entire linear programming problem with P

(3) Solve. Call the linear programming solver linprog() to solve directly the problem.
The solution of the problem can be obtained as x1 = 19.785, x2 = 0, x3 = 3.32, x4 = 11.385
and x5 = 2.57.
>> x=linprog(P) % call linprog() function to solve math problem


 Example 1.8
Artificial neural networks are the widely used intelligent mathematical tools in recent years.
They are useful in areas such as data fitting and pattern classifications. Assume that the
following commands generate a set of sample points.
>> x=0:0.1:pi; y=exp(-x).*sin(2*x+2);
Use these points to set up an artificial neural network, and draw the curve of the function.
Solutions If the user does not want to spend a lot of time learning systematic knowledge
on artificial neural networks, only wants to use neural network to solve the data fitting
problem, then considers using the three-step method here. After a few minutes of learning
on the essentials and use of neural network, the user can use neural network to solve the
data fitting problem. Let us go back to the three steps:
(1) What is an artificial neural network? In fact, it is not necessary to learn the technical
details of neural network, the user can just understand neural network as an information
processing unit, with adjustable parameters. It accepts several channels of inputs, processes
them to yield the outputs.
(2) How to set up neural network model? With fitnet() function, a blank neural network
model with 5 nodes can be set up. The sample points in the example can be used in training
the model, with train() function, that is, to adjust the internal parameters in the model
so as to better fit the samples. The following commands can be used to set up the expected
artificial neural network model, as shown in . Fig. 1.1.
>> net=fitnet(5); net=train(net,x,y), view(net)
(3) Solve curve fitting problem. With the neural network model net, the fitting results
can be obtained as shown in . Fig. 1.2, where the theoretical curve is also drawn.

. Fig. 1.1 Artificial neural network structure


12 Chapter 1 · Introduction to MATLAB

1 1

0.8

0.6

0.4

0.2

-0.2

-0.4
0 0.5 1 1.5 2 2.5 3

. Fig. 1.2 Data fitting results using artificial neural network model

>> t0=0:0.01:pi; y1=net(t0); y0=exp(-t0).*sin(2*t0+2);


plot(t0,y0,t0,y1,'--',x,y,'o') % compare theoretical and fitting curves
It can be seen that even neural network knowledge is not systematically learnt, we can
still solve practical problems with artificial neural networks. The structures and parameters
in the model can be adjusted, for instance, with different number of nodes, so as to better
observe fitting qualities. 

1.4 Outlines of the Book


The book is composed of three parts. In the first part, introductory knowledge on
MATLAB programming is provided. In the second part, concentrations are made
on solving various scientific computing problems with MATLAB, and finally in the
third part, introductions are made on Simulink-based system modeling and simulation
methods.
In the first part, MATLAB programming is presented, which establishes a foun-
dation for MATLAB applications. In 7 Chap. 1, the development and advantages of
MATLAB are briefly presented, followed by the introduction and demonstration of
the three-step method in scientific programming problems. In 7 Chap. 2, fundamental
knowledge on MATLAB programming is presented, including basic data structures
and statement structures, fundamental operations and file manipulations in MAT-
LAB. In 7 Chap. 3, flow control structures, including loops, conditional structures,
switch structures and trial structures, are addressed. The idea and implementation
of vectorized programming are also illustrated. In 7 Chap. 4, the mainstream MAT-
LAB programming-style—MATLAB functions are presented, and the use of the edi-
tors is also illustrated. In 7 Chap. 5, graphical facilities in MATLAB are addressed,
including data-based and mathematical expression-based two-dimensional and three-
dimensional graphics. Also, the graphical representation of implicit functions with
two or three independent variables is demonstrated. In 7 Chap. 6, object-oriented
programming techniques are presented, including the generation and programming
for classes, and also the design of Apps with graphical user interfaces.
1.5 · Exercises
13 1
In the second part, the application in scientific computing with MATLAB is pre-
sented. In-depth computer-based solutions to typical problems in various mathemat-
ics branches are presented. In 7 Chap. 7, the analytical solutions of calculus problems
are addressed, including limits, derivatives, integrals and series expansion problems.
Numerical differentiation and integrals are also addressed. The solutions of integral
transform problems are also demonstrated. In 7 Chap. 8, computer solutions of linear
algebra problems are illustrated, including matrix analysis, decomposition and trans-
formation problems, as well as matrix functions computing. In 7 Chap. 9, various
algebraic equation solution problems are presented, including linear and nonlinear
equation solutions, and also solutions of matrix equations with multiple solutions.
In 7 Chap. 10, differential equations are studied, including the analytical solutions
of linear differential equations, numerical solutions of differential equations with ini-
tial and boundary values. In 7 Chap. 11, optimization problems are studied with
MATLAB solutions, including unconstrained and constrained optimization prob-
lems. Intelligent optimization solutions are demonstrated. In particular, attempts are
made on finding global optimum solutions. In 7 Chap. 12, data interpolation and
function approximation problems are studied, and statistical methods are demon-
strated, such as hypothesis tests and variance analysis.
In the third part, modeling and simulation with Simulink are illustrated, so as to
establish the foundations for system simulation solutions. In 7 Chap. 13, fundamen-
tal knowledge on Simulink modeling and simulation is proposed, including a brief
introduction to the commonly used blocks, model parameter setting methods and
so on. Also, Simulink modeling methods for various differential equations are intro-
duced. In 7 Chap. 14, advanced knowledge on Simulink modeling and simulation is
presented, including the professional topics on fast restart mode, command-driven
simulation methods, subsystems and system masking and S-function programming.
It looks that significant number of mathematical formulas is included in this book,
and it looks rather deep in mathematics sense. But do not worry if you are uncertain
about your own background in mathematics. Do not be scared about the formulas.
The target of this book is not talking about low-level details on mathematics, but
to help the reader to bypass mathematics, and find the solutions of the mathematics
problems, with the help of computers, such as using MATLAB. After learning the
book, with the proper use of computer tools, the expected actual mathematical mod-
eling and solution capabilities of the reader may well exceed first class mathematicians
who do not use computers or are not good at using computers.
There is no shortcut to travel in learning MATLAB. The essential step in using
MATLAB is by practice. Only with the extensive use of MATLAB, the programming
skills and application levels may be promoted.
To learn further systematically a particular topic in this book, it is advised to refer
to References [10−16].

1.5 Exercises
(1) The derivative command is used in Example 1.3. Use MATLAB to compute
100th-order derivative to the function, and observe the result and time elapse.
(2) Can you guess what is the meaning of the command a(end) in Example 1.5?
14 Chapter 1 · Introduction to MATLAB

(3) Compute from Fibonacci sequence that after 13 years, how many pairs of rab-
1 bits are in total. Assume that the average weight of a pair of rabbits is 1 kilogram.
Find the total weight of all the rabbits, and compare it with the mass of the Sun,
which is 1.989×1030 kilograms. Compute then after 20 years, how many pairs
of rabbits are there?
(4) Compare the value of π (MATLAB constant pi) and the following continued
fraction.
1
3+ .
1
7+
1
15 +
1
1+
292
(5) Solve the algebraic equation, and validate the results.

⎪ 1 2 3 2 5 3

⎨ x +x+ + + 2 + 3 =0
2 2 y 2y x

⎪ y 3 1
⎩ + + + 5y4 = 0.
2 2x x4

(6) Find the second-order derivative of the following function:

sin x 1 x π
f (x) = 2
+ ln tan + .
cos x 2 2 4

(7) Function int() provided in MATLAB computes indefinite integrals, and the
syntax is similar to the function diff(). For the result in Example 1.3, call
function int() four times and see whether the function f (x) in Example 1.3
can be restored.
For an implicit equation x2 e−xy /2 +e−x/2 sin xy = 0, can you draw the curves
2
(8)
inside the −2π ≤ x, y ≤ 2π region? If other languages are adopted, do you
have any idea how to draw the curves for the implicit function? Function
fimplicit() is provided in MATLAB to draw directly curves of implicit func-
tions. Run the following statements on your computer and observe the result.
Can you guess what is the action of the following code?

>> syms x y;
f1=x^2*exp(-x*y^2/2)+exp(-x/2)*sin(x*y);
f2=y^2*cos(y+x^2)+x^2*exp(x+y);
fimplicit([f1,f2],[-2*pi,2*pi])
1.6 · Mini-Projects
15 1
1.6 Mini-Projects

1. Algebraic Equation Solutions


It can be seen that even though you have not yet learnt much MATLAB, you can
follow the examples and solve directly the following complicated equations, which
are almost impossible to solve otherwise. Substituting the solutions you found back
to the original equations, and find out what are the errors.
⎧ ⎧
⎨ 24xy − x2 − y2 − x2 y2 = 13 ⎨ x + 3y3 + 2z2 = 1/2
(1) 24xz − x − z − x z = 13
2 2 2 2 (2) x2 + 3y + z3 = 2
⎩ ⎩ 3
24yz − y − z − y z = 13,
2 2 2 2 x + 2z + 2y2 = 2/4,
⎧ 2 2
⎨ x y − zxy − 4x2 yz2 = xz2
(3) xy3 − 2yz2 = 3x3 z2 + 4xzy2

y x − 7xy2 + 3xz2 = x4 zy.
2

2. Calculus Problem Solutions


To solve calculus problems, sometimes, the skills and tactics from the users are
required. When the user wants to build up strong capabilities in solving calculus prob-
lems, repeated training on solving working problems is usually a must. The problems
in the famous work book by Demidovich [17] are good choices. In fact, if you have
been demonstrated and equipped with the solvers such as diff() and int(), skills
are no longer necessary. Follow the previous examples and find out the solutions of
the following problems:

(1) y(x) = x sin x 1 − ex , find y (x),

e−x arcsin e−x


2 2
1  2
(2) y(x) = + ln 1 − e−2x , find y (x),
2
1 − e−2x
2

 
3x2 + a sin2 x − 4 sin x cos x + 3 cos2 x
(3) I1 (x) = −  2 dx, (4) dx,
x2 x2 + a sin x + cos x
 7/10  4/5  9/10  1  11/10
(5) 6 − x2 − y2 − z2 − w2 − u2 dwdudzdydx.
0 0 0 0 0
Get online help information on the solvers limit() and symsum(), and follow
the examples to find directly the solutions of the following problems:
⎡ ⎤
1 1
(1) lim (3x + 9x )1/x , (2) lim ⎣  − ⎦,
x→∞ x→0 ln x + 1 + x2 ln(1 + x)
     
1 1 1 1 1 1
(3) + + + 2 + ··· + + n + ···.
2 3 22 3 2n 3
16 Chapter 1 · Introduction to MATLAB

References
1 1. Wolfram S (2003) The Mathematica book[M], 5th edn. Wolfram Media, Champaign
2. Monagan MB, Geddes KO, Heal KM et al (2007) Maple 11 advanced programming guide[M], 2nd
edn. Maplesoft, Waterloo
3. Molor CB (2013) Experiment with MATLAB[M]. BUAA Press, Beijing
4. Garbow BS, Boyle JM, Dongarra JJ et al (1977) Matrix eigensystem routines—EISPACK guide
extension[M]. Springer-Verlag, New York
5. Smith BT, Boyle JM, Dongarra JJ et al (1976) Matrix eigensystem routines—EISPACK guide[M],
2nd edn. Springer-Verlag, New York
6. Dongarra JJ, Bunsh JR, Molor CB (1979) LINPACK user’s guide[M]. Society of Industrial and
Applied Mathematics, Philadelphia
7. Numerical Algorithm Group (1982) NAG FORTRAN library manual[EB/OL]. 7 https://www.nag.
co.uk/nag-fortran-library
8. Moler CB (1980) MATLAB—an interactive matrix laboratory[R]. University of New Mexico
9. Xue DY (2014) Mathematics education made more practical with MATLAB[C]. Presentation at the
First MathWorks Asian Research Faculty Summit, Tokyo
10. Xue DY, Chen YQ (2016) Scientific computing with MATLAB[M], 2nd edn. CRC Press, Boca Raton
11. Xue DY (2020) MATLAB programming—Mathematical problem solutions[M]. De Gruyter, Berlin
12. Xue DY (2020) Calculus problem solutions with MATLAB[M]. De Gruyter, Berlin
13. Xue DY (2020) Linear algebra and matrix computations with MATLAB[M]. De Gruyter, Berlin
14. Xue DY (2020) Solving optimization problems with MATLAB[M]. De Gruyter, Berlin
15. Xue DY (2020) Differential equation solutions with MATLAB[M]. De Gruyter, Berlin
16. Xue DY (2022) Modeling and simulation with Simulink[M]. De Gruyter, Berlin
17. Demidovich BP (1970) Problems in mathematical analysis[M]. MIR Publishers, Moscow
17 2

Essentials in MATLAB
Programming
Contents

2.1 Simple Manipulations of MATLAB – 19


2.1.1 Main Interface of MATLAB – 19
2.1.2 Working Folder of MATLAB – 21
2.1.3 Online Help in MATLAB – 21
2.1.4 Display Format in MATLAB – 22
2.1.5 Workspace and Management in MATLAB – 23
2.1.6 Other Facilities in MATLAB – 24

2.2 Data Types in MATLAB – 25


2.2.1 Reserved Constants – 25
2.2.2 Variable Names and Naming Regulations – 26
2.2.3 Double Precision Data Type – 27
2.2.4 Symbolic Data Type and Symbolic Functions – 28
2.2.5 Generating Arbitrary Symbolic Matrices – 30
2.2.6 Other Data Types – 31
2.2.7 Data Types Recognition – 32

2.3 MATLAB Statement Structures – 32


2.3.1 Fundamental Assignment Statements – 32
2.3.2 Function Calls – 33
2.3.3 Colon Expressions – 33
2.3.4 Submatrix Extraction – 34
2.3.5 Man–Machine Interactive Functions in MATLAB – 35

2.4 Fundamental MATLAB Operations – 35


2.4.1 Arithmetic Operations – 36
2.4.2 Transcendental Functions – 39
2.4.3 Logical Operations – 42
2.4.4 Relational Operations – 42
2.4.5 String Manipulations – 42

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_2
2.4.6 Processing Symbolic Expressions – 45

2.5 File Processing in MATLAB – 47


2.5.1 Assessing MATLAB Workspace Variables – 47
2.5.2 File Read and Write Functions – 48
2.5.3 Assessing Microsoft Excel Files – 49

2.6 Exercises – 50
2.7 Mini-Projects – 51

Reference – 52
2.1 · Simple Manipulations of MATLAB
19 2
MATLAB language is the top-selected computer language in the academic world
in automatic control community worldwide. It is also the most suitable computer
language for many science and engineering disciplines. In this book, MATLAB is
the major computer language used extensively. With the help of MATLAB, scientific
computing and simulation problems are studied systematically and thoroughly. Mas-
tering such a high-standard language, it may be helpful for the readers to understand
and explore creatively scientific computing and simulation problems, so as to boost
the capabilities in solving such problems. Also, it may be helpful in learning other
courses.
In 7 Sect. 2.1, simple manipulations in the MATLAB environment are illustrated,
and necessary introductions to MATLAB interface and setting are addressed. In
7 Sect. 2.2, concentrations are made on presenting two data types—double preci-
sion and symbolic, which are extensively used in scientific computing and simulation.
Other data types are briefly introduced. The input format of different matrices is
also introduced. In 7 Sect. 2.3, basic statement structures in MATLAB are illus-
trated. Colon expressions and submatrix extraction techniques are also presented. In
7 Sect. 2.4, algebraic, logic and relationship operations are introduced, and string
computation and symbolic expression computing are also illustrated. In 7 Sect. 2.5,
file read and write facilities are illustrated, and the information exchange between
MATLAB and Microsoft Excel is presented.

2.1 Simple Manipulations of MATLAB


Compared with many computer languages, the use of MATLAB is relatively simpler.
Most facilities can be called directly in MATLAB functions and commands, which
are quite independent to MATLAB interface operations. In this section, MATLAB
interface operations are briefly introduced.

2.1.1 Main Interface of MATLAB


When MATLAB is installed properly, there is an icon for MATLAB on the desk-
top. Double click such an icon, default MATLAB interface is launched, as shown
in . Fig. 2.1. The upper part of the windows there is the MATLAB toolbar. There
are four different windows in the MATLAB window, labeled, respectively, Current
Folder, Details, Workspace and Command Window, where the latter one is essential.
All the other three zones can be closed, if necessary. There is a mark >> in the Com-
mand Window. It is the MATLAB prompt. All the MATLAB commands should be
issued under such a prompt.
Current Folder window displays all the files in the current folder. If one of them
is selected, the information about the file is displayed in the Details window. The
Workspace window on the right displays all the variable names in the MATLAB
workspace. In the Name column, the variable names are listed, while in the Values
column, the variable values are displayed.
The left portion of the toolbar in MATLAB command window is shown in
. Fig. 2.2a, and the right portion is shown in 2.2b. It can be seen that there are
20 Chapter 2 · Essentials in MATLAB Programming

. Fig. 2.1 MATLAB main window

(a) the left portion

(b) the right portion

. Fig. 2.2 MATLAB toolbar

six zones labeled at bottom, respectively, FILE, VARIABLE, CODE, SIMULINK, ENVIRON-
MENT and RESOURCES. In the FILE and VARIABLE zones, several icons are provided.
The actions of these buttons are quite straightforward, they are not further presented
here. In fact, apart from button operations, all these actions can be implemented with
MATLAB functions.
In the CODE partition, a series of buttons related to code are provided. If Analyze
Code button is pressed, the functions in the current folder are analyzed automatically,
to check whether there are errors or modification recommendations to the files. Click
the Clear Commands button, all the commands in the current command window are
cleared. The action is the same as the clc command. Run and Time button allows to
2.1 · Simple Manipulations of MATLAB
21 2
make profiling to the MATLAB code. The action indicates automatically which part
in the code is time-consuming, and prompt the user to further modify the code, so as
to increase the code efficiency. Its action is the same as profile command.
In the SIMULINK zone, the Simulink button is provided, and it launches Simulink
environment, and start system modeling and simulation. Details on this topic are fully
covered in 7 Chaps. 13 and 7 14.
Some useful facilities are provided in the ENVIRONMENT and RESOURCES zones.
The relevant buttons will be illustrated later when necessary.

2.1.2 Working Folder of MATLAB


When MATLAB is normally installed, the default working folder is bin folder under
MATLAB root folder, which is a read-only one, and not easy to store user files.
Therefore, it is recommended to use MATLAB folder under Documents as the working
folder. The specific operation is that, click the Preferences button in the toolbar. In
the opened dialog box, select the General item from the list on the left, the dialog box
in . Fig. 2.3 sets the working folder.
An alternative effective method is to create a file startup.m, whose listing is given
below. Move this file to the bin folder under MATLAB. Every time when MATLAB
is launched, this file is executed automatically to set the working folder.
cd('c:\Users\xuedi\Documents\MATLAB') % set your path accordingly
In order to use direct MATLAB functions under different folders, the folder must
be set under MATLAB search path. The setting method is click the Set Path button in
the ENVIRONMENT zone, the path-setting dialog box shown in . Fig. 2.4 is displayed.
The user can insert or remove paths as needed. Click Add Folder button, an individual
folder can be added to the search path. If Add with subfolders button is clicked, all the
subfolders under the selected one are added to the MATLAB search path. If the user
has downloaded a new third-party toolbox, the folders can be added to MATLAB
search path in an appropriate method, such that the functions in the toolbox can be
visited directly. Command pathtool can also be used to open the dialog box shown
in . Fig. 2.4.

2.1.3 Online Help in MATLAB


Powerful online help system is provided in MATLAB. The Help button in the toolbar
can be clicked to visit online help facilities.

. Fig. 2.3 Working path setting dialog box


22 Chapter 2 · Essentials in MATLAB Programming

. Fig. 2.4 MATLAB search path-setting dialog box

It is recommended in this book to use help function name command to visit


directly the help information of the specified functions. If the function name is
unknown, and we want to search a MATLAB function containing a certain key-
word, command lookfor keyword starts the searching process. The which function
name command finds the path of a certain function. Under default setting, the com-
mand stops when a matched function is found. If there are several files with the same
name, command which -all function name can be used to list the locations of all
the functions.

2.1.4 Display Format in MATLAB


Under default settings, the display format in MATLAB is set to short, meaning to
have 4 digits after the decimal point. To display more digits, the long format can be
chosen, meaning to have 15 digits after the decimal point. The command to set such a
display is format long. To restore the default display, format short command can
be used. Apart from these two display formats, other formats supported in MATLAB
are shown in . Table 2.1. It is worth mentioning that format command does not alter
the computing results, it only alters the display format. Normally the users may choose
his own format.

 Example 2.1
If the radius of a circle is r = 5, compute its perimeter and area, and find their rational
approximations.
Solutions The following commands compute the perimeter and area of the circle. If long
format is chosen, display the results. Here pi is a reserved constant in MATLAB, storing
the value of π. % is used to lead the comments, explaining the commands, but not executed.
2.1 · Simple Manipulations of MATLAB
23 2

. Table 2.1 Commonly used display formats in MATLAB

Formats Descriptions

loose Loose format, with an extra blank line before and after display

compact Compact format, no extra lines displayed

rat Display for variables in rational format approximately

long e Use scientific notation for numbers. Apart from 15 effective digits, it has also 3 digits
for exponentials. Similarly short e format is supported, with 5 effective digits

>> format long, r=5; L=2*pi*r, S=pi*r^2 % compute perimeter and area
The results obtained are L = 31.415926535897931 and S = 78.539816339744831.
To get the rational display, the format can be set to rat.
>> format rat, L, S, format short % set rational format
e1=3550/113-2*pi*r, e2=8875/113-pi*r^2 % compute approximation error
The display becomes L = 3550/113, S = 8875/113. The fractional approximation errors
in the perimeter and area are, respectively, e1 = 2.6676×10−6 and e2 = 6.6691×10−6 . 

Command get(0,'Format') extracts the current display format.


If the Preferences button in the MATLAB toolbar is clicked, the dialog box shown
in . Fig. 2.5 is displayed. Select the Command Window from the listbox on the left,
the display format can alternatively be set by selecting items in the Numeric format
and Line spacing listboxes. It is also seen from the dialog box that, apart from the
display format for numbers, other format such as date information can also be set.
If variable a is known, the command disp(a) displays the value of a in MATLAB
command window, where a can be of any data type supported in MATLAB.

2.1.5 Workspace and Management in MATLAB


MATLAB workspace is the place where MATLAB variables are stored. The following
commands manipulate the existing variables in MATLAB workspace.

. Fig. 2.5 Command window display format setting


24 Chapter 2 · Essentials in MATLAB Programming

(1) Command who lists all the variable names in MATLAB workspace, while whos
lists not only the variable names, but also other information such as data type, space
allocation and so on.
(2) To clear all variables in MATLAB workspace, command clear can be issued.
2 If only limited number of variables are to be removed, list the variable names after
clear command. Note that the variable names must be separated by spaces rather
than commas. Similarly, clearvars command can be used to remove several vari-
ables. The -except option lists names for the reserved variables. The other variables
can be removed with the command.
(3) The pair of commands save and load can be used to save or load variables to
or from files. Normally the files are with suffix mat, and they are in binary form.
(4) Command workspace opens directly the Workspace window in . Fig. 2.1.
The variables in the list can be selected individually for further manipulation.

2.1.6 Other Facilities in MATLAB


Some skills are presented in the operations in MATLAB command window, including
time elapse measuring, command history listing and code analysis, such that the
readers can use MATLAB to solve their own problems in an efficient way.
(1) Using the arrow keys. The up-arrow key scrolls back the commands in the past.
If we want to find a previous command start from ab. type ab at the prompt, and
then use up-arrow key to scroll back the expected commands.
(2) Command history display. Click Layout button in toolbar shown in . Fig. 2.2,
then select the Command History listbox, we can choose the way to display command
history information. Select a command in the past, double click it, the command

. Fig. 2.6 Code analyzer window


2.2 · Data Types in MATLAB
25 2
can be executed again. Sometimes this method may be more useful than the arrow
operations.
(3) Measuring time elapse. Two sets of methods measuring time elapse are provided
in MATLAB. One is to use command pair tic and toc. Use tic to start the stop
watch, after program execution, call toc command to read the stop watch. An alter-
native method is to measure CPU time. Before the code is executed, use t0 =cputime
to store the current CPU time, after program execution, command cputime−t0 mea-
sures time elapse. The two sets of methods have their own characteristics, and the
difference between them is not big.
(4) Code analysis. Click Analyze Code button in the toolbar, the window in
. Fig. 2.6 is displayed. The MATLAB code in the current folder can be examined
automatically, modifications and recommendations on the code are provided. For
instance, three suggestions are made to the bk_jpg.m function in the window. The
reader may decide whether or not to accept the modification as suggested.

2.2 Data Types in MATLAB


Data types are very important in programming. In this section, the constants reserved
in MATLAB are presented first, and naming regulations on MATLAB variables are
illustrated. Then two types of commonly used data types in scientific computing—
numeric and symbolic data types—are presented, followed by a brief introduction to
other data types.

2.2.1 Reserved Constants


For computational convenience, some constant names are reserved in MATLAB. For
instance, the circumference ratio π is represented directly by constant pi. Commonly
used reserved constants are provided in . Table 2.2. These names can be redefined.
Each time MATLAB restarted, the names restore to the original constant values. If a
constant is overwritten, command clear removes the overridden value, and restores
to its default value.

 Example 2.2
Observe the variations of the value of pi.
>> pi % display the default value of pi
pi=5 % redefine pi to another value
clear pi % remove the new value and restore pi to the reserved one
pi % pi is restored and displayed
Solutions In the following commands, the default value of pi is displayed first. The name
can be rewritten to other values. If clear command is used, the default value is restored.
In the above commands, pi is displayed three times, the values are in turn 3.1416, 5 and
3.1416. 
26 Chapter 2 · Essentials in MATLAB Programming

. Table 2.2 Commonly used constants

Constants Description

Machine precision, 2−52 = 2.2204×10−16 . If the absolute value of a variable is


2 eps
smaller than eps, it may be regarded as 0

pi Circumference ratio π, with reserve value of 3.141592653589793

inf, Inf MATLAB representation of +∞. Similarly, −∞ can be expressed as -Inf. In


MATLAB operations, if 0 is used as the divisor, the execution is not terminated.
A “divide by 0” warning is given, and the result is assigned to Inf. The operation
complies the IEEE standard. It can be seen from numerical operation viewpoint
that the implementation like this is more meaningful than the unprofessional
languages such as C

NaN Not a number. Obtained from 0/0, Inf/Inf and 0*Inf operations. NaN is an
interesting quantity, where the product of NaN and Inf is also NaN

i, j Constants i or j represents imaginary unit j = −1. In real programming, these
two names are always overridden. For instance, in loops, they are always used as
loop variables. To restore the original constant, commands i=sqrt(-1) or
i=1i can be used. It is strongly recommended to use 1i or 1j instead

true, false Logical constants, alternative values are 1 and 0

2.2.2 Variable Names and Naming Regulations


Variables are the most important elements in MATLAB programming. Before a
variable is used, it must be assigned to certain values first. If a variable does not exist,
an error message “Unrecognized function or variable ***” is displayed in MATLAB
command window.
MATLAB variable names must be led by a letter, followed by letters, numbers and
an underscore. For instance, MYvar12, MY_Var12 and MyVar12_ are all valid variable
names, while 12MyVar and _MyVar12 are invalid ones. MATLAB variable names are
case-sensitive, which means that Abc and ABc are two different variable names.
An important thing to note: if a variable name used coincides with the name of
an existing MATLAB function, the original function is shadowed, which may lead
to misleading results. Therefore, before using variable names, make sure it is not an
existing function name. For instance, use which command first to check whether there
is already such a function name.
An alternative way to test whether a name has been used is to use key=exist
('name') command, where the name is used to test a potential variable name, key is
the result. If key is 1, it means that there is a name variable in the current MATLAB
workspace; 2 for existing a name.m file in MATLAB search path; 3 for name.dll file;
4 for a Simulink model file; 5 for a built-in function name(); 6 for pseudocode file
name.p; 7 for a name folder. Therefore, if key is not 0, do not select such a variable
name.
2.2 · Data Types in MATLAB
27 2
2.2.3 Double Precision Data Type
Powerful and flexible capabilities in numerical operation are one of the most promi-
nent advantages in MATLAB. To ensure high precision in numerical computing, the
commonly used numeric data type in MATLAB is the double precision floating point
one, which takes 8 bites (64 bits), complying IEEE standard—with 11 exponential
bits, 52 numeric bits and 1 sign bit. The range of the data is −1.7×10308 ∼ 1.7×10308 ,
with the smallest quantity eps. Function double() converts a variable into double
precision data type.
In extreme cases, single precision data type is used, with 32 bits binary floating
point scheme. Normally 7 decimal digits are reserved. The conversion command is
single().
The default data type in MATLAB is a double precision complex matrix. Examples
are given next to illustrate the input commands for real and complex matrices.

 Example 2.3
Input the following matrix into MATLAB workspace:
⎡ ⎤
1 2 3
A = ⎣4 5 6⎦.
7 8 0

Solutions It is quite simple and straightforward to input a matrix into MATLAB workspace.
The following MATLAB command does the work:
>> A=[1,2,3; 4 5,6; 7,8 0] % input the matrix
For the convenience of reading, the actual MATLAB display is not given. Instead, the
display is given in mathematical format. In the matrix-input command, the contents of
the matrix are delimited by square brackets. The semicolons inside the square brackets
represent line changing or cartridge return, to start a new row in the matrix. Commas and
spaces are equivalent here, used to separate the elements in the same row. With the above
command, a matrix A can be established in MATLAB workspace, as a variable.
Based on the given A matrix, an augmented matrix can be generated, complying the row and
column regulations in MATLAB. The following command can be issued to dynamically
update the size of matrix A:
>> A=[[A; [1 2 3]], [1;2;3;4]] % dynamic matrix allocation


 Example 2.4
Input the following complex matrix into MATLAB workspace:
⎡ ⎤
1 + 9j 2 + 8j 3 + 7j
B = ⎣4 + 6j 5 + 5j 6 + 4j⎦ .
7 + 3j 8 + 2j 0+j

Solutions Complex matrix input is equally simple. In MATLAB, the notations i and j can
be used to describe imaginary entities. The following commands can be issued directly in
28 Chapter 2 · Essentials in MATLAB Programming

MATLAB, where to represent j, it is suggested to use 1i or sqrt(−1), rather than using i


or j.
>> B=[1+9i,2+8i,3+7j; 4+6j 5+5i,6+4i; 7+3i,8+2j 1i]

2
2.2.4 Symbolic Data Type and Symbolic Functions
Symbolic data type is also supported in MATLAB. In contrast to regular numeric
variables, symbolic variables are used in deriving formulas and finding analytical
solutions of mathematical problems. To carry out symbolic computing, the variables
must be declared as symbolic variables, with the syms command
syms variable list variable properties
where variable list is composed of a set of variable names, separated by spaces only.
Commas or other symbols cannot be used.
If necessary, the variable properties can be further declared. The properties such
as positive, integer, real and rational can be used. If a and b are to be defined as
symbolic variables, command syms a b can be used. The command can also be used
to declare specific properties for the symbolic variables. For instance, sym a real
command declares a as a real symbolic variable. If the variable properties are set to
clear, the property setting is removed, such that it is restored into ordinary symbolic
variable.
The information regarding a symbolic variable is retrieved with assumptions()
function. For instance, syms a real declares a variable a, and assumptions(a)
returns in(a ,'real').
Function x=symvar(f ) is provided in MATLAB Symbolic Math Toolbox, which
extracts symbolic variable list x from a symbolic expression f . All the symbolic vari-
ables in f can be retrieved in vector x.
Variable precision algorithm can be used to display a variable in any number of
digits, with vpa() function. The syntax of the function is vpa(A) or vpa(A,n), where
A is the symbolic expression to be displayed, n is the number of effective digits, with
default of 32 decimal digits.

 Example 2.5
How to describe 1/3 in MATLAB? What is 1/3 × 0.3 − 0.1?
Solutions Conventional computer languages support double precision data type, while
MATLAB also supports symbolic data type. What are the differences between these two
data types? The value 1/3 cannot be stored properly under double precision data type. It
is stored as 0.333333333333333, and the trailing digits are truncated. Symbolic sym(1/3)
stores and uses 1/3 all the time, without any error. It is obvious that in mathematics 1/3 ×
0.3 − 0.1 = 0, and it is so under symbolic data type. Now let us see what happens under
double precision framework. The following commands can be issued, and it can be seen
that the error is −1.3878×10−17 , smaller than eps.
>> 1/3*0.3-0.1 % expecting a 0, but the result is not

2.2 · Data Types in MATLAB
29 2

 Example 2.6
Display the first 100 digits for π.
Solutions If vpa() function in the Symbolic Math Toolbox is used, it can be displayed to
any number of digits. Therefore, the following commands can be used to solve the problem:
>> vpa(pi,100) % display the first 100 digits of π, and even more
The first 100 digits of π is 3.14159265358979323846264338327950288419716939937510582
0974944592307816406286208998628034825342117067. If n is not specified, vpa(pi) yields
π = 3.1415926535897932384626433832795. The user may specify even larger n’s, for
instance, 1000, 10000 or even larger ones. 

It is noted that function vpa() may only display a maximum of 32766 digits. To
display more digits, the methods presented later can be used. See Example 3.4.

 Example 2.7
Display the first 50 digits for the irrational number e.
Solutions To find the first 50 digits of e, it is natural to try the command vpa(exp(1),50).
Unfortunately, double precision is used first to compute e, then displays its first 50 dig-
its. Therefore the display is not accurate. The correct method is to compute e under
symbolic framework, then display the first 50 digits. The command should be
vpa(exp(sym(1)),50), which yields 2.7182818284590452353602874713526624977572470
937. 

The properties of symbolic variables can also be further defined with functions
assume() and assumeAlso(). For instance, let x be a real number, and −1  x < 5,
the following MATLAB commands define such a symbolic variable.
>> syms x real; assume(x>=-1); assumeAlso(x<5); % set −1  x < 5
Call assumptions(x) function, the display of x is [x < 5,−1 <= x].
If in MATLAB workspace there is already a variable a, function A =sym(a)
converts it into symbolic data type. Sometimes special manipulations are needed.
Examples are given next for demonstrations.

 Example 2.8
Represent integer 12345678901234567890 in MATLAB.
Solutions Numeric data type cannot represent such a long integer. It seems that with
command A =sym(12345678901234567890), the problem can be presented. However,
the result is A = 12345678901234567168, which is apparently incorrect. In the MATLAB
mechanism, the data is converted into double precision first, then converted into symbolic
expression, which yields bias. Therefore, care must be taken for this type of problems.
A feasible solution is to use strings to express long integers, then use sym() function for
conversion. The following statement inputs the 50-digit integer.
>> B=sym('12345678901234567890123456789012345678901234567890')

30 Chapter 2 · Essentials in MATLAB Programming

 Example 2.9
Convert the complex matrix in Example 2.4 into symbolic form.
Solutions The commands in Example 2.4 can be issued first to input the matrix, then use
sym() function for conversion. Note the display formats of the two data types.
2
>> B=[1+9i,2+8i,3+7j; 4+6j 5+5i,6+4i; 7+3i,8+2j 1i], B=sym(B)


Based on symbolic variables, symbolic functions can be declared. Symbolic func-


tions can also be declared with syms command, but its data type is symfun. An example
is given next to demonstrate the declaration method.

 Example 2.10
Declare symbolic functions F (x) and G(x, y, z, u).
Solutions Symbolic variables should be declared first, then declare F (x) and G(x, y, z, u).
>> syms x y z u F(x) G(x,y,z,u) % declare symbolic variables and functions
F(x,y)=x*y; % This command may lead to errors, clear F first


2.2.5 Generating Arbitrary Symbolic Matrices


MATLAB function sym() can also be used in generating arbitrary matrices. For
instance, the commands below can be used
A=sym('a',[n,m]), B=sym('b%d%d',[n,m])
where n and m are, respectively, the row and column numbers of the matrix. If one
of them is 1, arbitrary vectors can be defined. To generate a square matrix, m is not
needed. The above two commands can be used to generate arbitrary matrices A and
B, but the formats are different. The elements in A are ai_j, while those for B are bij .
Therefore, the former is not recommended.

 Example 2.11
Generate the following arbitrary matrices into MATLAB workspace:
⎡ ⎤ ⎡ ⎤
a11 a12 a13 a14 f1
A = ⎣ a21 a22 a23 a24 ⎦ , f = ⎣ f2 ⎦ .
a31 a32 a33 a34 f3

Solutions The following statements generate directly matrix A and vector f , where in vector
generation, it is not necessary to specify the type of the subscripts. Simple commands are
sufficient.
>> A=sym('a%d%d',[3,4]), f=sym('f',[3,1]) % constructing symbolic matrices

2.2 · Data Types in MATLAB
31 2
2.2.6 Other Data Types
Since the concentrations of the book are made on scientific computing and simulation,
double precision and symbolic data types are mainly addressed. Apart from the data
types, other commonly used data types are also supported.
(1) Single precision data type. Double precision data type is composed of 64 bits,
while single precision data type is with 32 bits binary code. The corresponding data
type is single. Single data type saves half of the storage space, but the accuracy is
sacrificed.
(2) Integer data type. In some specific applications, integer data type can be used.
For instance, in digital image processing, unsigned integer data types are widely used.
For example, uint8() is 8-bit unsigned integer, ranging 0 ∼ 255. Other supported
integer data types include int8(), int16(), int32(), int64(), uint16(), uint32(),
uint64() and so on. In numerical computing and simulation, if definitely needed,
these data types are not recommended.
(3) Logical data type. Logical data type is supported in MATLAB, whose values
are only 0 and 1. The conversion function is logical(), and the data type is logical.
Double precision or other data types also represent logical quantities. If the value is
zero, it is regarded as logic 0, otherwise, it is logic 1.
(4) Strings. Strings are delimited by single quotation marks. For instance, 'Hello
World', whose data type is char. String operations will be illustrated later.
(5) Structured data type. Structured variable contains a lower level of information,
for instance, A.b represents lower level member b under variable A. One structured
variable may have several members, and each member can be of any data type, includ-
ing lower level structured variables. The identifier of structured variable is struct.
(6) Multidimensional arrays. A vector is a one-dimensional array and matrix is a
two-dimensional one. Apart from those, multidimensional arrays are supported. For
instance, to describe a mono-colored image, it can be divided into mesh grids, each
such a grid is known as a pixel. Therefore, a matrix describes the grayscale values of
each pixel. To describe a colored image, three such matrices are used, representing,
respectively, the red, green and blue components. If the three matrices are piled up,
a cubic structure can be created, with the first layer representing red, the second
green and the third blue. In this case, a three-dimensional array can be defined, where
A(:,:,1) for red components. Similarly, the concept of 3D array can be extended
to multidimensional case.
(7) Cells. Consider matrix A, whose elements are numbers. If each element allows
to use different data type, for instance, a1,1 is a matrix, a1,2 is a string, the matrix data
type is insufficient doing that. The matrix concept should be extended to cells. If ai,j
is conceived as an independent unit, the cell structure can be defined. The identifier
of cell is cell.
>> A{1,1}=[1 2 3; 4 5 6; 7 8 1i]; A{1,2}='Hello World'
(8) Other data types, for instance, table data type is supported. They are not
covered in the book. Interested readers may refer to Reference [1]. Also, class and
object data types are supported, and an introduction to these data types is presented
in 7 Chap. 6.
32 Chapter 2 · Essentials in MATLAB Programming

2.2.7 Data Types Recognition


If there is a variable A, its data type can be extracted with class(A) command. For
instance, for the A matrix in Example 2.3, if class() is used, the result is double.
2 For the x and F variables in Example 2.10, if class() function is called, the returned
data type identifiers are, respectively, sym and symfun.
For the matrix A in Example 2.3, the function isa() can be called. For instance,
the command key=isa(A,'double') checks whether A is in double precision data
type. If it is, it returns logic 1, otherwise it returns 0.
Besides, functions such as isnan(), isfinite() can be called, to check whether
the data type is satisfied. For instance, v 1 =isnan(v) command is used to check
whether vector v contains NaN. Each element in the vector is tested, and the returned
v 1 is also a logical vector, of the same size as v. If the corresponding element in v is
NaN, the value is set to 1, otherwise it is 0.

2.3 MATLAB Statement Structures


There are mainly two types of MATLAB statements—assignment statements and
function call statements. In this section, these two types are presented first. Then
a colon expression format is illustrated, and based on it, submatrix extraction is
demonstrated.

2.3.1 Fundamental Assignment Statements


The structure of direct assignment statement is simple: a =expression. The returned
variable name a to the left of the equal sign is given. It can be any valid variable
names. To the right of the equal sign is the expression of any complexity, including
the mathematical operations of known variables. After the expression evaluation, the
result is assigned to a automatically. The variable can then be established in MATLAB
workspace. If the variable is already there, the old one is overridden. In fact, we have
used simple assignment statements several times earlier, and the structure is rather
straightforward. If the statement is ended with semicolon, the variable assigned is not
displayed in MATLAB command window, otherwise, the result is displayed.
For simple operations, a= can be omitted. The expression statement is still eval-
uated, and the result is returned in the reserved constant ans.

 Example 2.12
For the given function f (x) = x2 − x − 1, evaluate F (x) = f (f (f (f (f (x))))). If the result
is a polynomial, what is its highest degree?
Solutions The simplest way doing this is to use symbolic function to represent f (x). Then the
complicated composite function can be evaluated easily by the nested calls of the function.
The obtained polynomial can be expanded with expand() function.
>> syms x; f(x)=x^2-x-1; % define the function
F(x)=f(f(f(f(f(x))))), F1=expand(F) % expand the composite function
2.3 · MATLAB Statement Structures
33 2
The expanded polynomial of degree 32 is as follows:

F1 (x) = x32 − 16x31 + 96x30 − 200x29 − 444x28 + 2968x27 − 3052x26 − 11804x25 +


30944x24 + 9832x23 − 112076x22 + 68760x21 + 216048x20 − 279328x19 −
218500x18 + 525046x17 + 47653x16 − 591744x15 + 164520x14 +
416864x13 − 232442x12 − 175256x11 + 154806x10 + 35134x9 − 58854x8 +
1496x7 + 12614x6 − 2044x5 − 1382x4 + 300x3 + 69x2 − 9x − 1.

2.3.2 Function Calls


Function call statement is another major MATLAB statement format. MATLAB
functions are also the mainstream programming style in MATLAB. The fundamental
structure of function call is
[returned argument list]=fun_name(input argument list)
where fun_name is the name of the function, whose naming regulation is the same
as the ones for variables. Normally a function name corresponds to a file name
under MATLAB search path. For instance, function name my_fun corresponds to
the my_fun.m file. Of course, there are some function names corresponding to built-in
function in MATLAB. For instance, inv() function.
Returned argument list and input argument list can be consisted of several vari-
able names, separated by commas. For instance, [U,S,V ]=svd(X). Singular value
decomposition is made upon the input argument X, and the results are returned in
arguments U, S and V .
Flexible mechanism is provided in MATLAB, allowing the user to call the same
function under different syntaxes. For instance, MATLAB provides a built-in func-
tion eig(), the syntax eig( A) computes only the eigenvalue vector, while syntax
[V , D]=eig( A) returns not only the eigenvalues in D, but also the eigenvector matrix
V . If the syntax is changed to eig( A,B), generalized eigenvalues are obtained.
Apart from these, different toolboxes may provide different eig() files in MAT-
LAB. For instance, the eig() function provided in the Symbolic Math Toolbox is
used to find analytical solutions of the eigenvalues, from a symbolic matrix, while
eig() function provided in the Control System Toolbox evaluates the poles of a lin-
ear system. MATLAB mechanism may handle these functions such that they cannot
be mixed up. Under such a mechanism, the data type of the input arguments is rec-
ognized first, then appropriate eig() function for the particular data type is called,
so as to reach expected results.
The structure and programming details of MATLAB functions will be fully
addressed in 7 Chap. 4.

2.3.3 Colon Expressions


Colon expression is a very useful expression in MATLAB. It is useful in vector gen-
eration and submatrix extraction. The colon expression v = s1 :s2 :s3 generates a row
34 Chapter 2 · Essentials in MATLAB Programming

vector v, where s1 is the start value of the vector, s2 is the increment and s3 is possibly
the maximum value. If s2 is omitted, the increment of 1 is adopted.

 Example 2.13
2
Try different increments and create vectors in the range t ∈ [0, π].
Solutions Try increment of 0.2 first. The following commands can be used to generate a
vector:
>> v1=0:0.2:pi % note that the last value is 3 rather than π
which yields a row vector v 1 = [0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6,
2.8, 3].
Under different increments, the other vectors can be constructed using colon expressions.
>> v2=0:-0.1:pi, v3=0:pi, v4=pi:-1:0 % compare the results, understand them
where the generated v 2 is a 1×0 empty matrix, v 3 = [0, 1, 2, 3],v 4 = [3.1416, 2.1416, 1.1416,
0.1416]. 

It can be seen from the above example that the final value in the vector v 1 is not
the expected π. If the terminal value is expected, the following two methods can be
adopted:
(1) Set increment to π/N, where N is an integer, command v=0:pi/N:pi gener-
ates the expected vector.
(2) With linspace() function. Executing the command v=linspace(0,pi,
N + 1), an identical row vector v is generated.

 Example 2.14
Find all the integers dividable by 13 in the range 1∼1000.
Solutions One may check individually for each integer and see whether they are dividable
by 13. But this method is rather complicated. An alternative way doing this is to consider,
what is the first integer dividable by 13. Of course, it is a1 = 13. What is the second one? It
is a2 = a1 + 13. Then the subsequent ones are a3 = a2 + 13, a4 = a3 + 13, · · · . Of course,
the numbers are a set of values starting from 13, with increment of 13. Colon expressions
are suitable for generating those numbers, with the following MATLAB commands:
>> A=13: 13: 1000 % generate equally spaced vector with increment of 13


2.3.4 Submatrix Extraction


Submatrix extraction can be implemented from B = A(v 1 ,v 2 ), where v 1 vector speci-
fies all the row numbers to be extracted, v 2 specifies all the column numbers. Therefore
the selected rows and columns can be extracted from A, and assigned to B matrix. If
v 1 is :, all the rows are extracted. Similar cases apply to v 2 . The keyword end stands
for the last row (or column, depending on its position).
To delete the ith row from the matrix, A(i,:)=[] can be used, where i can also
be a vector.
2.4 · Fundamental MATLAB Operations
35 2

 Example 2.15
The following commands can be executed in MATLAB. The readers are referred to under-
stand the physical meaning of these statements, by comparing the comments and results.
>> A=[1,2,3; 4 5,6; 7,8 0]; B1=A(1:2:end,:) % extract all the odd rows
B2=A([3,2,1],[1,1,1]) % extract the 3rd, 2nd and 1st rows, 1st column of A
B3=A(:,end:-1:1) % left to right flip of A matrix
A(2,:)=[]; A(:,3)=[] % delete the 2nd row, 3rd column from A
The following matrices can be generated
⎡ ⎤ ⎡ ⎤
  7 7 7 3 2 1  
1 2 3 1 2
B1 = , B2 = ⎣ 4 4 4 ⎦ , B3 = ⎣ 6 5 4⎦, A = .
7 8 0 7 8
1 1 1 0 8 7

2.3.5 Man–Machine Interactive Functions in MATLAB


Many man–machine interactive functions are supported in MATLAB. Under com-
mand prompt, r =input(prompt) command gives prompt, the user may respond
to the prompt by entering the value of r. The response can be a scalar, vector or a
matrix. Strings can be entered with the command r =input(prompt,'s').
Besides, menu() function displays a menu:
key=menu(title of the string,option 1,option 2,· · · ,option n)
The user makes a choice from the menu.

 Example 2.16
Some interactive commands are given below. The user can input these commands into
MATLAB, and make responses to the commands to observe and understand the results.
>> r=input('enter radius') % may answer 5, or [1,2,3] for a set of radii
str=input('enter name','s') % input a string
key=menu('select a color','red','green','blue') % select a color


2.4 Fundamental MATLAB Operations


Various variable and matrix operations are supported in MATLAB. In this section,
concentrations are made on arithmetic operations, transcendental functions, logical
and relational operations. String operations and symbolic expression manipulations
are also presented.
36 Chapter 2 · Essentials in MATLAB Programming

2.4.1 Arithmetic Operations


Arithmetic operations are those in which the relationship between variables can be
expressed by a finite number of the four arithmetic operations, power and root oper-
2 ations. Some of the arithmetic operations are provided in . Table 2.3.

 Example 2.17
Observe the two simple variables below. What is the sum A + B?
   
5 1 2
A= , B= .
6 3 4

Solutions In mathematics, since the sizes of the two matrices are different, they cannot be
added up. It is the same in the earlier versions of MATLAB. In the recent versions, the
following commands can be tried.
>> A=[5;6]; B=[1 2; 3 4]; C=A+B, D=B-A'
In practice, this is an extension to the addition operation, and it is meaningful. Since A is
a column vector, it can be added to all the columns of matrix B, such that the sum can be
found. Besides, since AT is a row vector, it can be extracted from B matrix to compute D.
   
6 7 −4 −4
C= , D= .
9 10 −2 −2

 Example 2.18
For the complex matrix B in Example 2.4. Extract its real and imaginary parts.
⎡ ⎤
1 + 9j 2 + 8j 3 + 7j
B = ⎣ 4 + 6j 5 + 5j 6 + 4j ⎦ .
7 + 3j 8 + 2j j

Solutions Input the complex matrix into the computer, then the real and complex parts can
be extracted with the following commands.
>> B=[1+9i,2+8i,3+7j; 4+6j 5+5i,6+4i; 7+3i,8+2j 1i];
R=real(B), I=imag(B) % extract the real and imaginary parts
The real and imaginary parts can be extracted as
⎡ ⎤ ⎡ ⎤
1 2 3 9 8 7
R = ⎣4 5 6⎦, I = ⎣6 5 4⎦.
7 8 0 3 2 1


2.4 · Fundamental MATLAB Operations
37 2

. Table 2.3 MATLAB arithmetic operations

Operations Syntaxes and descriptions

Transpose A . Hermitian transpose of a complex matrix, that is, transpose then take
conjugate. If direct transpose is needed, use A.

Addition A + B. The corresponding elements of A and B matrices can be added up.


Normally the sizes of the two matrices are the same, while there are three
special cases, if one of them is a scalar or a vector, or the two are different
vectors. Examples are given later

Subtraction A − B. Corresponding element subtraction

Multiplication A ∗ B. Matrix product AB, where the matrices should be compatible

Left division A \ B. Solution X to the equation AX = B. If A is a nonsingular square


matrix, X = A−1 B; if A is singular and/or rectangular, the least squares
solution is found

Right division A / B. Solution of equation X A = B

Power A ^ p. Matrix power, where A is square, p is any scalar

Dot operation A.∗B. Corresponding elements of A and B are multiplied, which implies the
sizes of the two matrices are identical, or one of them is a scalar. Other dot
operations are supported, i.e., A.^B, A. / B and so on

Flipping fliplr( A). Left–right flipping, equivalent to A(:,end:-1:1); up–down


flipping can be implemented with flipud( A)

Rotating rot90( A). Rotate the elements in A by 90◦ in counterclockwise direction.


Command rot90( A, k) can also be used, where k is an integer

Expansion A(:). Expand A matrix in a column-wise format into a column vector. The
command applies also to multidimensional arrays

Reshape reshape(A,[n,m]). Rearranged the p × q matrix A into an n × m one, where


pq = nm. The specific method is that to expand A into a column vector in a
column-wise format, then segment the elements into a new matrix. It applies to
multidimensional arrays

Conjugate conj(Z). Computes complex conjugate matrix. Also, real(Z) and imag(Z)
commands extract the real and imaginary parts; abs(Z) and angle(Z) extract
the magnitude and phase, with phase in radians

Maximum [a, k]=max( A). Find the maximum values in each column in matrix A to yield
a row vector a, the indices are returned in vector k. The maximum value of the
entire matrix can be found with max( A(:)). Minimum values can be found
with min() function

Sorting [a, k]=sort( A). Sort the elements in each column of A in ascending order,
and the sorted results and indices are returned in vectors a and k. To sort in
descending order, [a, k]=sort( A,'descend') can be used

Rounding round( A). Rounding each elements in A to the nearest integer. Other functions
such as floor(), ceil() and fix() find integers under different definitions
38 Chapter 2 · Essentials in MATLAB Programming

Most of the mathematical functions in . Table 2.3 have unique solutions. √ The
root operation of matrices is an exception. Consider the scalar operation 3 −1. One
of its solutions is −1. Rotating the solution 120◦ in the complex plane, the second
solution can be found. Rotate further another 120◦ , the third solution can be found.
2 How to rotate it by 120◦ ? Just multiply the result by a complex scalar δ = e2πj/3 .
If the mth root is expected, the result obtained with A^(1/m) is one solution. It is
multiplied by δk = e2kπj/m , where k = 1, 2, . . . , m − 1, such that all the matrix roots
can be found.

 Example 2.19
Consider again the A matrix in Example 2.3. Find all its cubic roots and validate the results.
Solutions With ^ operation, one of the cubic roots can be found and then validated.
>> A=[1,2,3; 4,5,6; 7,8,0];
C=A^(1/3), e=norm(A-C^3) % find and validate the cubic root
The result is as follows. It can be validated that the norm of the error matrix is e = 1.0145×
10−14 . Therefore, the result is accurate.
⎡ ⎤
0.7718 + j0.6538 0.4869 − j0.0159 0.1764 − j0.2887
C = ⎣ 0.8885 − j0.0726 1.4473 + j0.4794 0.5233 − j0.4959 ⎦ .
0.4685 − j0.6465 0.6693 − j0.6748 1.3379 + j1.0488

In fact, there are three cubic roots. The one obtained is just one of them. Rotate the matrix
twice, that is, compute Cej2π/3 and Cej4π/3 , the other two roots can be found.
>> j1=exp(sqrt(-1)*2*pi/3); A1=C*j1, A2=C*j1^2 % find the other two roots
e1=norm(A-A1^3), e2=norm(A-A2^3) % validating results
The other two roots are as follows, and the errors are all at 10−14 level.
⎡ ⎤
−0.9521 + j0.3415 −0.2297 + j0.4296 0.1618 + j0.2971
A1 = ⎣ −0.3814 + j0.8058 −1.1388 + j1.0137 0.1678 + j0.7011 ⎦ ,
0.3256 + j0.7289 0.2497 + j0.9170 −1.5772 + j0.6343
⎡ ⎤
0.1803 − j0.9953 −0.2572 − j0.4137 −0.3382 − j0.0084
A2 = ⎣ −0.5071 − j0.7332 −0.3085 − j1.4931 −0.6911 − j0.2052 ⎦ .
−0.7941 − j0.0825 −0.9190 − j0.2422 0.2393 − j1.6831

It can be found under symbolic framework that the errors are around 7.2211×10−39 , much
smaller than the ones obtained under double precision framework.
>> A=sym([1,2,3; 4,5,6; 7,8,0]); C=A^(sym(1/3)); % symbolic computing
C=vpa(C); norm(C^3-A) % validate the results


 Example 2.20
The inverse of matrix A is mathematically denoted as A−1 . Function inv( A) finds the
inverse of matrix A. Use the complex matrix in Example 2.4, and find its −1st power, and
see whether it is the same as the inverse of A.
2.4 · Fundamental MATLAB Operations
39 2
Solutions To ensure accuracy in computation, symbolic matrices should be used. The
commands are used to compute the two matrices.
>> B=[1+9i,2+8i,3+7j; 4+6j 5+5i,6+4i; 7+3i,8+2j 1i];
B=sym(B); B1=B^(-1), B2=inv(B), C=B1*B % use inv() to find the inverse
It can be seen that the two matrices are identical
⎡ ⎤ ⎡ ⎤
13/18 − 5j/6 −10/9 + j/3 −1/9 1 0 0
B 1 = B 2 = ⎣ −7/9 + 2j/3 19/18 − j/6 2/9 ⎦ , C = ⎣ 0 1 0⎦.
−1/9 2/9 −1/9 0 0 1

 Example 2.21
Find the inverse matrix for the B matrix in Example 2.20. Preserve its two decimal digits
and assign it to matrix A.
Solutions To preserve certain number of digits, integer rounding method can be used. If two
digits are preserved, the expected result can be found by rounding 100B −1 into integers,
then times 0.01. The result can be found with the commands.
>> B=[1+9i,2+8i,3+7j; 4+6j 5+5i,6+4i; 7+3i,8+2j 1i];
A=0.01*round(100*inv(B)) % preserve two decimal digits
The converted result is
⎡ ⎤
0.72 − 0.83j −1.11 + 0.33j −0.11
A = ⎣ −0.78 + 0.67j 1.06 − 0.17j 0.22 ⎦ .
−0.11 0.22 −0.11

2.4.2 Transcendental Functions


Transcendental functions are those the relationship of the variables cannot be evalu-
ated with finite numbers of the four arithmetic operations, power and root operations.
For instance, exponential function, logarithmic function and trigonometric functions.
In . Table 2.4, the commonly used transcendental functions and MATLAB imple-
mentations are summarized, where the input argument x can be scalar, vector, matrix
or even multidimensional arrays. Note that the transcendental functions are carried
out on each element of x individually. It is similar to the dot operations discussed
earlier. Examples are provided next to illustrate the computations of transcendental
functions.

 Example 2.22
Show the famous identity ejπ + 1 = 0 in MATLAB.
Solutions This identify is regarded as the most beautiful formula of all time. It involves
irrational number π, imaginary unit j, and with transcendental function, the result is −1.
40 Chapter 2 · Essentials in MATLAB Programming

. Table 2.4 Commonly used transcendental functions

Functions Syntaxes and descriptions

exp(x). Compute the exponential function e x


2
Exponential

Logarithmic log(x). Natural logarithmic function lnx can be found from log(x),
common logarithmic function lgx and base 2 logarithmic function log2 x
can be found from log10(x) and log2(x). Base a logarithmic function
loga x can be computed from log(x)/log(a)

Trigonometric sin(x). Sinusoidal, cosine, tangent, cotangent functions can be evaluated


with functions sin(), cos(), tan() and cot(); secant, cosecant functions
with sec() and csc(); hyperbolic sine sinh x, hyperbolic cosine cosh x
can be found from sinh() and cosh() functions; The default unit for
trigonometric function is radian. If degrees are used, it can be converted to
radian y =pi*x /180 first. Alternatively functions like sind() can be
used instead

Arc trigonometric asin(x). Add a in front of the trigonometric function names, arc
trigonometric functions can be computed

How can we show such an identity? The left side of the identity can be fed into MATLAB
in symbolic form, and the result is 0, which means that the identity hold.
>> exp(sym(pi)*1i)+1 % symbolic computation yields the expected result


 Example 2.23
Simplify the following logarithmic expressions:

4 ln e3
f = log3 729 + log2 17 − log2 83521.
lg 5000 − lg 5

Solutions The expression can be fed directly into the computer directly. The computer can
then be used to compute and simplify the result. It is found that the result is f = 6.
>> f=log(729)/log(3)+4*log(exp(sym(3)))/... % ... for line continuation
(log10(5000)-log10(5))*log2(17)-log2(83521) % direct function call


 Example 2.24
Simplify the following trigonometric function:

4 7π 11π 1 1 π
T= cos + 3 tan2 − − sin2 .
3 3 6 2 cos2 (17π/4) 3 3
2.4 · Fundamental MATLAB Operations
41 2
Solutions The following commands compute the expression and the result obtained is
T = 5/12. It is recommended that symbolic data types are used in the computation. To use
symbolic computation, only convert one quantity into symbolic form. The whole execution
is then carried out under the symbolic framework, such that accurate result can be found.
>> T=4/3*cos(7*sym(pi)/3)+3*tan(11*pi/6)^2-1/(2*cos(17*pi/4)^2)...
-1/3*sin(pi/3)^2 % direct computation


 Example 2.25
Compute the trigonometric function
 √
cos 40◦ + sin 50◦ 1 + 3 tan 10◦
T= .
sin 70◦ 1 + cos 40◦

Solutions Since the unit given here is degree, not the default radian, unit conversion can
be used, x1 = πx/180, to unify the unit into radian, then start computing. An alternative
method is to use functions such as sind() to compute the expression.
>> T1=(cosd(40)+sind(50)*(1+sqrt(3)*tand(10)))/...
sind(70)/sqrt(1+cosd(40)) % use degree directly
p=sym(pi)/180; % unit conversion
T2=(cos(40*p)+sin(50*p)*(1+sqrt(3)*tan(10*p)))/...
sin(70*p)/sqrt(1+cos(40*p)) % compute under radian
vpa(T2-sqrt(2)) % compare results

The final result obtained above is T1√= 1.414213562373095, very close to 2. If symbolic
method is used, the result is also not 2. However it is found from vpa() function that the
error is zero. 

 Example 2.26
It is in our impression that | cos x| ≤ 1. Is it really so?
Solutions The condition when | cos x| ≤ 1 is satisfied is that, x is real. If x is an imaginary
or a complex number, the following commands can still be used to find the cosine values.
It is found that a1 = 3.7622, a2 = 2.0327−3.0519j and a3 = 2.0327+3.0519j. The absolute
values are all greater than 1, and a2 and a3 are complex conjugates.
>> a1=cos(2i), a2=cos(1+2i), a3=cos(1-2i) % cosine functions


If in the transcendental functions, matrix x is a square matrix, matrix transcenden-


tal functions are involved, also known as matrix functions. Dedicated presentation
on matrix functions will be addressed in 7 Chap. 8.
42 Chapter 2 · Essentials in MATLAB Programming

2.4.3 Logical Operations


If matrices A and B are the same size, n × m matrices, or one of them is a scalar, the
logical operations in MATLAB are given in . Table 2.5. Note that, logic operation
2 is in fact dot operations. If the sizes of the two matrices are not compatible, logical
operations cannot be carried out.

2.4.4 Relational Operations


Relational operations are defined in MATLAB. For instance, C = A > B, when A
and B matrices satisfy aij > bij , cij = 1, otherwise cij = 0. MATLAB language also
supports equal relationship, using the operator ==. The not equal relationship can be
expressed with the ~= operator. Besides, the operators such as <, >=, <= and so on are
supported. They can be used directly.

2.4.5 String Manipulations


String is an important data type in programming. Some input and output information
can be represented in strings. In this section, the representation of string is given first,
and the operations such as string searching and replacement are illustrated. String
read and write is also presented.
String variables are used to store text information. For instance, in Example 2.8,
a string application is demonstrated. The following command inputs directly a string
into MATLAB:
>> strA='Hello World!'

. Table 2.5 Logical operations

Operations Descriptions

A& B “and” operation of matrices A and B. If the corresponding elements are all
nonzero, the result is 1, otherwise the results are 0. If both A and B are scalars, it
is recommended to use the operator &&

A| B “or” operation of matrices A and B. If at least one of the corresponding elements


is nonzero, the result is 1, otherwise the result is 0. If both A and B are scalars, ||
is recommended

~A “not” operation. If the matrix element is 0, the result is 1, otherwise it is 0

xor( A,B) “exclusive or” operation. If one of A and B is 0, the other is nonzero, the result is
1, otherwise the result is 0
2.4 · Fundamental MATLAB Operations
43 2

 Example 2.27
Demonstrate string concatenation and other manipulation methods.
Solutions If there are several strings, they can be concatenated together, to form a longer
string. For instance
>> strA='Hello World!'
strB=' three strings '; strC=[strA, strB, strA]
The statement yields a longer string, which is concatenated by the three strings, which reads
'Hello World! three strings Hello World!'
“Column string vector” can be created in MATLAB, by piling up strings of different lengths.
The function str2mat() in MATLAB implements that
>> strD=str2mat(strA,strB,strA) % rearrange strings into a matrix
which yields a 3 × 16 string array
'Hello World!'
' three strings '
'Hello World!'
To extract the first row from the above string, the command strD(1,:) is used, rather
than the strD(1) command, otherwise, only the first character of the first row string is
extracted. The result of function strvcat() is the same as str2mat() function. 

 Example 2.28
String variables are delimited by single quotation marks. How to represent a single quota-
tion mark inside a string?
Solutions Single quotation mark inside a string can be expressed by two consecutive single
quotation marks. Therefore, it is not hard to understand the following command:
>> strE='In this string, single quote '' is defined.'


Many functions are provided in MATLAB to handle strings, and the commonly
used ones are provided in . Table 2.6. Examples are given next to demonstrate the
string handling methods.

 Example 2.29
If strA variable stores the string 'Hello World!', find the positions of letter o. How
many times the letter appears?
Solutions To find the letter 'o', the following commands can be issued.
>> strA='Hello World!'; k=findstr(strA,'o'), length(k)
and the return vector is k = [5, 8], meaning that the 5th and 8th character in the string is
letter o, and the letter appears twice. If the two arguments in the findstr() function are
swapped, the same results can be found. If we want to substitute o into OK, the following
command can be issued, which yields a result HellOK WOKrld!.
>> str=strrep(strA,'o','OK') % string substitution

44 Chapter 2 · Essentials in MATLAB Programming

. Table 2.6 Commonly used string processing functions

Functions Descriptions

k =strcmp(str1 ,str2 )
2
Checks whether the two strings are the same. If they are, k
returns 1, otherwise returns 0

k = findstr(str1 ,str2 ) Finds all the subscripts where one of the strings appear in
the other string. If the shorter one does not appear in the
longer one, it returns an empty matrix

str=strrep(str1 ,str2 ,str3 ) String substitution. Change str2 in the original string str1
to str3 , and the result is returned in str

str1=deblank(str) Deletes blanks at the end of string str

k =length(strA) Measures the number k of characters in the string

str=num2str(v,n) Converts variable into a string, where n is the number of


digits reserved. To convert integers into a string, function
int2str() can be used instead

v =double(str) Converts each character in the string into ASCII code, to


form vector v; If ASCII vector is v, function char(v) can be
used to restore it into a string

str=sprintf(format,a1 ,· · · ,am ) Writes to the string str in specified format, where format is
the string to control the display of variables. For instance,
'%d' for integer format, '%f' for floating point format,
'%s' for strings

eval(str) Executes the MATLAB commands specified in string


str

feval(fun,p1 ,p2 ,· · · ,pn ) Executes fun() function, which is equivalent to


fun(p1 ,p2 ,· · · ,pn )

 Example 2.30
Convert 'Hello World!' string into ASCII codes.
Solutions Input the string into MATLAB workspace, and then call double() function.
>> strA='Hello World!'; v=double(strA), s1=char(v)
The obtained ASCII code vector is v = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100].
Each number is the ASCII representation of the corresponding character. If char() func-
tion is applied to the result, the original string is restored. 

 Example 2.31
Observe what is exactly the double precision representation of 1/3.
Solutions To observe the exact representation, it can be converted into a string. It can be seen
from the result that 1/3 is actually stored in MATLAB as 0.333333333333333314829616256
247, where only the first 16 digits are accurate. The remaining ones after 16 digits are
unreliable ones, and can be ignored completely.
2.4 · Fundamental MATLAB Operations
45 2
>> a=1/3; num2str(a,30) % display the first 30 digits of 1/3


 Example 2.32
Display the perimeter and area of the circle in Example 2.1 in a more readable format.
Solutions The direct display of the results is already demonstrated in Example 2.1. Here a
more readable format of display can be generated, with the following statements:
>> r=5; L=2*pi*r; S=pi*r^2; % compute the perimeter and area
str=sprintf('perimeter is %f, area is %20.12f',L,S); disp(str)
The generated string str can be displayed with function disp() in the following format.
The default is with 6 decimal digits, and the user may specify the total number of digits and
the number of decimal digits.
perimeter is 31.415927, area is 78.539816339745


2.4.6 Processing Symbolic Expressions


Symbolic Math Toolbox can be used to derive formulas. The results obtained are
usually not in their simplest form or not in the expected form. Simplification and
manipulation for the results are expected. The commonly used simplify() function
can be used to perform simplification tasks, with the format s1 =simplify(s). Dif-
ferent simplification functions are tried to the expression s, and the simplest form s1
can be found. Note that the function simple() in the old versions can no longer be
used. Apart from simplify() function, other functions shown in . Table 2.7 are
provided in manipulating symbolic expressions.

 Example 2.33
Convert the function tan(x + y) into an expression containing sine functions only.
Solutions Input the function, then rewrite it into a new expression.
>> syms x y, F=tan(x+y), F1=rewrite(expand(F),'sin')
and the result obtained is

sin x/(2 sin2 x/2 − 1) + sin y/(2 sin2 y/2 − 1)


F1 = .
sin x sin y/[(2 sin2 x/2 − 1)(2 sin2 y/2 − 1)] − 1


46 Chapter 2 · Essentials in MATLAB Programming

. Table 2.7 Commonly used symbolic expression processing functions

Functions Descriptions

2
[n,d]=numden(s) Extracts from symbolic expression s the numerator n and denominator d

expand(s,fun) Expansion, suitable for use in polynomials and trigonometric functions

collect(s1 ,s) Collects like-terms from expression s1 according to term s

v =factor(s) Factorization for expression s. the factors are returned in the vector v. To find
the factorized expression, use command prod(v) to multiply the factors

subs(s,s1 ,s2 ) Substitutes s1 in the expression s by s2 . If several expressions are to be


substituted simultaneously, use subs(s,{x1 ,x2 ,· · · ,xn },{y1 ,y2 ,· · · ,yn })

rewrite(s,fun) Rewrites expression s, where fun is the way to rewrite the expression, with
options such as trigonometric functions 'sin' (sine only), 'sincos' (sine
and cosine), 'cos' (cosine only) and 'tan' (tangent only); also 'exp',
'sqrt', 'log', 'heaviside' and 'piecewise' and so on

 Example 2.34
If x is real, rewrite function y = |2x2 − 3| + |4x − 5| into a piecewise one.
Solutions The original function can be expressed in MATLAB directly. Then function
rewrite() can be called, with the 'piecewise' option, to convert the original function
into a piecewise one.
>> syms x real; y(x)=abs(2*x^2-3)+abs(4*x-5);
y1=rewrite(y,'piecewise') % convert the function into a piecewise one
The piecewise function obtained is

⎨ 2x2 + 4x − 8, 5/4 ≤ x
y1 (x) = 2x2 − 4x + 2, x ≤ 5/4 and 0 ≤ 2x2 − 3

−2x2 − 4x + 8, x ≤ 5/4 and 2x2 − 3 ≤ 0.

 Example 2.35
Consider the polynomial P(s) = (s + 3)2 (s2 + 3s + 2)(s3 + 12s2 + 48s + 64). Expand the
polynomial, and also factorize the polynomial.
Solutions The polynomial can be expressed first under the symbolic framework, then
expand and factorize the polynomial.
>> syms s z;
P=(s+3)^2*(s^2+3*s+2)*(s^3+12*s^2+48*s+64); % input polynomial
F1=expand(P), F2=prod(factor(P)) % expand and factorize
The results obtained are F1 = s7 + 21s6 + 185s5 + 883s4 + 2454s3 + 3944s2 + 3360s + 1152,
F2 = (s + 1)(s + 2)(s + 3)2 (s + 4)3 . 
2.5 · File Processing in MATLAB
47 2

 Example 2.36
Consider polynomial P(s) in Example 2.35, use s = (z − 1)/(z + 1) to perform bilinear
transform and simplify the result.
Solutions The following commands can be used to carry out directly bilinear transform,
and find its simplest form.
>> syms s z;
P=(s+3)^2*(s^2+3*s+2)*(s^3+12*s^2+48*s+64); % input polynomial
P1=simplify(subs(P,s,(z-1)/(z+1)))) % variable substitution


 Example 2.37
Symbolic function can also be expressed by the function in MATLAB. Use symbolic func-
tion data type to carry out variable substitution for the problem in Example 2.35.
Solutions The following commands can also be used to solve the variable substitution
problem, and the results are identical.
>> syms s z;
P(s)=(s+3)^2*(s^2+3*s+2)*(s^3+12*s^2+48*s+64); % symbolic function
P1=simplify(P((z-1)/(z+1))) % variable substitution


2.5 File Processing in MATLAB


MATLAB workspace is the field where MATLAB actions take place. In the oper-
ating process, all the variables are stored in MATLAB workspace. The users can
set up the relationship between MATLAB workspace and files. That is to save the
results to the files or retrieve from file the variables. In this section, the information
exchange between MATLAB workspace and file, MATLAB and Microsoft Excel
files is illustrated. The low-level operating commands in MATLAB are presented.

2.5.1 Assessing MATLAB Workspace Variables


A pair of commands, save and load, is provided in MATLAB which saves variables
in MATLAB workspace to files, and load variables in files to MATLAB workspace.
The syntaxes of the functions are
save file_name var_list, load file_name
where var_list is the variable names to be saved, separated by spaces. The variables
can be saved into the specified file_name. If suffix is given in file_name, the name is
used directly, otherwise, the default .mat is added automatically. The default saving
format is binary. Command load loads file into MATLAB workspace. If readable
form is expected to store the variables, the option -ascii can be used in the save
command. If no file name is used in save or load commands, the default file name
is matlab.mat.
48 Chapter 2 · Essentials in MATLAB Programming

2.5.2 File Read and Write Functions


A great amount of low-level commands is provided in MATLAB, to perform file
read and write tasks. Some of the commonly used ones are listed in . Table 2.8. It
2 can be seen that the low-level commands led by f are very similar to their C language
counterparts.

 Example 2.38
Write a simple program to display the source code in a file.
Solutions A standard file name dialog box can be called to select a *.m file. Then while
loop is used to read the file line by line, and function disp() displays the source code, until
the end of the file. After reading the file, the loop is completed automatically, and the file
is closed. Loop structure and application will be presented later in 7 Chap. 3.
>> [f,p]=uigetfile('*.m'); % open a dialog box to select file
ff=[p,f]; h=fopen(ff,'r'); % open file as a read-only one
while ~feof(h), str=fgetl(h); disp(str); end % read in a line and display
key=fclose(h); % close the file


. Table 2.8 File read and write functions

Functions Descriptions

[f ,p]=uigetfile(spec) Opens a standard file dialog box, such that a file name can be chosen.
spec is the file name filter. For instance, use '*.m,*.slx'. The
returned f ,p are strings, for file name and path name. The absolute file
name is [p,f ]

h =fopen(fname,opt) Opens the file and the handle is passed to h. The argument opt is the
file type, optional ones are 'r' (read only), 'n' (new), 'w' (new,
when exists, overwrite it) and so on

str=fgetl(h) Gets one line of information in string str, from handle h

key=fclose(h) Closes file h, with returned key as 0 or 1, indicating whether close file is
successful or not

key=feof(h) Checks whether the end of the file is reached, with key as 0 or 1

fprintf(h,format,vars) Writes variables to file h. Refer to sprintf() in . Table 2.6 for


format

Other low-level ones MATLAB also supports other low-level file manipulating functions
such as ferror(), fscanf(), frewind(), fread(), fseek(),
ftell(), fwrite() and so on. Check online help for details
2.5 · File Processing in MATLAB
49 2
2.5.3 Assessing Microsoft Excel Files
MATLAB provides a function xlsread(), and it extracts data from a Microsoft
Excel file, with the syntax
[N,TXT,RAW]=xlsread(file name,sheet,range)
where sheet is the sheet number in Excel file. If it is not provided, default 1 can be
used. Range is a string, indicating the range in Excel cells. For instance, to load from
Column B to Column F in an Excel file, and Line 3 to Line 20, the range can be
set to 'B3:F20'. The values in the range can be returned in a numeric matrix N. If
necessary, other arguments can be returned. For instance, text format of each Excel
cells is returned in variable TXT, while original information in the Excel can be returned
in RAW.
Function xlrwrite() writes MATLAB workspace variables directly into an Excel
file, with the syntax
xlswrite(file name,variable,sheet,range)
where variable is the variable name to be written. It can be a matrix or even two-
dimensional cell array. The definitions of sheet and range are the same as the ones
discussed above. Besides, if the range is set to 'A1', it means to write the file starting
from the upper-left corner cell. If C2 is used, it means to write Excel files starting from
Column C, Line 2. If starting from the upper-left corner, the latter two arguments are
omitted.
It is worth mentioning that if the file is already opened, the xlswrite() function
call may fail. Corresponding error messages are given. Close the file first then write
to it.

 Example 2.39
The population information of a province is described in a Microsoft Excel file census.
xls. It can be seen from the Excel file that the 4th row is the header of the table, and the
actual data are in 5th to 67th rows, containing the population from 1950 to 2011. Column
B contains the year information, and Column C contains the population. Generate two
vectors in MATLAB, t and y, to store, respectively, the year and population information.
Solutions It is known from the above description that the useful information is stored in the
cells in B5:C67 in the Excel file. Therefore, the following commands load the meaningful
information into matrix X. Extracting the first and second columns, the vectors t and y
can be found.
>> X=xlsread('census.xls','B5:C67'); t=X(:,1); y=X(:,2);


 Example 2.40
Save the 2nd to the 33rd columns of a 100 × 100 magic matrix into an Excel file.
Solutions The magic matrix can be generated with the magic(). The submatrix can be
extracted, such that it can be written to the Excel file with xlswrite() function.
50 Chapter 2 · Essentials in MATLAB Programming

>> A=magic(100); A=A(:,2:33); % extract the 2nd-33rd columns from magic matrix
xlswrite('myfile.xls',A) % write the matrix into the Excel file


2
2.6 Exercises
(1) The default display format in MATLAB is loose, which has an extra blank line
before and after the display. If we do not want to have the blank lines, compact
format can be selected instead. Set compact format as the default one. If we
want to set automatically compact format each time MATLAB is launched,
how can we do that?
(2) If we want to set f:\matlab_files folder as the work path, how can we do
that?
(3) The Preferences button in the toolbar in . Fig. 2.2b allows the user to select
default fonts. Set the font of the MATLAB command window and editor to
Monospaced, bold, with font size 16pt.
(4) Find with which command the locations of all the mtimes.m files in MATLAB
search path.
(5) Simplify the expression sin(kπ + π/6) for any integer k.
(6) Compare the two numbers 231 and 321 . What are the two numbers?
(7) Judge what is the result when the commands a =5; key=isinteger(a) are
executed. What is the value of key? Why? Execute the commands on the machine
and see whether the results are the same as your expected. √ √
(8) Compute the first 200 digits for the irrational numbers 2, 11, sin 1◦ , e2 ,
6

ln(21) and log2 (e).


(9) Which of the following commands is correct for lg(12345678)?
(a) vpa(log10(sym(12345678))), (b) vpa(sym(log10(12345678)))
1 − 2 sin α cos α 1 − tanα
(10) Show the identity = .
2
cos α − sin α
2 1 + tanα
(11) Input matrices A and B
⎡ ⎤ ⎡ ⎤
1 2 3 4 1 + 4j 2 + 3j 3 + 2j 4 + 1j
⎢4 3 2 1⎥ ⎢ 4 + 1j 3 + 2j 2 + 3j 1 + 4j ⎥
A=⎢
⎣2
⎥, B = ⎢ ⎥.
3 4 1⎦ ⎣ 2 + 3j 3 + 2j 4 + 1j 1 + 4j ⎦
3 2 4 1 3 + 2j 2 + 3j 4 + 1j 1 + 4j

For the 4 × 4 matrix A, if A(5, 6) = 5 command is issued, what happens?


(12) For the matrix B in Exercise 2.6, find C = B + B T and D = B + B H . Are the
matrices C and D symmetrical ones?
(13) What is the ASCII code of backslash \? What is the ASCII code of 5? Convert
the ASCII code back to the original characters.
x sin x
(14) For the mathematical functions f (x) = and g(x) = tan x,
x + 2(x + 5)
2
compute the composite functions f (g(x)) and g(f (x)).
2.7 · Mini-Projects
51 2
(15) Double precision data structure may only preserve certain number of dig-
its. Therefore, it is not possible to achieve sufficient accuracy. Use numerical
method and symbolic method to compute C50 10 , where Cn = m!/ n!(m − n)! .
m
Function nchoosek() is also provided in MATLAB Symbolic Math Toolbox,
to solve combination problems, with the syntax nchoosek(sym(m),n).
(16) List all the negative integers larger than −100, which are divisible by 11. Find
all the positive integers in the interval [3000,5000], which are divisible by 11.
(17) Judge and explain the meaning of the commands A =magic(3); A( A>=5)=5.
(18) For the matrix B in Exercise 2.6, compute B^2, B. ∗ B and B.^2.
(19) Extract the real and imaginary parts from matrix B in Exercise 2.6, and compute
its phase.
(20) Find all the roots of four for matrix B in Exercise 2.6, and validate the results.
(21) Simplify the trigonometric function 5 cos4 α sin α − 10 cos2 α sin3 α + sin5 α.
(22) Find the locations of the letters 'a' and 'A' in the string 'Do you speak
MATLAB?'. Alter their cases.
(23) Observe and explain the command rat(sym(pi),1e-20) and the execution
result.
(24) If x and y are all positive integers. Try to find the solutions of the algebraic
equation x2 +y3 = 80893009, and validate the solutions. Is the solution obtained
unique?
(25) Save the last 50 rows of 501×501 magic matrix into the Excel file mytest1.xls.

2.7 Mini-Projects

1. Table Data Type


Many data types are supported in MATLAB. In this book, concentrations are made
on those widely used in scientific computing. In fact, there are many useful data types
in other fields. For instance, table data type. Learn to use table data type in MATLAB,
with online help facilities. Use doc table command to find help information, and
then solve the following problem.
Some parameters of the eight planets in the solar system are provided in
. Table 2.9, where the parameters are relative ones to the Earth parameters. The unit
for semimajor axis is astronomical unit (AU, which is 149597870700 m ≈ 1.5×1011 m).
The unit for rotation period is days. Use MATLAB to represent these planet param-
eters. Note that the most suitable data structure is table(), try to use this data type.
Once a table object is created, save the table into a Microsoft Excel file. If the
mass of the Earth is known, which is 5.965×1024 kg, compute the masses of the other
planets. Append them to a new column in the table, and update the Excel file.

2. Get More Information of π


It has been pointed out that the direct display of vpa() function only displays at most
32766 digits. With str=vpa(pi,n) command however, the first n digits, excluding
the decimal point, are returned to the string variable str, even though n is very large,
for instance, n = 1000000. The kth character in the string str can be retrieved with
s =str(i). Extract the 30000th to the 40000th digits from π, and count how many
3’s are there in these digits.
52 Chapter 2 · Essentials in MATLAB Programming

. Table 2.9 Parameters of the eight planets

Name of planet Relative Relative Semimajor Orbital Orbital Rotation Confirmed Rings
diameter mass axis period eccentricity period moons

2 Mercury 0.382 0.06 0.39 0.24 0.206 58.64 0 No

Venus 0.949 0.82 0.72 0.62 0.007 −243.02 0 No

Earth 1 1 1 1 0.017 1 1 No

Mars 0.532 0.11 1.52 1.88 0.093 1.03 2 No

Jupiter 11.209 317.8 5.20 11.86 0.048 0.41 69 Yes

Saturn 9.449 95.2 9.54 29.46 0.054 0.43 62 Yes

Uranus 4.007 14.6 19.22 84.01 0.047 −0.72 27 Yes

Neptune 3.883 17.2 30.06 164.8 0.009 0.67 14 Yes

Reference
1. Xue DY (2020) MATLAB programming—mathematical problem solutions[M]. De Gruyter, Berlin
53 3

MATLAB Flow Control


Structures
Contents

3.1 Loop Structures – 54


3.1.1 For Loop Structure – 54
3.1.2 While Loop Structures – 57
3.1.3 Nesting Loop Structures – 58
3.1.4 Vectorized Programming and loops – 59

3.2 Conditional Structures – 61


3.2.1 Simple Conditional Structures – 61
3.2.2 Ordinary Form of Conditional Structures – 62
3.2.3 Other Flow Control Commands – 62
3.2.4 Vectorized Computing of Piecewise Functions – 63

3.3 Switch Structures – 64

3.4 Trial Structures – 66


3.5 Exercises – 67

3.6 Mini-Projects – 70

References – 71

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_3
54 Chapter 3 · MATLAB Flow Control Structures

Interactive programming format is illustrated in the previous chapter, where sequen-


tial execution of the statements are demonstrated. The MATLAB mechanism runs
the commands line by line. In real applications, sometimes the execution order of the
commands may need to be controlled according to certain conditions. For instance,
it may need to execute a piece of code repeatedly for a certain number of times. There-
fore flow control structures should be introduced to MATLAB programming. Flow
3 control is also known as control flow, indicating the control mechanism to the execu-
tion orders in the statements. As a programming language, MATLAB supports loop
structures, conditional structures, switch structures and trial structures. In this chap-
ter, various flow control structures are presented. Vectorized programming styles are
also presented.
In 7 Sect. 3.1, two types of different loop structures are presented. Then itera-
tion methods in loop structures are discussed, and vectorized programming is also
addressed. The eventual target of vectorized programming is to replace loop structures
so as to boost the efficiency in programming. In 7 Sect. 3.2, conditional structures
are introduced. Discussions on vectorized manipulation of piecewise functions are
demonstrated, so as to replace conditional structures with high-efficiency vectorized
programming. In 7 Sects. 3.3 and 3.4, switch structure and trial structure are pre-
sented.

3.1 Loop Structures


To run a piece of code repeatedly, loop structures are needed. There are two types
of loop structures. One is to assign the number n of loop executions, and execute the
code n times. Here it is referred to as for loop. Another loop structure is conditional
loop structure. Under certain conditions, the loop is executed repeatedly. This is
referred to as while loop. The structures and programming styles of these two loops
are presented in this section. Vectorized programming style is also presented in the
section, aiming at posing a more efficient format to replace loops.

3.1.1 For Loop Structure


for loop is the most widely used loop structure in programming, with the structure
for i=v, loop body, end
Under standard for loop structure, v is a vector, and the loop variable i extracts
one element from vector v at a time, and the loop body is executed once. The control
returns to the for statement, and extracts the next element from v and executes the
loop body again. The loop body is executed repeatedly, until all the elements in v are
extracted. The loop structure is then completed automatically.
If v is a matrix, then each time, i extracts a column vector from v to execute the
loop body, until all the columns in v are extracted.
3.1 · Loop Structures
55 3

 Example 3.1

100
Consider first a simple example. Use loop structure to compute S = i.
i=1
Solutions We can consider using for loop to solve this type of problem. Assign v vector
first to a row vector [1, 2, . . . , 100]. Also assign an accumulative variable s, whose initial
value is 0. Inside the for loop, let i extracts an element from v at a time, and adds it to the
accumulative variable s. The following MATLAB program can be written and the when
the loop is completed, the accumulative sum is s = 5050.
>> s=0; for i=1:100, s=s+i; end, s % a simple loop structure
In fact, the simple command sum(1:100) solves the problem directly, and identical result
is obtained. With MATLAB function sum(), the whole vector is processed, such that the
program is much easier. 

If low-level languages such as C is used to implement loops, the statement for (i =


1; i <= 100; i++) represents the loop. The loop condition satisfies a fixed pattern,
while in MATLAB loops, vector v can be arbitrarily arranged. It can be seen that the
structure is more flexible than the C loop. An example is given next to demonstrate
the use of loops in iterative processes.

 Example 3.2
 whose first term is a1 = 3. The second term can be computed based on
Consider a sequence,
one, a2 = 1 + a1 . The subsequent terms can be computed in a recursive formula
the first 
ak+1 = 1 + ak , k = 1, 2, . . . , m. How to find a32 ?
Solutions The recursive computation process can be implemented with a process referred
to as√iterations. Iterative process is very important in computer languages.√ The notation
a = 1 + a is used in pseudocode representation, √ which really means that 1 + a ⇒ a, that
is, based on the current value of a, the value 1 + a is worked out, and the value of a is
updated. Let a = 3, and let the loop execute 31 times, the most recent value of a is found.
Loop structure solves the problem.
>> a=3; format long % initial value and display format
for k=1:31, a=sqrt(1+a); disp(a), end % iterative computing and display
It can be seen that (the display of intermediate results is omitted) the last two terms are
all 1.618033988749895. They are coinciding under double precision framework. There is
no need to continue iterating, and the process can be regarded as convergent. The final
recursive result is referred to as the golden ratio [1].
To view the sequence in a mathematical way, the first few terms are

  
√ √ √
3, 1 + 3, 1 + 1 + 3, 1 + 1 + 1 + 3, · · · .

 that√it converges to x, then it is found that


If the sequence is convergent, and assume

x = 1 + x, whose positive solution is x = 1 + 5 /2 ≈ 1.618033988749895. 
56 Chapter 3 · MATLAB Flow Control Structures

 Example 3.3
Fibonacci sequence can be obtained from the formula ak = ak−1 + ak−2 , k = 3, 4, . . .,
where the initial values are a1 = a2 = 1. Generate the first 100 terms in the Fibonacci
sequence.
Solutions It is seen from the Fibonacci sequence formula that if a vector is used to describe
the sequence, the initial values can be set to a(1) = a(2) = 1. From the third term on,
3 the recursive formula generates the first 100 terms. The MATLAB commands to generate
Fibonacci sequence are as follows:
>> a=[1 1]; for k=3:100, a(k)=a(k-1)+a(k-2); end, a(end)
It can be seen from the result that, since double precision scheme may only preserve 15
digits, the Fibonacci sequence generated above may not be very accurate. Symbolic data
type should be used instead. To adopt symbolic data type, just modify the initial terms, and
change the command to a=sym([1,1]), the accurate term a100 = 354224848179261915075
can be found. 

 Example 3.4
It was stated in Example 2.6 that, the command line display with vpa() function may only
display up to 32766 characters. How can we use MATLAB to display the first 1000000
terms for π?
Solutions Since the results cannot be displayed in a single line, it can be segmented into
several lines, with 10000 characters each. It is obvious that loop structure is useful in
segmenting the display. The char() function may convert all the 1000000 characters of π
into a string. Then the following commands display all the digits:
>> P=vpa(pi,1000000); str=char(P); n=10000; % convert to string
for i=1:n:length(str) % display line by line
disp(str(i:min(i+n-1,length(str)))); % display results with disp()
end
With the above commands, the value of π can be displayed in 101 lines. There is only one
digit in the last line. This is because the converted string has 1000001 characters, since the
decimal point generates an extra character. 

for loop preassigns a loop execution condition. The loop variable extracts all the
possible values and starts the loop structure. Therefore for loop can be regarded as
an unconditional loop. The limitations of unconditional loops are demonstrated next
in an example.

 Example 3.5
m

Find the smallest value of m satisfying S = i > 10000.
i=1
Solutions In the earlier demonstrations, m should be given first such that unconditional
loops can be used. While in this example, the value of m is unknown. Therefore the v
vector cannot be specified. Therefore, for loop cannot be used to solve the problem. An
alternative while loop is presented next. 
3.1 · Loop Structures
57 3
3.1.2 While Loop Structures
while loop is an alternative loop structure. Compared with the unconditional loop
like for loop, conditions are allowed to terminate while loops. If the
condition is not satisfied, the loop structure is completed. The typical form of while
loop is
while (condition), loop body, end
In the while loop, condition is a logical expression. If its value is true, the loop
body is executed once. Then control returns to the while command, and the condition
is rested again. If it is still true, the loop body is executed. If the condition is false,
the loop is completed. If the condition is not a logic variable, we should check whether
the condition is 0. If it is 0, the loop can be completed.
Loops can be led by for or while statements, and terminated by end statement.
All the statements in between are referred to as the loop body. The application fields
of these two types of loops are not the same. Examples are used to demonstrate the
differences and their application fields.

 Example 3.6

100
Using while loop to solve again the problem s = i.
i=1
Solutions Similar to for loop, an accumulate variable s with zero initial value can still be
used. Meanwhile, the loop variable i in for loop can be selected as an independent variable,
with initial value of 0. The while loop tests the value of i. If i ≤ 100, add i to s, and i itself is
increased by 1. Control then goes back to the while statement, and test once again whether
i ≤ 100 is satisfied. If it is, then the loop body is executed; if not, it means that all the 100
terms are already added. The loop can be completed. The above idea can be implemented
directly with the following MATLAB statements, and the sum is s = 5050, which is the
same as the one obtained earlier.
>> s=0; i=1;
while (i<=100), s=s+i; i=i+1; end, s % condition unsatisfied to terminate loop


For this particular problem, while loop is slightly more complicated than for
loop.

 Example 3.7
m

Find the smallest m such that s = i > 10000.
i=1
Solutions This problem cannot be solved with for loop, since the v vector cannot be assigned
first. To solve the problem, while loop should be used instead to find the value of m. The
idea is that, the term can be added to s one by one. Before adding the terms, we should test
whether s exceeds 10000. If s ≤ 10000, the loop continues, otherwise, stop adding terms
and complete the loop. Using the following commands, it is found that s = 10011 and
m = 141. The result can be validated with the command sum(1:m).
58 Chapter 3 · MATLAB Flow Control Structures

>> s=0; m=0; % set initial values


while (s<=10000), m=m+1; s=s+m; end, s, m % exceeds 10000 to complete loop


 Example 3.8
3 In Example 3.2, the loop was executed 32 steps to find the convergent result. If the number
of iterations is not known, find a convergent result with loop structure.
Solutions The condition to terminate loops can be assigned. If the absolute value of the
difference between the current value of a and its previous one is smaller than eps, the loop
can be terminated. In this way, while loop can be used and the result is the same as the
one in Example 3.2, where k = 32.
>> a0=4; a=3; k=0; format long % set initial value and display format
while abs(a-a0)>=eps % set terminate condition
a0=a; a=sqrt(1+a0); k=k+1; disp(a) % iterating and display results
end, k % complete loop and show iteration steps


 Example 3.9
Let us revisit the source code display program in Example 2.38. For convenience, the code
is presented again here. If while loop is learnt, it is much easier to understand the code.
The main body of the program is composed of the while loop. The terminating condition
is ~feof(h), meaning the end of the file is not reached. Function fgetl() reads in a line
from the file, until the end of the file is reached.
>> [f,p]=uigetfile('*.m'); % open file dialog box to select file
ff=[p,f]; h=fopen(ff,'r'); % open file in read-only format
while ~feof(h), str=fgetl(h); disp(str); end % display source code
key=fclose(h); % close the file


3.1.3 Nesting Loop Structures


Similar to other programming languages, loop structures can be nested. That is, a
loop can be embedded into another loop. Note that, each loop is led by for or
while statement, and there must be a matching end statement to terminate the loop.
Otherwise, MATLAB mechanism displays error messages. Of course, with such a
format, multiple loop structures can be generated. Other types of control structures
can be embedded in loops, or vice versa. The following example demonstrates the
nested loop structures.

 Example 3.10
Hilbert matrix is a commonly used test matrix, whose general term is hij = 1/(i + j − 1),
i = 1, 2, . . . , n, j = 1, 2, . . . , m. Use loop structure to generate a 4 × 6 Hilbert matrix.
3.1 · Loop Structures
59 3
Solutions Double loops can be used, that is, inner loop is embedded in the outer loop.
Therefore, Hilbert matrix can be generated in the following nested loops:
>> n=4; m=6; % assign the number of rows and columns, the implement double loops
for i=1:n, for j=1:m, H(i,j)=1/(i+j-1); end, end, H
The generated Hilbert matrix is
⎡ ⎤
1 0.5 0.3333 0.25 0.2 0.1667
⎢ 0.5 0.3333 0.25 0.2 0.1667 0.1429 ⎥

H =⎣ ⎥.
0.3333 0.25 0.2 0.1667 0.1429 0.125 ⎦
0.25 0.2 0.1667 0.1429 0.125 0.1111

3.1.4 Vectorized Programming and loops


In MATLAB programs, the execution of loops is relatively slow. Therefore, if oper-
ations can be made on the entire matrices or vectors, vectorized programming can be
adopted, to avoid loop structures. The efficiency of vectorized programming style is
usually higher.
Vectorized programming is an attractive topic in MATLAB programming. Vec-
torized programming makes MATLAB code look pretty and neat, while programs
with too many unnecessary loops are usually regarded as poor implementations by
professionals. Examples are given next to show the differences between loop and
vectorized programming styles.

 Example 3.11
Assume that there is a set of circles, with radii r = 1.0, 1.2, 0.9, 0.7, 0.85, 0.9, 1.12, 0.56, 0.98,
respectively. Compute the areas of these circles.
Solutions The area formula is S = πr2 . For this problem, the beginner in MATLAB, who
has already some experience in C language, may write the following commands:
>> r=[1.0,1.2,0.9,0.7,0.85,0.9,1.12,0.56,0.98];
for i=1:length(r), S(i)=pi*r(i)^2; end, S % compute the area one by one
The commands compute correctly the areas, but this is not a decent MATLAB program.
If vectorized programming style is used, the entire loop structure above can be replaced by
the following command. The results are exactly the same, but the program is much prettier.
>> S=pi*r.^2 % vectorized programming to avoid loop


 Example 3.12
 

10000000 1 1
Solve the series sum problem s = + .
i=1 2i 3i
Solutions For this particular problem, the loops in Example 3.1 can be used directly. The
sum obtained is 1.5 and time elapse is 2.079 s.
60 Chapter 3 · MATLAB Flow Control Structures

>> N=10000000;
tic, s=0; for i=1:N, s=s+1/2^i+1/3^i; end; toc % with loop
If an i vector is generated, then 1/2 i expression can be evaluated in dot operation
1./2.^i. It is again a vector. Similarly the mathematical expression 1/3 i can be speci-
fied as a vector 1./3.^i. Adding up all the terms of 1./2.^i+1./3.^i vector, function
sum() avoids loop. With vectorized programming, the same solution can be found, and the
3 time elapse is reduced to 0.566 s.
>> tic, i=1:N; s=sum(1./2.^i+1./3.^i); toc % vectorized sum
For this particular example, the efficiency of vectorized programming is apparently
higher than the loop structure. In fact, the efficiency in recent versions of MATLAB has
already been increased significantly. If the two methods are compared under the old ver-
sions, the differences are even bigger. 

 Example 3.13
Function meshgrid() provided in MATLAB generates 2D or even 3D mesh grids. Observe
the format of the mesh grid matrices generated by the function.
Solutions Assume that the horizontal coordinates are selected as v 1 = [1, 2, 4, 3, 5, 7, 9],
and vertical coordinates are v 2 = [−1, 0, 2], then the following commands can be issued,
such that two mesh grid matrices are generated.
>> v1=[1 2 3 4 5 7 9]; v2=[-1 0 2]; % horizontal and vertical axes
[x,y]=meshgrid(v1,v2) % generate and display mesh grid matrices
The two mesh grid matrices are generated as follows:
⎡ ⎤ ⎡ ⎤
1 2 4 3 5 7 9 −1 −1 −1 −1 −1 −1 −1
x = ⎣1 2 4 3 5 7 9⎦, y = ⎣ 0 0 0 0 0 0 0⎦.
1 2 4 3 5 7 9 2 2 2 2 2 2 2

It can be seen that the two matrices can be used together to describe the coordinates on
each mesh grid points. 

 Example 3.14
The creation of Hilbert matrices is demonstrated in Example 3.10. If we want to generate
a 50000 × 50 large-scale Hilbert matrix, how to input it?
Solutions It is observed that double loops can be used to generate the expected matrix, and
the time elapse is 35.52 s.
>> tic, for i=1:50000, for j=1:50, H(i,j)=1/(i+j-1); end, end, toc
Now consider generating a 50000×500 matrix. The above method is too time-consuming,
such that the matrix cannot be generated in this way. If the order of the two loops is swapped,
that is to move the larger loop to the inner one, the time elapse is reduced to 0.334 s. It can
be seen that if the larger loop is swapped to the inner one, the efficiency can be boosted
significantly.
>> tic % move larger loop to the inner layer
for j=1:500, for i=1:50000, H1(i,j)=1/(i+j-1); end, end, toc
3.2 · Conditional Structures
61 3
If the inner loop is substituted by vectorized method, the time elapse is further reduced
to 0.26 s.
>> tic, for j=1:500, i=1:50000; H2(i,j)=1./(i+j-1); end, toc
Function meshgrid() generates mesh grid matrices. Then vectorized programming is
used to replace the double loops. The time elapse is reduced to 0.16 s. Compared with loops,
the cost of using vectorized programming style is that two additional large-scale matrices
are generated.
>> tic, [i,j]=meshgrid(1:50000,1:500); H3=1./(i+j-1); toc


 Example 3.15
If x and y are positive integers, solve the algebraic equation x2 + y3 = 80893009, and
validate the solutions. Besides, are the solutions unique? (Exercise (24), Chap 2)
Solutions To solve certain problems, sometimes nonconventional viewpoints can be tried,
such that easy method finds the solutions. If√positive integers are involved, even if y is
1,
√ the maximum value of x may not exceed 80893009. Meanwhile, y does not exceed
3
80893009. With meshgrid() function, all the possible combinations of x and y can be
generated. It is concluded that the solution is x = 521 and y = 432, which is the solution
to the equation, and it is in fact the unique solution.
>> N=80893009; [x y]=meshgrid(1:sqrt(N),1:N^(1/3)); % generate all possibilities
K=x.^2+y.^3; ij=find(K==N); % find all combinations satisfying the equations
x=x(ij), y=y(ij), x.^2+y.^3-N % validate the solution


3.2 Conditional Structures


Conditional structure is a commonly used structure in programming languages. Nor-
mally conditional structure determines which branch to execute depending on the
conditions. Under different conditions, different tasks are undertaken. The simplest
conditional structure in MATLAB is the if · · · end structure. It can be extended with
the help of else and elseif statements. In this section, various conditional structures
are presented, and examples are used to explore its applications.

3.2.1 Simple Conditional Structures


The simplest conditional structure is
if (condition), statements, end
where condition is a logic expression. The physical explanation of the conditional
structure is, if the condition is true, the statements are executed, and the structure is
completed. Otherwise, the structure is bypassed.
62 Chapter 3 · MATLAB Flow Control Structures

Another simple conditional structure is


if (condition), statements 1, else, statements 2, end
Similar to the simplest conditional structure, if condition is true, the statements 1
are executed, and the structure is completed. If the condition is not true, the statements
2 are executed, and the structure is completed.

3
3.2.2 Ordinary Form of Conditional Structures
Apart from the simple conditional structures, general conditional structures are also
supported. The corresponding structures are
if (condition 1) % if condition 1 is satisfied, run statements 1
statements 1 % lower-level if or other structures can be embedded
elseif (condition 2) % otherwise, if condition 2 is satisfied, run statements 2
statements 2
..
. % many such conditional branches can be used
else % if none of the above conditions are satisfied
statements n + 1
end

3.2.3 Other Flow Control Commands


For loop structures, apart from for and while structures, the statements such as
break and continue are also very useful. Statement break terminates the current
loop structure, and continue statement bypasses the remaining part of the loop
body, and passes control to the for or while statement. These statements can be used
together with if or other control structures to make powerful and flexible control
structures. An example is used next to demonstrate the use of break statement.

 Example 3.16
Solve again the problem in Example 3.7 using for and if statements.
Solutions It was stated in Example 3.7 that the problem cannot be solved by merely using
for loop alone. It can only be solved by the use of if structure. The specific idea is that
let the loop variable m vary in a very large range under for loop, and accumulated to
the variable s. Then test whether the sum is larger than 10000. If not, continue the loop,
otherwise, run break statement to terminate the loop. The expected solutions are then
found. The MATLAB commands for the problem are given below:
>> s=0; for m=1:10000, s=s+m; if s>10000, s, m, break; end, end
It can be seen that for this particular example, the statement structure is rather compli-
cated. The while loop is more straightforward and flexible. 
3.2 · Conditional Structures
63 3
3.2.4 Vectorized Computing of Piecewise Functions
Consider the typical piecewise function with one independent variable.

f1 (x), x ≥ 2
y = f (x) =
f2 (x), otherwise.

If the independent variable x is a vector x composed of some samples, how to


evaluate the corresponding y vector? For the users with C language experience, it is
quite natural to use loop structure to process each value xi individually. Inside the
loop, if statement is used to evaluate the piecewise function values.
In fact, if you understand the meaning of the statement x >= 2, a more concise
way can be adopted to process the piecewise function. The statement x >= 2 gener-
ates a logical vector of the same length of x. For a certain i, if xi satisfies xi ≥ 2,
the corresponding value in the logical vector is 1, otherwise it is 0. Besides, the
mathematical representation of otherwise in the formula should be explicitly indi-
cated, that is, x < 2. The two conditions can be regarded as two elements, if one
of them is true, the other is false. This kind of relationship is referred to as mutual
exclusive.
With the mutual exclusive logical conditions, vectorized method can be used to
work out the piecewise function values:
y=f1 (x).*(x >= 2) + f2 (x).*(x < 2)
The benefit of doing this is to avoid low-level loop and conditional structures, and
find the results in a more efficient way. Dot operations are actually used in comput-
ing directly the piecewise functions. This method can also be used in the evaluations
of piecewise functions with more independent variables. Before the computing com-
mands are activated, the mutual exclusive logical expressions must be established,
otherwise misleading results may be obtained.
Besides, the function piecewise() provided in the MATLAB Symbolic Math
Toolbox computes piecewise functions under symbolic framework. The syntax of the
function is
f =piecewise(condition 1,function 1,condition 2,function 2,· · · )
where condition i is the ith while function i is the ith corresponding function. When
using such a function, make sure that the conditions and functions are specified in
pairs, otherwise error messages are given.

 Example 3.17

1.1 sign(x), |x| > 1.1
Express the saturation function y =
x, |x| ≤ 1.1.
Solutions Condition |x| ≤ 1.1 can alternatively be expressed as −1.1 ≤ x ≤ 1.1, which
can be understood as x ≥ −1.1 and x ≤ 1.1. The corresponding symbolic expression is
x >= -1.1 & x <= 1.1.
If sample vector x is given, dot operations can be used to evaluate the function y, with
the following statement:
>> x=-2:0.01:2; y=1.1*sign(x).*(abs(x)>1.1)+x.*(abs(x)<=1.1);
64 Chapter 3 · MATLAB Flow Control Structures

The piecewise function can also be described under symbolic framework:


>> syms x % declare symbolic variable and define piecewise function
f(x)=piecewise(abs(x)>1.1,1.1*sign(x),abs(x)<=1.1,x);


The vectorized method presented here also applies to process piecewise functions
3 with two or more independent variables. A 2D piecewise function is given next for
demonstration.

 Example 3.18
Assume that a joint probability density function is given as a piecewise function [2]


⎪ −0.75x22 −3.75x12 −1.5x1
, x1 + x 2 > 1
⎨ 0.5457e
0.7575e−x2 −6x1 ,
2 2
p(x1 , x2 ) = −1 < x1 + x2  1


⎩ 0.5457e−0.75x22 −3.75x12 +1.5x1 , x + x  −1.
1 2

Generate mesh grids in the range −2 ≤ x, y ≤ 2, and compute the function values at the
mesh grid points.
Solutions Of course, double loops work out this piecewise function. A simpler and more
concise way is to use vectorized method, so that loops can be avoided. Although for such a
small-scaled problem, there is no necessity in considering the time-consumption problem,
the program structure thus generated looks prettier.
>> [x1,x2]=meshgrid(-2:0.1:2); % generate mesh grid matrices
p=0.5457*exp(-0.75*x2.^2-3.75*x1.^2-1.5*x1).*(x1+x2>1)+...
0.7575*exp(-x2.^2-6*x1.^2).*(-1<x1+x2 & x1+x2<=1)+...
0.5457*exp(-0.75*x2.^2-3.75*x1.^2+1.5*x1).*(x1+x2<=-1);


3.3 Switch Structures


Switch structure is an important flow control structure in programming. Its actions
are similar to the multi-port switch in a real-life circuit. If the switch is dialed to one
of locations in the switch, the corresponding loop is turned on, but the other loops
are turned off.
The switch structure can also be implemented with if, elseif, end structure.
For instance, the following commands can be used:
if key == expr.1, statements 1;
elseif key == expr. 2, statements 2; · · · , end
However, the readability of the code under such a structure is always regarded
poor. Therefore, switch structures can be introduced instead. The typical form of a
switch structure is
3.3 · Switch Structures
65 3
switch expression
case expression 1, statements 1
case {expression 2,expression 3,· · · ,expression m}, statements 2
..
.
otherwise, statements n
end
where the key point is the judgement upon the expression. If it equals to a certain
expression in a case, the corresponding statements after the case are executed. After
that the switch structure is completed.
Care must be taken in the following for cases:
(1) If expression is the same as expression 1, statements 1 can be executed. After that
it is jump out of the switch structure. This is different from the case in C language,
where the next case statement is executed. To implement this, a break command
should be appended to the statements in C.
(2) When testing whether expression is the same as one of the several expressions,
these expressions must be delimited with curly brackets, which is the cell array.
(3) If none of the enumerated expressions is satisfied, the statements in otherwise
part are executed. The keyword is default in C language.
(4) The results of the program are dependent on the orders of the case statements.
If two or more case statements contain the same expression, then the first case is
executed. Therefore, repeated expressions should not be used in case statements,
otherwise, the statements listed behind are never executed.
It can be seen that switch structures and conditional structures are essentially all
conditional structures. If certain conditions are satisfied, the controls are passed to
certain statements. What are the differences between conditional and switch struc-
tures? It can be seen that conditional structures may use inequalities as conditions,
such as if x > 0, therefore it is considered as continuous conditions. In switch cases,
the conditions can be considered as enumerate discrete points. Therefore the appli-
cation fields of the two structures are different.

 Example 3.19
Write a program to compute the perimeter, area and volume of a circle (sphere).
Solutions The input() function in 7 Chap. 2 accepts the radius. Then function menu()
sets up a menu, enables the user to select a task—to compute perimeter, area or volume.
Based on the selected key variable, the switch structure is used to carry out computation.
Since dot operations are used in the program, the relevant information of a group of circles
(spheres) can be computed simultaneously.
>> r=input('input radius r='); % input the radius, which accepts a vector
key=menu('Select a task','perimeter','area','volume');
switch key % based on the selection key, complete task
case 1, Result=2*pi*r % compute perimeter with l = 2πr
case 2, Result=pi*r.^2 % compute area with S = πr2
66 Chapter 3 · MATLAB Flow Control Structures

case 3, Result=4*pi*r.^3/3 % compute volume with V = 4πr3 /3


end


3.4 Trial Structures


3
A trial structure is supported in MATLAB, whose syntax is
try, statements 1, catch, statements 2, end
In this program structure, the paragraph statements 1 is executed first. If an error
has occurred in the execution, all the remaining statements are bypassed, and the
control is passed to the catch clause, so that statements 2 are executed instead.
The error message is assigned to the lasterr variable. If there is nothing wrong
in executing statements 1, the whole structure is then completed.
Trial structure is very practical in real programming. For instance, if there are two
algorithms to solve a certain problem, one is very efficient but sometime not quite
reliable, the other one is reliable but it is extremely very slow. The efficient algorithm
can be placed under the try clause, and the slow one is placed under the catch clause.
In this way, the reliability of the problem can be ensured, and if the try clause works,
the high efficiency can be adopted. An alternative application of the trial structure is
when writing a universal program, the code can be embedded in the try clause, when
an error happens, the catch clause can be written to explain the reason for the errors.
Besides, trial structure can also be used in setting and processing error traps.

 Example 3.20
If there is a variable a in MATLAB workspace, check whether it is a number.
Solutions There are two possible cases for representing a number in a. One is to use double
precision, while the other is in symbolic expression. Function isnumeric(a) recognizes
a in the first case, while if a is a symbolic expression, even if it is a number, for instance,
sqrt(sym(2)), the isnumeric() function still returns 0. Therefore with isnumeric(),
numbers cannot be properly detected.
To solve this problem, a MATLAB function can be written. Details on MATLAB func-
tions are fully presented in 7 Chap. 4. The data type of a is extracted first. If it is double
precision one, set key to 1 and complete the program. If a is a symbolic variable, try to
convert it into a double precision data type. If the conversion is successful, set key to 1,
then complete the program. Otherwise, when a is not a number, after double() function
call, an error appears. Then the control is passed to the? catch clause, and set key to 0. If
a is not of the two cases, set key to 0.
function key=isnumber(a)
switch class(a) % extract the data type
case 'double', key=1; % if in double precision, set key to 1
case 'sym', try, double(a); key=1; catch, key=0; end
otherwise, key=0; % otherwise set key to 0
end, end
3.5 · Exercises
67 3
The key step here is the use of double() function, on the conversion to double precision
variables. Sometimes the conversion fails. Why? The symbolic variable a is not a number.
Therefore double() function produces an error, and try clause is terminated. The control
is passed to the catch clause, and set key to 0, indicating that a is not a number. 

3.5 Exercises
(1) Generate a 100 × 100 magic matrix. Use loop and vectorized programming to
find all the elements larger than 1000, and set them to 0.
(2) In Example 3.2, the steps in the loop are fixed to 31. Assume that a terminate
condition is set such that when the difference between two consecutive values of
a is small enough. For instance, let the allowed difference is 10−10 , implement
the idea in MATLAB.
(3) Use loop structure to find all the prime numbers smaller than 1000, with low-
level commands. If loops are not used, is there any other methods to use?
(4) In the above description, v vector is used in the for loop. If v is a matrix, analyze
the following statement and observe the results. Explain the execution process
if v is a matrix.
>> A=magic(9) % generate a magic matrix
for i=A, i, end
(5) Generate a multidimensional pseudorandom array with A=rand(3,4,5,6,7,
8,9,10,11). How many random numbers generated? What is the mean for all
the random numbers?

63
(6) Compute with numerical method S = 2i = 1 + 2 + 4 + 8 + · · · + 262 + 263 . If
i=0
loop structure is not used, find the sum again. Since double data type is used,
the result is not quite accurate. Find accurate result under symbolic framework.
(7) Construct the root expression.
 
  
   
    
   √

f (x) = x + x + x + x + x + x + x.

If the number of roots increased to 30, compute the expression again.


(8) If f (x) = x2 − x − 1, compute F (x) = f (f (f (f (f (f (f (f (f (f (x)))))))))). If the
result is a polynomial, what is the highest degree? Since the results are too long, it
cannot be displayed in conventional methods. Refer to Example 3.4, display all
the results with loop structure. Note that the vpa() function should be skipped,
instead, use directly char() command to convert the result into a string.
(9) For a given n, generate the following matrix:
68 Chapter 3 · MATLAB Flow Control Structures

⎡ ⎤
1 −2 4 ··· (−2)n−1
⎢0 1 −2 ··· (−2)n−2 ⎥
⎢ ⎥
⎢ ··· (−2)n−3 ⎥
A = ⎢0 0 1 ⎥.
⎢. .. .. .. .. ⎥
⎣ .. . . . . ⎦
0 0 0 ··· 1
 
3 (10) For an iterative sequence xn+1 = xn /2 + 3/ 2xn , x0 = 1, assume that if n is
large enough, the sequence tends to a fixed number. Select a suitable n, such
that the convergent sequence can be reached (the accuracy request is 10−14 ).
Find its accurate mathematical expression.
(11) In an n × n Pascal matrix, assume that all the elements in its first row and first
column are 1’s. The other elements can be computed with

pi,j = pi,j−1 + pi−1,j , i = 2, 3, . . . , n, j = 2, 3, . . . , n.

Write a piece of code to generate Pascal matrix of any size. Compare the results
with pascal() function, and validate its accuracy and efficiency.
(12) Slightly change the orders of the statements in Example 3.7. Are the new results
the same as the ones obtained in the original problem? Why?
>> s=0; m=1; % set initial values
while (s<=10000), s=s+m; m=m+1; end, s, m % stop if sum>10000
(13) For the iterative formulas xk+1 = (xk + 2/xk )/2, select an initial value x0 and
assign a terminative condition, observe the iterative formula, and see what is
the convergent value.
(14) It is known that arctan x = x − x3 /3 + x5 /5 − x7 /7 + · · · . Let x = 1, the
following formula can be derived:
 
1 1 1 1 1
π≈4 1− + − + − + ··· .
3 5 7 9 11

Use the recursive formula to find the approximate value of π, such that the
convergent condition is 10−6 .
(15) The following formula finds the approximate value of π. If the factor satisfies
|δ − 1| < , the loop can be completed. Select an error tolerance of  = 10−15 ,
find the accuracy of π value, and assess the method. Compare the efficiency of
this method and the method in Exercise (14).

  
√ √ √
2 2 2+ 2 2+ 2+ 2
≈ · · ··· .
π 2 2 2

(16) Matrix sinusoidal function is expressed as a power series function


 A2k+1 1 1
sin A = (−1)k = A − A3 + A5 + · · · . (3.1)
(2k + 1)! 3! 5!
k=0
3.5 · Exercises
69 3
Use approximation method to evaluate matrix sinusoidal function for a given
square matrix. If the norm of the accumulative term is less than 10−10 , the loop
can be terminated. Note that a test matrix A=magic(5) can be used, and the
result can be compared with the result of command funm( A,@sin).
∞ 
 
(17) Compute S = 1 + 2/n2 . The loop is terminated if the error is smaller than
n=1
 = 10−12 .

10
(18) For the polynomial (xk + 2k), find its expanded form.
k=1
k
(19) For the product of a sequence, if the general term is ak = (x + k)(−1) , find
a1 a2 . . . a40 .
(20) Find the first 300 terms of the generalized Fibonacci sequence, where T (n) =
T (n − 1) + T (n − 2) + T (n − 3), n = 4, 5, · · · , and the initial values are T (1) =
T (2) = T (3) = 1.
(21) Implement coin-tossing experiment in MATLAB. Toss the coins for 100000
times, find the face up probability with the computer experiment. Note that,
since the probabilities for face up and face down are the same, 100000 pseudo-
random numbers uniformly distributed in the [0,1] interval can be generated.
Count how many of the numbers are greater than 0.5, which can be defined
as “face up”. The probability where the random number is exactly 0.5 can be
completely ignored.
(22) The fractal tree model is: Select an initial point on a plane, (x0 , y0 ). Assume that
there is a set of pseudorandom numbers γi uniformly distributed in the interval
[0, 1]. Depending on its values, the next coordinate can be found (x1 , y1 ) [3].


⎪ x1 = 0, y1 = y0 /2, γi < 0.05

x1 = 0.42(x0 −y0 ), y1 = 0.2 + 0.42(x0 +y0 ), 0.05 ≤ γi < 0.45
(x1 , y1 ) ⇐

⎪ = 0.42(x0 +y0 ), y1 = 0.2 − 0.42(x0 −y0 ), 0.45 ≤ γi < 0.85

= 0.1x0 , y1 = 0.2 + 0.1y0 , otherwise.

Generate a set of coordinates. Can we implement the recursive computation


with vectorized methods? Why?
(23) Monte Carlo method is a commonly used statistical experiment method. Con-
sider in a square with side length of 1. Through N uniformly distributed random
points into the square. If N is large enough, the value of π can be approximated
with π ≈ 4N1 /N, where N1 is the number of points fall into the quarter cir-
cle inside the square. Select different values of N, and compute the values of
approximated π. Note that the reference statements for Monte Carlo method
are given below for reference:
>> N=100000; x=rand(1,N); y=rand(1,N);
i=(x.^2+y.^2)<=1; N1=nnz(i); p=N1/N*4
(24) A random integer square matrix can be generated with A=randi([am ,aM ],n)
command. Find a 4 × 4 square matrix whose element range is −8 ∼ 8, such
that its determinant is 1. Is it possible to find a complex matrix? Note that: the
determinant of a matrix can be evaluated with det(). To ensure accuracy for
such small-scale matrices, symbolic manipulation is suggested.
70 Chapter 3 · MATLAB Flow Control Structures

(25) Use loops to solve again the equation in Example 3.15 and compare the effi-
ciency.
(26) For a number with three digits, if the cubic sum of the three digits happens to
be the number, the number is referred to as a narcissus number. Find all the
narcissus numbers. If loops are not used, how many other methods find the
narcissus numbers?
3 (27) The judgement method in Example 3.20 has a bug, since only double precision
and symbolic data types are considered. If a is of data types single or uint8,
it can still be a number, but the code in the example may return 0. Fix the bug
such that all these data types can be handled correctly. Is there a more concise
solution for the problem?

3.6 Mini-Projects

1. Understanding Vectorized Computing


Lagrange interpolation algorithm is an algorithm often introduced in interpolation
textbooks [4]. For a given set of points xi and yi , the interpolation on x vector can be
evaluated from
m m
x − xj
φ(x) = yi .
(xi − xj )
i=1 j=1,j =i

Write a low-level MATLAB code to implement Lagrange algorithm.


Note that, sometimes, low-level loops can be substituted by vectorized program-
ming. A piece of code is listed below for you reference. Try to understand the vector-
ized programming style from the code.
>> ii=1:length(x0); y=zeros(size(x)); % generate initial vectors
for i=ii, ij=find(ii~=i); y1=1; % remove current points
for j=1:length(ij), y1=y1.*(x-x0(ij(j))); end % multiply
y=y+y1*y0(i)/prod(x0(i)-x0(ij)); % handling outer loop
end

2. Visiting Optimization Problems for the First Time


An overview and detailed studies on optimization will be presented later in 7 Chap.
11. Here an example is given, and low-level programming is expected to solve the
problem.
It is known that in MATLAB, a solver fminsearch() is provided in solving
optimization problems. The use of the function is demonstrated next.
Consider a simple optimization problem with one variable, f (x) = x sin(10πx)+2,
the solution can be found with the following procedures:

(1) Use anonymous function f =@(x)x.*sin(10*pi*x)+2 for the function.


(2) From an initial search point x0 , find a solution with x=fminsearch(f ,x0 ).
References
71 3
Unfortunately, it is always complained that the solver fminsearch() may lead to
local minimum solutions, if x0 is not selected properly.
The following ideas are conceived.

(1) Divide evenly the interested interval x ∈ (−1, 2) into 40 subintervals.


(2) Use a point in each subinterval to call fminsearch() function, with the flow
chart in . Fig. 3.1.

Implement the above idea with MATLAB and see whether you can find the global
optimum solutions of the original problem. If possible, please extend your function
into a global optimal solution search program, for multivariate problems y = f (x).

References
1. Molor CB (2013) Experiment with MATLAB[M]. BUAA Press, Beijing
2. Atherton DP, Xue D (1991) The analysis of feedback systems with piecewise linear nonlinearities when
subjected to Gaussian inputs[M]. In: Kozin F, Ono T (eds) Systems and control, topics on theory and
application. Mita Press, Tokyo, pp 23−38
3. Xue DY, Chen YQ (2008) Solving applied mathematical problems with MATLAB[M]. CRC Press,
Boca Raton
4. Xue DY, Chen YQ (2016) Scientific computing with MATLAB[M], 2nd edn. CRC Press, Boca Raton

start

with 40 initial points

let = 100

loop complete, output global


take an 0 from loop end
optimal and minimized

call fminsearch() with initial


0 , return optimized 1 1

compare 1 and . if 1 and


−1 ≤ 2, let = 1 , and = 1

. Fig. 3.1 Flow chart for finding global optimal problems with random initial values
73 4

MATLAB Functions
Programming
Contents

4.1 MATLAB Script Files – 74


4.1.1 MATLAB Editor – 74
4.1.2 MATLAB Live Editor – 75

4.2 Fundamental Structures of MATLAB Functions – 77


4.2.1 Why MATLAB Functions? – 78
4.2.2 MATLAB Function Structures – 78
4.2.3 Naming Regulations of MATLAB Functions – 79
4.2.4 Numbers of Input and Output Arguments – 80
4.2.5 Input Arguments Validation – 81
4.2.6 Recursive Structures – 83
4.2.7 Anonymous Functions – 85

4.3 Variable Transfers in Functions – 87


4.3.1 Extractions of Arguments – 87
4.3.2 Local and Global Variables – 89
4.3.3 Accessing MATLAB Workspace Variables – 90

4.4 Debugging in MATLAB Functions – 90


4.4.1 MATLAB Function Debugging – 91
4.4.2 Pseudocode Technique – 92

4.5 Exercises – 93

4.6 Mini-Projects – 96

Reference – 97

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_4
74 Chapter 4 · MATLAB Functions Programming

The MATLAB code discussed in the previous chapters are all interactive ones. If a set
of interactive MATLAB code is saved into a file, the file is then a MATLAB program.
In this chapter, the structures of MATLAB programs and programming methods are
presented.
There are two types of files of MATLAB source programs. One is that the file
composed of ASCII code, containing a set of MATLAB statements. This type of file
is referred to as an M-script file. Another type is the so-called MATLAB function
file, to be discussed later. One thing in common for the two types of files is that, the
suffix of the files is m.
4 MATLAB source codes are usually ASCII text files. Any text editor can be used
to modify the source code; however, it is recommended to use the MATLAB editor
to write and debug MATLAB programs, since it is easier in manipulating programs.
Also the live editor provided in MATLAB processes live files, with suffix of mlx. Live
files are no longer text files. Live files will be illustrated later.
In 7 Sect. 4.1, the simplest script programs are presented first, and the use of
MATLAB editor and live editor are illustrated. In 7 Sect. 4.2, the limitations of
script files are demonstrated, and the necessity of introducing MATLAB functions is
presented. The mainstream MATLAB programming style—MATLAB functions are
presented in the remaining part of the chapter. An anonymous function description
method is also presented. In 7 Sect. 4.3, the information transfer between MATLAB
functions and their callers is demonstrated. Variable numbers of input and output
arguments are supported. In this section, the definitions of global and local variables
are also illustrated. In 7 Sect. 4.4, MATLAB function debugging and pseudocode
technique are presented.

4.1 MATLAB Script Files


MATLAB scripts are the simplest MATLAB programs. This type of file is just a
collection of MATLAB interactive commands. In this section, MATLAB program
editor is introduced, then MATLAB script programming is presented. Finally, the
use of MATLAB live editor is illustrated.

4.1.1 MATLAB Editor


MATLAB command type is provided to display the program in text format. Also,
edit command opens a MATLAB editor, as shown in . Fig. 4.1. If in the toolbar in
the MATLAB command window (. Fig. 2.1), the New Script button is clicked, the
editor interface is also opened.
The use of the MATLAB editor is very simple. The code can be written in the
editing zone in the blank area. The Save button in the toolbar can be clicked to save
the file. Buttons such as Find in the NAVIGATE group allow the user to find particular
text in the files. The buttons in the EDIT group adjust the styles and format of the code.
These buttons are standard Microsoft Windows buttons, and not further explained
here. Besides, click the Run button, the source code is executed.

 Example 4.1
4.1 · MATLAB Script Files
75 4

. Fig. 4.1 MATLAB editor interface

In the examples given earlier there are many program codes. Consider the problem in
Example 3.7, the code can be copied into the editor, such that the first program in the book
is created. The file is saved to c4mfirst.m file, and the editing zone is shown in . Fig. 4.2.
In the tag of the editing zone, the file name is shown. To open a blank file, click the +
button on the tag.
In the screenshot, the code m,s at the end of the program is shaded, indicating that
there are suggestions on the code. Moving the cursor to the shaded area, the recommended
modification prompt is automatically displayed. In this example, it is suggested to modify
commas to semicolons to suppress output. In fact, the automatically generated prompts
are not always correct. The user may decide whether or not to accept the modification
suggestions. 

4.1.2 MATLAB Live Editor


Live files are special MATLAB program files, with suffix mlx. Text, images, formulas
and MATLAB code can all be embedded in the live files. Since the MATLAB codes

. Fig. 4.2 Editing zone


76 Chapter 4 · MATLAB Functions Programming

inside are executable ones, the file is referred to as live files. Live files are no longer
ASCII code files. It can only be opened with live editor in MATLAB, not with any
other editors.
Click New Live Script button in the toolbar in MATLAB command window
(. Fig. 2.1), the live editor interface shown in . Fig. 4.3 is opened. The interface
is rather similar to ordinary MATLAB editor. The differences are that there are two
zones, labeled TEXT and CODE appear in the toolbar, which can further be expanded
as shown in . Fig. 4.4. Apart from the code, text information can be inserted in the
file. Besides, INSERT pane is provided to allow the user to insert other objects, such as
4 mathematical formulas or images. An example is given next to demonstrate the use
of live editor.

 Example 4.2
Generate the live file shown in . Fig. 4.5 with the live editor.
Solutions The background of the live file is the equation solution problem in Example 1.2.
The expected live file is composed of the following elements: “Solving Equation” is the
heading; “Solve the equation”, “MATLAB commands” are normal text. Besides, there are
mathematical formula and MATLAB code.
Open the live editor interface, then click TEXT to switch to text input mode. Click Normal
list box and select Heading 1 from the list. The title “Solving Equation” can be entered. It is

. Fig. 4.3 Live editor interface

. Fig. 4.4 CODE, TEXT and SECTION zones in the toolbar


4.2 · Fundamental Structures of MATLAB Functions
77 4

. Fig. 4.5 Expected live file (file name: c4mexlive.mlx)

centered, and the font of title is set automatically. Type Enter key, the text mode is changed
back to Normal. Click left align button, then type “Solve the equation”. Type Enter key
again. Click the INSERT pane, the new toolbar appears, as shown in . Fig. 4.6. It can be
seen that different objects can be inserted from the toolbar. Open Equation list box. Two
ways are provided to input equations—Equation and Latex Equation. The former provides
an equation editor, which is quite similar to the one in Microsoft Word, while the latter
allows the user to input LATEX commands. The user may select either way to input the
formula. Then type in normal text “MATLAB commands”. Press the CODE button, a gray
box appears, where the MATLAB commands can be filled in the area. The expected live
text in . Fig. 4.6 can then be created and saved. The default suffix for live files is mlx. 

Apart from the traditional format, the file can also be saved into PDF, HTML
and LATEX format. Press the Save list box, the output format can be selected. Note
that the output file is in fact a static file, and cannot be used to restore the live files.

4.2 Fundamental Structures of MATLAB Functions


MATLAB function format is the mainstream programming format. In practical pro-
gramming, MATLAB script format is not recommended. In the subsequent sections
in this chapter, concentrations are made on MATLAB function programming essen-
tials and skills. The fundamental structures in MATLAB functions are presented,

. Fig. 4.6 Toolbar under INSERT pane


78 Chapter 4 · MATLAB Functions Programming

and information on function naming is discussed. Examples are used to demonstrate


fundamental programming methods in MATLAB functions.

4.2.1 Why MATLAB Functions?


Before introducing function, an example is given to show why MATLAB functions
are recommended, rather than MATLAB scripts.

4
 Example 4.3
Consider the MATLAB script file c4mfirst in Example 4.1. The program can be executed
without any difficulties, but it can only be used to solve exactly the same problem. If the
problem is slightly changed, for instance, to find the m such that the sum is larger than
20000, the source code in c4mfirst.m file must be modified. In this example, modify 10000
into 20000. It is not a difficult thing for extremely small-scale problems, however for other
problems, sometimes the modification of source code may be extremely difficult. Therefore,
MATLAB script is not a good way in writing programs. 

To solve this type of problems, MATLAB function programming style should


be introduced. The variables which may change can be made as arguments. When
calling the function, the variables can be passed directly into the function, and there
is no need to modify the source code. MATLAB function will be simply written as
M-function later.

4.2.2 MATLAB Function Structures


A MATLAB function can be regarded as an information processing unit. It accepts a
set of input variables in1 , in2 , · · · , inn from the caller. These variables can be regarded
as input arguments of the M-function. The variables in the input and output list are
referred to as arguments in the book, to distinguish from the other variables. Inside
the information processing unit, these input arguments are processed, and the results
out1 , out2 , · · · , outm are written back to the caller. The structure of the M-function
is shown in . Fig. 4.7.
M-function is led by the function statement, with the fundamental structure
function [out1 ,out2 ,· · · ,outm ]=func_name(in1 ,in2 ,· · · ,inn )
comment statements led by % sign
input and returned arguments checking statements
function body
end

input arguments returned arguments


in 1 out 1
in 2 MATLAB function out 2
.. (information ..
. processing unit) .
in out

. Fig. 4.7 Structure of a MATLAB function


4.2 · Fundamental Structures of MATLAB Functions
79 4
The final end statement is not compulsory, it is recommended to use it in this book.
If there are more than one returned arguments, they should be delimited with square
brackets, otherwise the square brackets can be omitted. The arguments should be
separated by commas. Each line in the comment part should be led by the percentage
sign, and the contents in the comments are not executed, and only used to explain
accordingly the MATLAB function. The user can use help command to display
the information in the comments part. Besides, from the standardized programming
viewpoint, the detection of the arguments is necessary. If the argument numbers or
their format are incorrect, M-function gives appropriate error messages.
Apart from input and output arguments, all the variables inside the function are
local ones. They vanish directly when the function call is completed.

 Example 4.4
Change the script file in Example 4.1 into an M-function.
Solutions To write M-functions, a very crucial thing to do is to choose input and returned
arguments for the M-function. It was hinted earlier in Example 4.3 that N can be selected as
the input argument. If the sum is larger than N, the loop completes. The returned arguments
are m and s. After arguments selection, the following MATLAB function can be written.

function [s,m]=c4mmfun(N)
s=0; m=0; % set initial values
while (s<=N), m=m+1; s=s+m; end % complete loop when the sum > 10000
end
Save the above function to c4mmfun.m file. The following commands can be used to call
the function directly, and the corresponding results can be obtained. Different values can
be set to N argument, and there is no need to modify the source code. Meanwhile, different
variable names can be used to accept the results.

>> [s1,m1]=c4mmfun(10000), [a,b]=c4mmfun(12345)




4.2.3 Naming Regulations of MATLAB Functions


The naming regulations of functions are the same as the ones in variable names. It
must be led by a letter. Normally, a meaningful function name should be selected.
(1) Avoid the use of oversimple function names, such as a, otherwise it may collide
with the existing variable names, which may lead to errors.
(2) Before using a certain name, make sure that there is no such a name under
MATLAB search path. Otherwise the files with the same name may be shadowed,
and wrong results can be found. How to select a correct name in real applications? A
name can be conceived first, for instance, my_fname, then use which my_fname and
see whether an existing one can be found. If there is none found, the file name can be
selected. Function exist() can also be used in the name test.
(3) Since MATLAB is case-sensitive, when using names with capital letters, the
same case should also be used in the function call, otherwise warning messages are
displayed.
80 Chapter 4 · MATLAB Functions Programming

(4) The file name can be selected as different ones with the func_name in the
function statement. MATLAB search engine only searches file names rather than
their internal name inside the function. For better programming habits, it is suggested
to keep them the same.

4.2.4 Numbers of Input and Output Arguments


The actual numbers of input and returned arguments can be measured with nargin
4 and nargout. An example is given next to show the programming format and method.

 Example 4.5
Write an M-function to generate an n × m Hilbert matrix, whose element in the ith row,
jth column is hi,j = 1/(i + j − 1). The expected syntaxes of the function are

H=myhilb(n,m) % generate n × m Hilbert matrix


H=myhilb(n) % generate an n × n square Hilbert matrix

Solutions In Example 3.10, it has been shown that double loops generate the expected
Hilbert matrix. This can be used as the kernel of the function. The row number n and
column number m are selected as input arguments, and Hilbert matrix H is used as the
output argument. According to the two syntaxes, it can be seen that the first one can be
implemented directly, and in the second syntax, the number of input argument should be
measured. If the number is 1, that is, nargin is 1, we can set m = n, such that a square matrix
can be generated. Therefore the expected MATLAB function myhilb() can be written, and
saved into file myhilb.m, and place it MATLAB search path.

function A=myhilb(n,m)
% MYHILB This function demonstrates MATLAB function programming
% A=myhilb(n,m) generates an n × m Hilbert matrix A
% A=myhilb(n) generates an n × n square Hilbert matrix A
% See also: HILB

% Designed by Professor Xue Dingyu, (c) 1995-2022


if nargin==1, m=n; end % if only one input argument n is given, set m = n
for i=1:n, for j=1:m, A(i,j)=1/(i+j-1); end, end % generate the elements
end % to end the function paragraph
With the function written, we can use the following commands to call the function, and
the expected results can be found.

>> A1=myhilb(4,3), A2=myhilb(sym(4)) % call the function in different syntaxes


It is found that
⎡ ⎤ ⎡ ⎤
1 0.5 0.3333 1 1/2 1/3 1/4
⎢ 0.5 0.3333 0.25 ⎥ ⎢ 1/5 ⎥

A1 = ⎣ ⎥ , A2 = ⎢ 1/2 1/3 1/4 ⎥.
0.3333 0.25 0.2 ⎦ ⎣ 1/3 1/4 1/5 1/6 ⎦
0.25 0.2 0.1667 1/4 1/5 1/6 1/7

The following commands get online help information.


4.2 · Fundamental Structures of MATLAB Functions
81 4
>> help myhilb % display online help information
The online help information is displayed below:

MYHILB This function demonstrates MATLAB function programming


A=myhilb(n,m) generates an n × m Hilbert matrix A
A=myhilb(n) generates an n × n square Hilbert matrix A
See also: HILB
Note that only the information of syntaxes is displayed, with no author information
displayed. Compare the function, it is found that before the author information, there is
a blank line. To have help command display help information, there should not be any
blank line added in the source code. Even though a blank line is expected when displayed
with help command, it should be led by the percentage sign %. 

With commands nargin and nargout, the actual number of arguments can be
measured. Besides, function class() checks the data type of the arguments such that
the same MATLAB function supports different data types and calling syntaxes.

4.2.5 Input Arguments Validation


In recent versions of MATLAB, version R2019b and newer ones, the input arguments
can be validated with arguments paragraph. Before introducing such a new facility,
let us have a look at a simple example.

 Example 4.6
Writing a simple function with the syntax s=c4excirc(r,key), where r is a vector of
positive values, indicating the radii of circles or spheres. If the flag key is 1, the perimeter
vector s is returned; if key is 2 or 3, areas or volumes vector s is returned.
Solutions To make such a function more reliable, input argument validation must be made.
The input argument r must be a scalar or a vector, and the vector must be real and positive.
The input argument key must be a scalar, which can only be assigned as 1, 2 and 3 only.
To validate the input arguments and compute the s vector, the following function can be
written:

function s=c4excirc(r,key)
if ~isreal(r), error('r must be real'); end
if any(r<=0), error('r must be larger than 0'); end
if length(key)~=1, error('key must be a scalar'); end
if ~(isnumeric(key) && (key==1 || key==2 || key==3))
error('key must be 1, 2 and 3 only')
end % the above commands are for arguments validation
switch key % argument key can only be 1, 2 or 3
case 1, s=2*pi*r; % compute perimeters
case 2, s=pi*r.^2; % compute areas
case 3, s=4*pi*r.^3/3; % compute volumes of spheres
end, end

82 Chapter 4 · MATLAB Functions Programming

It can be seen from the above sentences that the input argument validation code
is too complicated. A new arguments paragraph is provided in recent versions of
MATLAB, whose main framework is
arguments
argument name 1(size) class name {mustBe commands}=default value
argument name 2(size) class name {mustBe commands}=default value
..
.
4 end
It should be noted in the paragraph that
(1) All the input arguments must be defined according to the order in the function.
(2) All the other elements except argument names can be omitted.
(3) In the size expression, (1,:) is allowed to define a row vector. If a column
vector is used in function call, it is accepted and converted automatically into a row
vector. If a matrix is used in function call, an error message is displayed.
(4) Class name is used to describe the argument’s data type, such as double.
(5) mustBe commands are used to validate the properties of the input argu-
ments. Some of the commonly used ones are mustBePositive(), mustBeInteger(),
mustBeNonpositive(), mustBeGreaterThan(), mustBeMember(), where in the
latter two, two input arguments should be provided.
(6) Many arguments can be designed in a single sentence, separated by commas
or semicolons.
If a certain input argument does not satisfy the definition in the arguments para-
graph, the function call is terminated, and an error message is displayed to indicate
the error.
Examples are given next to demonstrate the input argument validation paragraph.
It is recommended to use such a paragraph whenever necessary.

 Example 4.7
Input argument validation is demonstrated in Example 4.6, and the implementation looks
clumsy. Use arguments paragraph to simplify the validation process.
Solutions Two input arguments are allowed in the function, where r must be a row vector,
with positive components only, otherwise error messages should be displayed; key must
be a scalar, and it can only be assigned as 1, 2 or 3, otherwise error message should be
displayed. With the arguments paragraph given next, the validation can be implemented
in a simpler and neater manner. The code in switch-case is exactly the same as in Example
4.6. In the arguments paragraph, the double declaration is in fact not necessary.

function S=c4excirc1(r,key)
arguments % validate input arguments
r(1,:) double {mustBePositive} % positive row vector
key(1,1) double {mustBeMember(key,[1,2,3])} % scalar: 1, 2 or 3 only
end
switch key % argument key can only be 1, 2 or 3
4.2 · Fundamental Structures of MATLAB Functions
83 4
case 1, s=2*pi*r; % compute perimeters
case 2, s=pi*r.^2; % compute areas
case 3, s=4*pi*r.^3/3; % compute volumes of spheres
end, end


 Example 4.8
Rewrite the function in Example 4.5 with arguments paragraph.
Solutions If arguments paragraph is used, there is no need to use nargin command. The
default value of m can be assigned directly instead. The new function is more concise and
reliable, since input argument validations are implemented.

function A=myhilb1(n,m)
arguments, n(1,1) double {mustBeInteger, mustBePositive}
m(1,1) double {mustBeInteger, mustBePositive}=n
end
for i=1:n, for j=1:m, A(i,j)=1/(i+j-1); end, end % generate the matrix
end % to end the function paragraph


4.2.6 Recursive Structures


Recursive call of function means that the function calls itself. Recursive structures
are supported in MATLAB.

 Example 4.9
Write an M-function to compute the factorial n! with recursive structure.
Solutions An important formula for factorial is n! = n(n − 1)!. Therefore, if a function
my_fact() is created to compute the factorial, its kernel statement is

k=n * my_fact(n − 1)
where k is the expected n!. This relationship is the so-called recursive one.
Of course, it is not sufficient to use such a statement, since the function call will be
executed on and on. To compute the factorial normally, an exit must be designed, such that
the function call can be stopped normally. It is seen from the factorial definition that the
factorial of n can be evaluated from the factorial of n − 1, which in turn can be evaluated
from factorial of n − 2. The formula will be executed on and on, until the known term
1! = 0! = 1. Therefore the M-function can be written.

function k=my_fact1(n)
if nargin~=1, error('Error: Only one input variable accepted'); end
if abs(n-floor(n))>eps | n<0 % judge whether n is a nonnegative integer
error('n should be a non-negative integer'); % display error message
end
if n>1, k=n*my_fact(n-1); % if n > 1, recursive call
84 Chapter 4 · MATLAB Functions Programming

elseif any([0 1]==n), k=1; end % if 0! = 1! = 1, set the exit


end
With arguments paragraph, the function can be rewritten as follows, with a standardized
function structure. More than one mustBe type of functions are allowed.

function k=my_fact(n)
arguments, n(1,1) {mustBeNonnegative, mustBeInteger}; end
if n==0 || n==1, k=1; else, k=n*my_fact(n-1); end
end
4
It can be seen that in the function, the input argument n is checked, and see whether it is
a nonnegative integer scalar. If it is not, an error message is displayed. If it is, the program
calls itself when n > 1. If n = 1 or 0, the function returns 1. With my_fact(11) command,
the function returns the factorial 39916800. In fact, factorial() in MATLAB can also
be used, with the kernel algorithm prod(1:n), which is simpler and faster. 

 Example 4.10
Compare the advantage and disadvantage between recursive algorithm and loop algorithm
in generating Fibonacci sequence.
Solutions Recursive algorithm is an effective algorithm for many problems, but it should
not be misused. A counterexample is here. Consider Fibonacci sequence, a1 = a2 = 1,
ak = ak−1 +ak−2 , k = 3, 4, · · · . It is quite natural to consider adopting recursive algorithm
to write the function, and set the exits when k = 1, 2 to 1. The function can be written as

function a=my_fibo(k) % function with recursive algorithm


arguments, k(1,1) {mustBePositive, mustBeInteger}; end
if k==1 || k==2, a=1; else, a=my_fibo(k-1)+my_fibo(k-2); end
end
The argument checking command for k is introduced. If the 40th term is expected, the
following command can be issued. The measured executing time is 16.83 s.

>> tic, my_fibo(40), toc % compute the 40th term and that term ONLY
If recursive algorithm is used to compute the 40th term, the time elapse is 26.87 s. When
computing the 50th term, it may take about a few hours. The computational load increases
drastically. Why is the computational burden so high? Assume that at k = 6, the terms a4
and a5 are computed from the beginning, while when computing a5 , the terms a4 and a3
also need to start from the very beginning. The binary tree structure is shown in . Fig. 4.8.
Therefore it is quite time-consuming. The computing of a6 requires to compute a5 once,
a4 twice, a3 three times. If larger value of k is expected, the computational load will be too
high to compute.
To compute a6 , if the terms a5 and a4 previously obtained can be adopted directly,
rather than recomputed from the very beginning, the computational load will be reduced
significantly. A practical method is to set up an a vector, such that the value ai previously
found can be stored and visited, rather than computed again. If loop structure is used to
compute the terms when k = 100, the time elapse is only 0.0002 s.

>> tic, a=[1,1]; for k=3:100, a(k)=a(k-1)+a(k-2); end % the first 100 terms
toc, a(end) % display the last term in the vector
4.2 · Fundamental Structures of MATLAB Functions
85 4

5 4

4 3 3 2

3 2 2 1 2 1

2 1

. Fig. 4.8 Binary tree of Fibonacci sequence

It can be seen that the terms incapable to be found with recursive structure can be found
in an extremely short time when loop structure is used. Therefore the recursive structure
should not be misused in real programming. It is also seen from the results that, since
the terms in the sequence are too large, symbolic data type should be used. The simplest
way is to change the statement a=[1,1] into a=sym([1,1]), such that accurate solution
a100 = 354224848179261915075 is found, and the time elapse is 0.717 s.

>> tic, a=sym([1,1]); for k=3:100, a(k)=a(k-1)+a(k-2); end


toc, a(end)


4.2.7 Anonymous Functions


The functions previously discussed corresponds to a .m file. Sometimes to describe
mathematical formulas in a concise way, anonymous functions describe the for-
mula dynamically. The calling syntaxes of anonymous functions are equivalent to
M-functions. There is no need to write a genuine .m file. This manipulating method
can be understood as defining a function dynamically.
The syntax of anonymous function is f =@(input arguments)function expression,
for instance, f =@(x,y)sin(x.^2+y.^2).
Besides, the variables in MATLAB workspace can be used directly to evalu-
ate function expression. For instance, if there are variables a and b in MATLAB
workspace, the anonymous function can be written as f =@(x,y)a*x.^2+b*y.^2, to
define the mathematical formula f (x, y) = ax2 +by2 , where there is no need to include
a and b as input arguments of the anonymous function. Therefore, the description of
mathematical formulas is even simpler and more convenient. Note that, when defin-
ing the anonymous functions, the current values of a and b in MATLAB workspace
are used. If their values are changed later, the anonymous function is not affected. If
the user expects anonymous function uses the current values of a and b, the best way
is to redefine the anonymous function after the parameters are changed.
Anonymous functions are very useful in numerical computation. Simple math-
ematical formulas are suitable to describe with anonymous functions. The use of
anonymous functions will be used extensively later.
86 Chapter 4 · MATLAB Functions Programming

 Example 4.11
Assume a = 1 and b = 2, use anonymous function to describe the function f (x, y) =
ax2 + by2 . Find the value of f (2, 3). Modify the values a = 2 and b = 1, compute again
the value of f (2, 3).
Solutions The value of a and b can be assigned first, and define the function with anonymous
function. The value of the anonymous function can be evaluated directly, with the result
f (2, 3) = 22. If a and b are changed, and call the anonymous function again, the value of
f (2, 3) is still 22, while the theoretical value is f1 = 17. It is obvious that they are different.

4 >> a=1; b=2; f=@(x,y)a*x^2+b*y^2; f(2,3) % define anonymous function


a=2; b=1; f(2,3), f1=a*2^2+b*3^2 % no effect when parameters modified
Why the phenomenon like this happens? When defining the anonymous function, the
symbols a and b are not used, their current values in workspace are used instead. It is
equivalent to the definition f =@(x,y)x^2+2*y^2. Therefore, even if the parameters a and
b are changed, the anonymous function is not altered at all. Therefore the anonymous
function value is different from the theoretical result.
How to get the same results as in the theoretical one? After modifying the variables a and
b, the anonymous function should be declared again and then evaluated to get the correct
result of 17.

>> a=2; b=1; f=@(x,y)a*x^2+b*y^2; f(2,3) % modify parameters, redefine function




 Example 4.12
Consider the piecewise function in Example 3.18. If x 1 and x 2 are selected as input argu-
ments, describe the function with anonymous function. Then compute the values of the
function on the mesh grid points.
Solutions Vectorized operations should be used in the anonymous function description.
The following MATLAB commands describe the piecewise function, with dot operations
in the command, otherwise errors may be found. Therefore the function handle f can be
defined, whose identifier is a function_handle.

>> f=@(x1,x2)... % input arguments, dot operations are used below


0.5457*exp(-0.75*x2.^2-3.75*x1.^2-1.5*x1).*(x1+x2>1)+...
0.7575*exp(-x2.^2-6*x1.^2).*(-1<x1+x2 & x1+x2<=1)+...
0.5457*exp(-0.75*x2.^2-3.75*x1.^2+1.5*x1).*(x1+x2<=-1);
The advantages of vectorized programming style are very useful in the description, since
loop structures are not supported inside the anonymous functions. If mesh grid matrices
x 1 and x 2 are generated, the following commands get the function values at the mesh grid
points. The size of the returned argument p is identical to those in x 1 and x 2 matrices.

>> [x1,x2]=meshgrid(-2:0.1:2); % generate mesh grids


p=f(x1,x2); % evaluate function values directly

4.3 · Variable Transfers in Functions
87 4
4.3 Variable Transfers in Functions
The variable transfers between M-functions and their callers can be made by the input
and output arguments. Besides, other variable transfer methods are supported. In this
section, these variable transfer methods are presented.

4.3.1 Extractions of Arguments


An important application of cell array is demonstrated in this section. It sets up
the storage containing variable numbers of input and output arguments. It should
be noted that most of the MATLAB functions adopt these methods for input and
output arguments.
Before learning how to deal with arbitrary numbers of input and output argu-
ments, it is better to learn first how the input arguments are transferred from the
caller to the M-functions. Based on the MATLAB mechanism, the input arguments
are transferred into the M-function in a cell array named varargin, whose struc-
ture is shown in . Fig. 4.9. The value of n can be evaluated directly with com-
mand nargin. Similarly, output arguments are transferred back in the cell array
varargout. To extract the kth input argument from the varargin cell array, the com-
mand varargin{kx} can be used. Such a programming method may make MATLAB
function more flexible and effective. An example is given here to demonstrate how to
process arbitrary number of input arguments.

 Example 4.13
There are different ways in describing polynomials in MATLAB. One is the symbolic
expression expressed earlier. The other is to use numerical method. By convention, a poly-
nomial can be described by a vector of coefficients, in the descending order of s. The latter
is considered in this example. The product of two polynomials can be found with function
call p=conv( p1 , p2 ). If many polynomials are to be multiplied, nested calls of the func-
tion should be made. It might be rather complicated to multiply several polynomials in
this way. Write a MATLAB function, which computes the product of arbitrary number of
polynomials.
Solutions A function name convs() can be selected. The input arguments are p1 , p2 , · · · .
The target of the function is to multiply arbitrary number of polynomials together. The
input arguments can be passed into the function through a cell array varargin, and the
returned argument is p, which is the product vector. In the implementation viewpoint, the
initial value of p can be set to 1. Then each argument shown in . Fig. 4.9 can be extracted
in a loop structure, and function conv() multiplies the argument to p. Therefore the final
polynomial is the product of all the polynomials, returned in vector p.

in 1 in 2 in

varargin{1} varargin{2} ··· varargin{ }

. Fig. 4.9 Input arguments storage


88 Chapter 4 · MATLAB Functions Programming

function p=convs(varargin)
p=1; % set the initial value of the product
for i=1:nargin % in the loop structure, extract each input argument
p=conv(p,varargin{i}); % multiply the polynomial in the argument
end, end
Therefore, all the input arguments can be expressed in the cell array varargin. The
ith input argument is actually stored in varargin{i}. Theoretically, arbitrary number of
polynomials can be multiplied in this way. For instance, the following commands can be
4 used to call the function.

>> P=[1 2 4 0 5]; Q=[1 2]; F=[1 2 3];


D=convs(P,Q,F) % process the product of three polynomials
E=conv(conv(P,Q),F) % nested use of the conv() function
G=convs(P,Q,F,[1,1],[1,3],[1,1]) % product of 6 polynomials
The same D and E vectors can be found, and vector G is also found.

D = E = [1, 6, 19, 36, 45, 44, 35, 30],


G = [1, 11, 56, 176, 376, 578, 678, 648, 527, 315, 90].

 Example 4.14
Observe closely the convs() function written in Example 4.13. It seems that there exist bugs
in the code. For instance, normally pi are scalars or row vectors. If a certain pi is a column
vector, it may lead to erroneous results. Error tolerance processing can be introduced in
programming. In this case, each argument should be converted a row vector before it is
used. Use this idea to modify the source code.
Solutions For a given vector p, no matter whether it is a column vector or a row one,
command p(:) converts it directly into a column vector. To change it into a row vec-
tor, transpose should be made. Therefore, the original program can be modified into the
following form:

function p=convs1(varargin)
p=1; % set initial values
for i=1:nargin % use loop structure to process each argument
p=conv(p,varargin{i}(:).'); % manipulating fault tolerance facilities
end, end
If arguments paragraph is used, the function can be rewritten as

function p=convs2(varargin)
arguments (Repeating), varargin(1,:) {mustBeNumeric}; end
p=1; % set initial values
for i=1:nargin % use loop structure to process each argument
p=conv(p,varargin{i}); % polynomial product
end
end
4.3 · Variable Transfers in Functions
89 4
Note that when using varargin, (Repeating) specification must be used. Since mustBe-
Numeric is used, the function works for double, single, or even integer data types. 

Similarly, if necessary, all the returned arguments can be expressed by a single cell
array varargout.

4.3.2 Local and Global Variables


It has been shown that the information transfer between M-function and its caller can
be made through input and returned arguments. The variables except the arguments
vanish after the function call is completed. Therefore these variables are referred to as
local variables. For instance, variable i in Example 4.13 vanishes automatically when
the function call is completed. Even though the same name as the one in MATLAB
workspace is used inside the function, the original one in MATLAB workspace is not
affected.
In real programming, if we are expecting two or more M-functions sharing one or
more variables, the concept of global variables is used. Command global declares
global variables. In at least two places, the global variables should be declared. One
is in the function where the variable is used, the other one is in the function where the
variable is assigned or modified.

 Example 4.15
Consider the problem in Example 4.4. If N is passed to the function through global variable,
rather than through input argument, modify the function, and use new statements to call
the function.
Solutions If N is no longer an input argument, there is no input argument in this function.
The entry point of the function should be modified. Inside the function, N should be
declared as a global variable. Therefore the new function can be written as

function [s,m]=c4mmfun1 % no input argument


global N; s=0; m=0; % declare global variable & set initial values
while (s<=N), m=m+1; s=s+m; end % there is no change here
end
To call the function, N should be declared as global variable first. Then its value should
be assigned. Therefore the statements in Example 4.4 can be replaced by the following ones,
and the same results can be found.

>> global N; N=10000; [s1,m1]=c4mmfun1


N=12345; [a,b]=c4mmfun1 % no need to declare global variable again


It can be seen from the above commands that the variable transfer format using
global variables are rather complicated than the input argument one. Therefore unless
absolutely necessary, the global variable transfer format is not recommended. Input
and output argument-based transfers are recommended.
90 Chapter 4 · MATLAB Functions Programming

4.3.3 Accessing MATLAB Workspace Variables


Apart from the argument-based and global variable-based data transfer, MATLAB
functions can also load in the current variables in MATLAB workspace, and also
write results back to the MATLAB workspace.
A pair of functions, assignin() and evalin(), are provided in MATLAB
to access MATLAB workspace variables. The command assignin(‘base’,var_
name, variable) writes the variable into MATLAB workspace. The stored variable
name is expressed in var_name in the string. Command a=evalin(‘base’,var_
4 name) reads MATLAB workspace variable under var_name, to variable a in the
function.
If the option ‘base’ is substituted by ‘caller’, the data access is not between
the function and MATLAB workspace, but between the function and its caller.

 Example 4.16
Consider the problem in Example 4.4. Assume that N cannot be passed into the function
via input argument. It should be read directly from MATLAB workspace. Rewrite the
function, and issue the new statements to call the function.
Solutions Inside the function, the value of N can be read directly from MATLAB
workspace. After execution of the function, the result m can be written back to the vari-
able m0 in MATLAB workspace. Therefore m is no longer a returned argument. The new
function is written as

function s=c4mmfun2 % no input argument, one output argument


N=evalin('base','N'); s=0; m=0; % read N from MATLAB workspace
while (s<=N), m=m+1; s=s+m; end
assignin('base','m0',m); % write result back to MATLAB workspace
end
To call the function, the following commands can be issued. The results are exactly the
same as the ones in Example 4.4.

>> N=10000; s1=c4mmfun2, m1=m0, N=12345; a=c4mmfun2, b=m0




Please note that the variable transfer methods introduced here are informal ones.
The formal one is to use input and output arguments to pass the variables. If not
absolutely necessary, it is NOT recommended to use these informal ways to pass
variables.

4.4 Debugging in MATLAB Functions


Programming of MATLAB functions is illustrated earlier. Under normal cases, the
debugging is relatively complicated, since the variables between the function and its
caller are passed through arguments. Apart from these arguments, all other vari-
ables are local ones, which cannot be monitored from outside the function. Therefore
4.4 · Debugging in MATLAB Functions
91 4
debugging facilities should be introduced to monitor the changes in the local vari-
ables. In this section, function debugging methods are demonstrated. Pseudocode
and MATLAB code protection methods are then presented.

4.4.1 MATLAB Function Debugging


Debugging facilities are provided in MATLAB. The user may set up breakpoints in
the functions, such that the internal local variables can be visited, and the internal
statements can be executed in single-step execution mode. These debugging facili-
ties can be implemented in the editor interface or with MATLAB commands. In the
examples in the book, each line of the source code is usually composed of several state-
ments. If necessary, they can be broken into single lines for debugging. An example
is given next to demonstrate the debugging process.

 Example 4.17
Handle the function in Example 4.4 with debugging method.
Solutions Use edit c4mmfun command to open the c4mmfun.m file, and separate the lines
in the source code, as shown in . Fig. 4.10. The user may set up breakpoints upon his
needs. The so-called breakpoint means that the source code pauses here when executed.
The simplest way to add a breakpoint is to click the identifier to the left of each line. For
instance, in the 4th line, click the identifier beside “4”, a red mark appears at the location.
This mark is a breakpoint. Execute the following statement:

>> [s,m]=c4mmfun(500)
A pause automatically appears when executed to the breakpoint, as shown in . Fig. 4.11.
When the cursor is moved above the interested variable in the editor, the current value of
the variable is displayed. The toolbar in the editor is also changed accordingly, to display
buttons for debugging. The Continue button can be clicked to continue executing until the
next breakpoint. The Step button executes one statement from the breakpoint. The Quit

. Fig. 4.10 MATLAB editor interface


92 Chapter 4 · MATLAB Functions Programming

. Fig. 4.11 Monitor the local variables at breakpoints

Debugging button cancels the current debugging mode, and restores to normal execution
mode.
At the breakpoint, the following prompt is displayed in MATLAB command window:

4 m=m+1; s=s+m;
K>>
where the first line displays the line number of the breakpoint and the code, K>> in the
second line is the prompt, allowing the user to enter commands to display and manipulate
internal and local variables inside the function. In this mode, the variables in MATLAB
workspace cannot be displayed. Only the local variables can be accessed. 

4.4.2 Pseudocode Technique


Two of the aims in MATLAB pseudocode techniques are
(1) To accelerate the execution speed of MATLAB function, since with pseudocode
technique, the .m file is converted into executable code to bypass the interpretation
process.
(2) To convert the .m file in ASCII code into encoded binary code, such that other
users are not able to read the source code inside the function. The source code can
then be protected.
Command pcode converts .m files into pseudocode files, and the suffix of pseu-
docode files is p. If the user wants to convert file mytest.m into a pseudocode file, the
command pcode mytest can be used. If one wants to have the converted .p file in the
same folder of the .m file, the command pcode mytest -inplace can be executed.
To convert all the .m files in a folder into .p ones, the command cd gets into the
folder, and type pcode *.m. If there is no syntax error in the files, all the .m files
can be converted into .p ones. If there are syntax errors, the conversion process is
terminated, and error message is displayed. The error message can be used for locating
bugs in the functions. If there are both .m and .p files under same name, the .p file
has higher priority. Note that M-scripts cannot be processed with pcode commands.
4.5 · Exercises
93 4
The users are advised to store the .m source files in safe place, and should not be
deleted, since the .p files are not invertible. If the .m files are lost, only .p files saved,
it means that the file can only be used, but not be modified, since .m files cannot be
restored from the .p files.

4.5 Exercises
(1) Write a function mat_add() to add up matrices in the following syntax:
A=mat_add( A1 , A2 , A3 ,· · · )
The function adds up arbitrary number of matrices. If the size of a certain matrix
is not compatible with others, terminate the summation and display an error
message.
(2) Write a MATLAB function to implement the following piecewise function:

⎨ h, x>D
y = f (x) = h/Dx, |x| ≤ D

−h, x < −D.

(3) Write a MATLAB function with the syntax H=mat_roots( A,n), where A is a
square matrix, n is an integer, and H is a cell array, such that the kth cell stores
the kth root, in the nth root of A.
(4) Write a MATLAB function such that it generates an m × m Hankel matrix
⎡ ⎤
h1 h2 ··· hm
⎢ h2 h3 ··· hm+1 ⎥
⎢ ⎥
H =⎢ . .. .. .. ⎥,
⎣ .. . . . ⎦
hm hm+1 ··· h2m−1

such that the syntax is v=[h1 , h2 , hm , hm+1 , · · · , h2m−1 ]; H=myhankel(v).


(5) MATLAB functions gcd() and lcm() find the greatest common divisor and
least common multiple of two numbers. The limitation of the two functions is
that they can only handle two integers. Extend the functions to gcds() and
lcms() such that arbitrary number of integers can be processed.
(6) Fibonacci sequence is generated from formula ak = ak−1 + ak−2 , k = 3, 4, · · · ,
where the initial values are a1 = a2 = 1. Write an M-function to generate a
certain term in the Fibonacci sequence, where
(a) The syntax is y=fib(k). If k is provided, the k terms can be assigned into
vector y.
(b) Write suitable input and output argument validation code, and make sure
k is a positive integer.
(c) Use recursive method to write the function.
(7) Use the following method to compute the value of π with a loop structure: If
the multiplier |δ − 1| < 10−6 , stop the loop. If the error tolerance is further
reduced, whether a more accurate value of π can be found. What is the most
accurate possible value of π can be found, under double precision framework?
94 Chapter 4 · MATLAB Functions Programming

√ √ √
2 2 2+ 2 2+ 2+ 2
≈ · · ··· .
π 2 2 2

(8) Newton−Raphson iteration. Assume that from a guess of the solution xn of an


equation f (x) = 0, the next approximation point is xn+1 = xn − f (xn )/f  (xn ).
If the two points are closed enough, that is, |xn+1 − xn | < , where  is a
predefined error tolerance, xn+1 can be regarded as the solution of the equation,
otherwise xn+1 can be set as the initial value and try again, until a solution
4 is found. Write an M-function to implement the algorithm. Let x0 = −4 and
 = 10−12 , use Newton−Raphson iteration method to solve the equation f (x) =
x2 sin(0.1x + 2) − 3 = 0.
(9) The definition of the well-known Mittag-Leffler function is


xk
Eα (x) = ,
(αk + 1)
k=0

where (x) is a Gamma function, which can be evaluated with function


gamma(x). Write an M-function with the syntax f =mymittag(α,z,), where 
is the error tolerance, with a default value of  = 10−6 , z is a numeric vector.
Draw the curves of the function at α = 1 and α = 0.5.
(10) Chebyshev polynomial is defined as

T1 (x) = 1, T2 (x) = x, Tn (x) = 2xTn−1 (x) − Tn−2 (x), n = 3, 4, 5, . . . .

Write a recursive function to generate Chebyshev polynomial, and compute


T10 (x). Write a more efficient function to generate Chebyshev polynomial, and
compute T30 (x).
(11) It is known that if a matrix M can be written as M = A + BC B T , where A, B
and C are matrices of compatible sizes, the inverse of M matrix can be evaluated
from the following algorithm:
 −1  −1 T −1
M −1 = A + BC B T = A−1 − A−1 B C −1 + B T A−1 B B A .

Write an M-function to evaluate the inverse matrix of M. The following test


matrices can be used to validate the inverse. Compare the result with the direct
one using inv() function.
⎡ ⎤ ⎡ ⎤
−1 −1 −1 1 0 1 0 0 0 0
⎢ −2 0 0 −1 0⎥ ⎢0 3 0 0 0⎥
⎢ ⎥ ⎢ ⎥
M=⎢
⎢ −6 −4 −1 −1 −2 ⎥ ⎢
⎥, A = ⎢0 0 4 0 0⎥⎥,
⎣ −1 −1 0 2 0 ⎦ ⎣0 0 0 2 0⎦
−4 −3 −3 −1 3 0 0 0 0 4
4.5 · Exercises
95 4
⎡ ⎤ ⎡ ⎤
0 1 1 1 1 1 −1 1 −1 −1
⎢0 2 1 0 1⎥ ⎢1 −1 0 0 −1 ⎥
⎢ ⎥ ⎢ ⎥
B=⎢
⎢1 1 1 2 1⎥ ⎢
⎥, C = ⎢0 0 0 0 1⎥⎥.
⎣0 1 0 0 1⎦ ⎣1 0 −1 −1 0⎦
1 1 1 1 1 0 1 −1 0 1
(12) Many exercises in 7 Chap. 3 can be made into functions, when added input and
output arguments. For instance, given the size n, an M-function can be written
to input directly the following matrix:
⎡ ⎤
1 −2 4 ··· (−2)n−1
⎢0 1 −2 ··· (−2)n−2 ⎥
⎢ ⎥
⎢0 0 1 ··· (−2)n−3 ⎥
A=⎢ ⎥.
⎢. .. .. .. .. ⎥
⎣ .. . . . . ⎦
0 0 0 ··· 1

Write an M-function, with the syntax A=mymatx(n). If n is not given, generate


a 6 × 6 matrix instead.
(13) Write a function to generate the first m terms in the extended Fibonacci
sequence, where

T (n) = T (n − 1) + T (n − 2) + T (n − 3),

n = 4, 5, · · · , and the default initial values are T (1) = T (2) = T (3) = 1.


(14) Write an M-function to generate random integer square matrix. Assume the
elements are in the interval (am , aM ), we need to write a function with the syntax
A=unirandi([am ,aM ],n), such that the determinant of A is 1. Generate a
13 × 13 integer matrix, with possible elements of 0, 1 and −1, such that its
determinant is 1.
(15) The first row and column elements of an n × n Pascal matrix are all 1’s. The
remaining elements can be worked out with the following formula:

pi,j = pi,j−1 + pi−1,j , i = 2, 3, . . . , n, j = 2, 3, . . . , n.

Write an M-function to generate an n × n Pascal matrix. √


(16) Compare Exercises 10 and 13 in Chap 3, it is seen that the former one is 2,

and the latter 3. It is safe to guess that if√the iterative formula is changed to
xk+1 = (xk + a/xk )/2, the formula finds a. Write a MATLAB function to
validate such a conjecture.
(17) Write an essay using live editor to describe the definition, recursive algorithm
and binary tree in generating Fibonacci sequence. Use live code to generate the
sequence.
96 Chapter 4 · MATLAB Functions Programming

4.6 Mini-Projects

1. Recursive Implementation
Consider the binomial coefficients formula.
 
n n!
wj = (−1)j = (−1)j , j = 0, 1, 2, . . . , n (4.1)
j j! (n − j)!

If n = α is no longer an integer, the factorials do not exist. Therefore, they can be


4 extended into Gamma functions, and the binomial coefficient can be redefined as [1]
 
α (−1)j (α + 1)
wj = (−1)j = , j = 0, 1, 2, · · · (4.2)
j (j + 1)(α − j + 1)

How can we find the first 200 such coefficients? An immediate answer is to use
a loop structure and work out the coefficients one by one. Unfortunately, Gamma
function (x) for large x tends to ∞ under double precision framework, therefore
the values wj = 0 when j > 172. This is NOT correct.
Using the property (a + 1) = a(a), the ratio wj /wj−1 can be simplified, such
that Gamma functions in the formula can be canceled.

wj (−1)j (α + 1) (−1)j−1 (α + 1)
=
wj−1 (j + 1)(α − j + 1) (j)(α − j + 2)
(j)(α − j + 2) (j)(α − j + 1)(α − j + 1)
=− =− (4.3)
(j + 1)(α − j + 1) j(j)(α − j + 1)
α−j+1 α+1
=− =1−
j j

and the following recursive formula can be derived:


 
α+1
w0 = 1, wj = 1 − wj−1 , j = 1, 2, · · · (4.4)
j

(1) Prove (4.4) with symbolic computing method.


(2) The coefficients wj can be evaluated even for large values of j. Write a MATLAB
function to compute the first 1000 terms of wj . What is the last value?

2. Recursive Implementation Again


Matrix functions are the extension of Taylor series in matrix form. For instance,
sinusoidal function of a square matrix A is defined as

A2k+1 1 1
sin( A) = (−1)k = A − A3 + A5 + · · · (4.5)
(2k + 1)! 3! 5!
k=0

The matrix function can be evaluated numerically by adding the first few terms,
until the norm of a certain term is smaller than the predefined error tolerance ε. A
Reference
97 4
loop can be constructed to compute the matrix function. By the direct implementation
method, the computing of Ak is needed, even up to a very large value of k. To avoid
computing Ak , the recursive formulation discussed earlier can be used.
(1) Derive a recursive formula for matrix computation.
(2) Write a MATLAB function to compute the sinusoidal function of a given
matrix A, under error tolerance ε, with default value of 10−14 .
(3) Validate the function and see whether the result obtained is the same as the
one with funm( A,@sin) command.
Note that, when writing the function, make sure that A is a square matrix, while
ε is a positive scalar, whose default value is 10−14 .

Reference
1. Xue DY, Bai L (2023) Fractional calculus: high-precision algorithms and implementations[M].
Springer, Singapore
99 5

MATLAB Graphics
Contents

5.1 Simple Two-Dimensional Plots – 101


5.1.1 Data-based Plotting – 101
5.1.2 Function Expression-based Plotting – 105
5.1.3 Plots of Parametric Equations – 107
5.1.4 Plots with Two y Axes – 109
5.1.5 Graph Decorations and Editing – 109
5.1.6 Extracting Data from Plots – 111

5.2 Special Two-Dimensional Plots – 111


5.2.1 Polar Plots – 112
5.2.2 Representation of Discrete Signals – 114
5.2.3 Statistical Plots – 115
5.2.4 Filled Plots – 117
5.2.5 Logarithmic Plots – 118
5.2.6 Dynamic Trajectory and Animation – 120
5.2.7 Graphics Window Divisions – 121

5.3 Three-Dimensional Plots in MATLAB – 121


5.3.1 Three-Dimensional Curves – 122
5.3.2 Three-Dimensional Parametric Equation Curves – 123
5.3.3 Three-Dimensional Surfaces – 123
5.3.4 Viewpoint Setting – 125
5.3.5 Surface of Parametric Equations with Two Parameters – 126
5.3.6 Three-Dimensional Animation – 127

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_5
5.4 Implicit Function Plotting – 128
5.4.1 Two-Dimensional Implicit Function Curves – 129
5.4.2 Three-Dimensional Implicit Function Surfaces – 131

5.5 Exercises – 132

5.6 Mini-Projects – 135

References – 136
5.1 · Simple Two-Dimensional Plots
101 5
MATLAB graphics and visualization are the prominent advantages in MATLAB lan-
guage. A series of straightforward and simple two-dimensional and three-dimensional
plotting commands and functions are provided in MATLAB. The experimental data
and simulation results can be displayed in visual form. Two-dimensional and three-
dimensional plots from data, explicit or even implicit mathematical functions are
illustrated in this chapter.
From MATLAB R2014b, a completely new set of functions and commands are
provided. Although some of the graphics functions in the earlier versions can still
be used, they may be ignored in the coming versions. Therefore, the new plotting
facilities and functions are recommended in this book.
In 7 Sect. 5.1, simple two-dimensional plotting facilities are illustrated. Data-
based and mathematical formula-based methods are presented to draw 2D plots.
Decorations of the plots are also demonstrated. In 7 Sect. 5.2, special 2D graphics
facilities are presented. Polar plots, discrete point representation as well as statis-
tical plots are illustrated. Dynamic graphics are also demonstrated. In 7 Sect. 5.3,
the graphical facilities on three-dimensional plots are presented. Three-dimensional
curves and 3D surface plots are illustrated. The definition of viewpoint is proposed,
and the processing of 3D dynamic plotting, animation and video generation are illus-
trated. In 7 Sect. 5.4, the implicit function graphics are presented, where 2D and 3D
implicit function plotting are demonstrated.

5.1 Simple Two-Dimensional Plots


Two-dimensional graphics are the most common and practical graphics in scientific
research. In this section, 2D graphical representation methods from data are presented
and then curve representation of mathematical formulas is illustrated.

5.1.1 Data-based Plotting


Assume that the user has acquired some experimental data. For instance, at time
instances t = t1 , t2 , · · · , tn , the measured function values are y = y1 , y2 , · · · , yn .
These data can be input into MATLAB environment, in the vectors t=[t1 ,t2 ,· · · ,tn ]
and y=[y1 ,y2 ,· · · ,yn ]. If a curve is needed to show the relationship between the two
vectors, plot(t, y) command can be used to draw the 2D curve. It can be seen that
the syntax is very straightforward.

 Example 5.1
Draw the curve of the explicit function y = sin(tan x) − tan(sin x), x ∈ [−π, π].
Solutions The simplest way to solve the problem is to generate an x vector and evaluate
the function values. Then the plot can be drawn immediately. With the command, the plot
in . Fig. 5.1 can be obtained. While it can be seen that there seem to be problems and the
plot is suspicious.

>> x=-pi:0.05:pi; % generate vector with increment of 0.05


y=sin(tan(x))-tan(sin(x)); plot(x,y) % find the function values

102 Chapter 5 · MATLAB Graphics

-1

-2

5 -3
-3 -2 -1 0 1 2 3

. Fig. 5.1 The curve of the given function

It should be noted that the curve obtained with MATLAB function plot() is not
really a “curve”. It is a poly-line joining the samples. If the samples are sufficiently
close, the poly-line may become smoother and looks like a curve. In this book, the
poly-line is referred to as a curve.

 Example 5.2
Generate densely distributed samples and draw the correct curve for the function in Exam-
ple 5.1.
Solutions It can be seen by observing the curve in . Fig. 5.1 that the plot has problems
at around ±π/2 points. Why does this happen? Observing the term sin(tan x), since at the
points ±π/2, the tangent function tends to infinity, such that the changes in the sinusoidal
values become very irregular, and there are strong oscillations.
Extremely small step size can be taken in the whole range, or in a small ranges at x ∈
(−1.8, −1.2) and x ∈ (1.2, 1.8), the above commands can be simplified as

>> x=[-pi:0.05:-1.8,-1.799:0.0001:-1.2, -1.2:0.05:1.2,...


1.201:0.0001:1.8, 1.81:0.05:pi]; % generate vector with variable step-size
y=sin(tan(x))-tan(sin(x)); plot(x,y) % compute the function values
The new curve obtained is shown in . Fig. 5.2. It can be seen that the curves around
the points ±π/2 have very strong oscillation, and look normal.
If small step size 0.0001 is taken, the same plot can be found.

>> x=-pi:0.0001:pi; % generate vector with increment 0.0001


y=sin(tan(x))-tan(sin(x)); plot(x,y) % evaluate function and draw plot


It can be seen from this example that we should not rely too much on the curves
drawn with MATLAB. The results should be validated. An effective way is to select
different step sizes, and see whether the curves obtained are consistent. If they are,
the curve is validated; otherwise, smaller step size can be selected and validated again
until consistent results can be found.
5.1 · Simple Two-Dimensional Plots
103 5

-1

-2

-3
-3 -2 -1 0 1 2 3

. Fig. 5.2 The curve with new step sizes

In real applications, the syntax of plot() function can be further extended.


(1) t is still a vector, and y is a matrix defined below.
⎡ ⎤
y11 y12 ··· y1n
⎢ y21 y22 ··· y2n ⎥
⎢ ⎥
y=⎢ . .. .. .. ⎥.
⎣ .. . . . ⎦
ym1 ym2 ··· ymn

Under the same axis, m curves can be drawn, that is, each row in the matrix
corresponds to a curve, and the color of the curve is assigned automatically. Note
that the number of columns of matrix y should be the same as the length of vector t.
(2) Both t and y are matrices of the same size. The curve of each row of t and each
row of y can be drawn.
(3) Assume that there are many such vectors or matrices (t 1 , y1 ), (t 2 , y2 ), · · · , (t m ,
ym ), the following commands draw the curves of the corresponding pairs.
plot(t 1 , y1 ,t 2 , y2 ,· · · ,t m , ym )

(4) The properties such as line type, line thickness and colors, can further be
assigned using the following command:
plot(t 1 , y1 ,option 1,t 2 , y2 ,option 2,· · · ,t m , ym ,option m)
where the options can be described according to . Table 5.1, with the options of the
combinations of the strings. For instance, to use red dash-dot lines, and the marker
are described as pentagrams. the string 'r-.pentagram' can be used.
(5) Apart from the concise description method shown in . Table 5.1, plot() can
also be called in the following syntax:
plot(∼,parameter 1,value 1,parameter 2,value 2,· · · )
where ∼ indicates the above normal syntaxes. The commonly used parameters and
their values are shown in . Table 5.2.
104 Chapter 5 · MATLAB Graphics

. Table 5.1 Various options in MATLAB plotting commands

Line type Line color Marker symbols

Options Meaning Options Meaning Options Meaning Options Meaning Options Meaning

'-' Solid 'b' Blue 'c' Cyan '*' Star 'Pentagram' ✩

'--' Dash 'g' Green 'k' Black '.' Dots 'o' Circle

':' Dotted 'm' Magenta 'r' Red 'x' Cross 'Square' 

'-.' Dash- 'w' White 'y' Yellow 'v'  'Diamond' ♦


dot
5 'None' None '^'  'Hexagram' ✡

'>'  '<' 

. Table 5.2 Commonly used options for the plotting command

Option names Descriptions

LineSpec Line type control, for instance, 'r-.pentagram'. See . Table 5.1

LineWidth Line width, default 0.5pt, where 1pt=0.3527mm. The line width in the
book is set to 1pt

MeshDensity Automatically generated density of dots, with default of 23. Mainly used
in the functions fimplicit() and fplot(). Increase the value may
increase the precision of the curves

Color Color of lines. Apart from the 8 colors in . Table 5.1, it can also be set to
RGB components [r,g,b]

MarkerEdgeColor In fact, it is the color of the marker

MarkerSize The size of the marker, with default of 6pt

(6) Command h=plot(∼) draws the plot, and the handle of the plot is returned
in h. If a plot is drawn in the axis with handle h, command plot(h,t, y,· · · ) can be
issued.

 Example 5.3
Consider the mathematical model of a fractal tree. Select an initial point (x0 , y0 ) on a 2D
plane. Generate uniformly distributed random numbers γi in the interval [0, 1]. Based on
its value, the following formula generates a new point: (x1 , y1 ) [1].
5.1 · Simple Two-Dimensional Plots
105 5


⎪ x1 = 0, y1 = y0 /2, γi < 0.05


⎨x = 0.42(x0 −y0 ), y1 = 0.2 + 0.42(x0 +y0 ), 0.05 ≤ γi < 0.45
1
(x1 , y1 ) ⇐

⎪ 1
x = 0.42(x0 +y0 ), y1 = 0.2 − 0.42(x0 −y0 ), 0.45 ≤ γi < 0.85



x1 = 0.1x0 , y1 = 0.2 + 0.1y0 , otherwise.

Generate 10000 points and draw the positions of the points with dots.
Solutions The fractal tree data can be generated with the following statements, such that
two vectors x and y can be constructed. Therefore, with the following statements, the fractal
tree shown in . Fig. 5.3 can be found.

>> v=rand(10000,1); N=length(v); x=0; y=0;


for k=2:N, gam=v(k); % for each value of γi , update x and y
if gam<0.05, x(k)=0; y(k)=0.5*y(k-1);
elseif gam<0.45
x(k)=0.42*(x(k-1)-y(k-1)); y(k)=0.2+0.42*(x(k-1)+y(k-1));
elseif gam<0.85
x(k)=0.42*(x(k-1)+y(k-1)); y(k)=0.2-0.42*(x(k-1)-y(k-1));
else, x(k)=0.1*x(k-1); y(k)=0.1*y(k-1)+0.2;
end, end
plot(x,y,'.','MarkerSize',5) % note that the dot option cannot be ignored


5.1.2 Function Expression-based Plotting


If the mathematical function is known, function fplot() draws the curve, with the
syntax fplot(f ), where, f is an anonymous function handle to describe the mathe-
matical function, or a symbolic expression or a symbolic function. The default plotting
range is x ∈ [−5, 5]. To specify the plotting range, the syntax is fplot(f ,[xm ,xM ])
is used.

0.45

0.4

0.35

0.3

0.25

0.2

0.15

0.1

0.05

0
-0.25 -0.2 -0.15 -0.1 -0.05 0 0.05 0.1 0.15 0.2 0.25

. Fig. 5.3 Fractal tree display


106 Chapter 5 · MATLAB Graphics

The function ezplot() in earlier versions of MATLAB also draws the curves,
with default range of [−2π, 2π]. The syntax of this function is not presented here.

 Example 5.4
Draw the curve of the function in Example 5.1 with fplot() command.
Solutions Symbolic function describes the mathematical function, and the following com-
mands draw the 2D plot, as shown in . Fig. 5.4. It can be seen that the result is almost the
same as the one obtained earlier. The dash line at x = −π/2 is drawn automatically.

>> syms x;
f(x)=sin(tan(x))-tan(sin(x)); fplot(f,[-pi,pi])
5 Anonymous function can also be used to describe the mathematical function. The same
results can be found. When using anonymous functions, dot operations are needed. For
this particular example, the functions sin() and tan() are equivalent to dot operations.

>> f=@(x)sin(tan(x))-tan(sin(x)); fplot(f,[-pi,pi])




Similar to plot() function, fplot() function also supports various other syn-
taxes. For instance, if there are several mathematical functions, command fplot([f1 ,
f2 ,· · · ,fn ]) can be issued, where fi is the handle of the ith symbolic expression. If
anonymous functions are defined, curly brackets rather than square brackets are
used. Besides, different options can be provided, and the handle can also be returned.

 Example 5.5
Consider the sinusoidal function f (t) = sin x. It is known from college mathematics that
Taylor series can be used to approximate the function. A finite-term Taylor series is y(t) =
x9 /362880 − x7 /5040 + x5 /120 − x3 /6 + x. Draw the two curves together in the same
coordinate, where x ∈ [−4, 4]. Assess the fitting quality of approximate function.

-1

-2

-3
-3 -2 -1 0 1 2 3

. Fig. 5.4 Draw the function plot with fplot() function


5.1 · Simple Two-Dimensional Plots
107 5
Solutions Symbolic expressions are used to describe the original function and Taylor series
approximation. Then function fplot() draws the two functions together, as shown in
. Fig. 5.5. In the plot, the Taylor series curve is manually set to dash line.
>> syms x; f=sin(x); y=x^9/362880-x^7/5040+x^5/120-x^3/6+x;
fplot([f,y],[-4 4]) % draw the two functions together
If anonymous function is used to express the mathematical functions, use dot operations.
Note that curly brackets must be used here.

>> f=@(x)sin(x); y=@(x)x.^9/362880-x.^7/5040+x.^5/120-x.^3/6+x;


fplot({f,y},[-4 4]) % draw the two functions together


5.1.3 Plots of Parametric Equations


For the given parametric equation,

x = x(t), y = y(t), tm ≤ t ≤ tM , (5.1)

where x(t) is described by handle hx , while y(t) is expressed by handle hy , and the
handles can be symbolic expressions or anonymous functions, command fplot(hx ,
hy ,[tm ,tM ]) draws its trajectory.

 Example 5.6
Lissajous figure is generated by the parametric equation of two sinusoidal functions with
different frequencies. Draw the Lissajous figure for x(t) = sin t, y = sin 1.25t, where
t ∈ [0, 30].
Solutions Symbolic expressions are used to describe the parametric equation, and draw the
Lissajous figure, as shown in . Fig. 5.6.

>> syms t; x=sin(t); y=sin(1.25*t); fplot(x,y,[0,30])

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-4 -3 -2 -1 0 1 2 3 4

. Fig. 5.5 Comparisons of the two curves


108 Chapter 5 · MATLAB Graphics

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
5 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1

. Fig. 5.6 Lissajous figure

Under the default settings, the fplot() function selects plotting options automatically.
For instance, if [tm ,tM ] is given, the increment can be selected automatically. Sometimes
erroneous results may be found. The control options such as Meshdensity should be
assigned accordingly so as to get the correct results. 

 Example 5.7
Consider again the Lissajous figure in Example 5.6. If the interval t ∈ [0, 1000] is selected,
erroneous figure can be obtained. How to get the correct figure?
Solutions The following commands can be executed, the erroneous Lissajous figure can be
obtained directly, as shown in . Fig. 5.7.

>> syms t; x=sin(t); y=sin(1.25*t); fplot(x,y,[0,1000])

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1

. Fig. 5.7 Erroneous Lissajous figure


5.1 · Simple Two-Dimensional Plots
109 5
The option Meshdensity can be set accordingly. For instance, set its value to 300 or
larger ones, such that the correct Lissajous figure in . Fig. 5.6 can be found.
>> fplot(x,y,[0,1000],'MeshDensity',300)


Similar to the plot() function, the result of fplot() function automatically


found should also be validated. One way is to set different values to the MeshDensity
option. Generally speaking, larger values may yield more accurate results. If different
MeshDensity values of the options are used, and consistent curves are obtained, the
option selection is reasonable.

5.1.4 Plots with Two y Axes


It has been stated that with plot() function, several curves can be drawn together.
In certain applications, if the magnitudes of two curves differ significantly, double y-
axis mode should be selected. The specific method is to use yyaxis left and yyaxis
right commands to set the axes, then draw the curves separately. Function plotyy()
in the earlier versions can still be used, it is not recommended here.

 Example 5.8
Consider two functions y1 = sin x and y2 = 0.01 cos x, compare their curves.
Solutions Of course, function plot() draws directly the two functions. However, since
their magnitudes differ significantly, y2 curve looks like a horizontal line. Therefore, two
vertical axes can be set, and the curves can be drawn separately under different axes, as
shown in . Fig. 5.8. It can be seen that the y-axis scales of the solid line are marked on the
left, while the dash one is marked on the right. In this way, the two curves can be displayed
in a better format.
>> x=0:0.01:2*pi; y1=sin(x); y2=0.01*cos(x);
yyaxis left; plot(x,y1), yyaxis right; plot(x,y2,'--')


5.1.5 Graph Decorations and Editing


When the curves are drawn, further decorations and processing to them can be made.
In . Table 5.3, several commands for plot decoration and processing are listed. These
commands can be used to manipulate plots. Alternatively, the tools provided in the
toolbar can also be used.
The submenus of Insert menu in the MATLAB graphics window is shown in
. Fig. 5.9. For typesetting purposes, the menu is divided into three parts. The main
menu system is also shown in . Fig. 5.9a. It can be seen that most of the functions
and commands in . Table 5.3 can be visited directly from the Insert menu items.
The View menu in MATLAB graphics window is shown in . Fig. 5.10a, where
if the first three items are checked, the toolbars are shown in . Fig. 5.10b, Under
110 Chapter 5 · MATLAB Graphics

1 0.01
0.8 0.008
0.6 0.006
0.4 0.004
0.2 0.002
0 0
-0.2 -0.002
-0.4 -0.004
-0.6 -0.006
-0.8 -0.008
-1 -0.01
0 1 2 3 4 5 6
5
. Fig. 5.8 Function curves with two vertical axes

(a) menu system and upper portion (b) middle one (c) lower one
. Fig. 5.9 Insert menu in MATLAB graphics window

(b) fully opened toolbars

(a) View menu (c) axis tool


. Fig. 5.10 View menu and toolbars

default mode, only the first line of tools is displayed. Click the button in the toolbar,
the graphs are in edit mode. If unchecked, the edit mode is canceled. If the cursor is
moved inside an axis, the axis toolbar appears in the upper right corner of the axis,
shown in . Fig. 5.10c.
5.2 · Special Two-Dimensional Plots
111 5

. Table 5.3 Commonly used plot decoration commands

Commands Syntaxes and descriptions

title() title(str). Adds a title to the plot, with the title string str

xlabel() xlabel(str). Adds x-axis label, also use ylabel(str) command

text() text(x,y,str). Adds text to the plot at specified locations (x, y)

gtext() gtext(str). Adds text description, but the location is selected by mouse

legend() legend(s1 ,s2 ,· · · ). Adds legends to the plot, where the text description sk is the
text for the kth curve

annotation annotation(s,x, y). Adds descriptions to the plot, where s is the type of
description, which can be selected as 'arrow', 'line', 'doublearrow' and so
on. The description can be described as [x1 ,x2 ] and [y1 ,y2 ], with the former for
start point, and the latter for end point

hold hold on. Command hold on or hold off to hold or free the axis. If an axis
is held, plot() command superimposes plots on the existing ones. Command
hold off frees the axis. Command key=ishold is check the status, which
returns 0 or 1
zoom zoom on. Zooming facilities. Use mouse to select the region to be zoomed. zoom
off command cancels the zooming status. Commands zoom xon and zoom yon
zoom a particular axis

5.1.6 Extracting Data from Plots


The menu system in MATLAB graphics window allows the user to save the current
plot into a file, with suffix fig. To restore the plot, use menu item and load the .fig
file into the window. To get the data from the current data, or load .fig file to extract
data, enter the edit mode, then click the interested curve to select it, then, use gco (get
current object) command to get the handle of the curve, the data can be extracted
with get() function
x=get(gco,'xData'); y=get(gco,'yData');
A series of MATLAB functions like gco are provided, for instance, gcf (get current
figure), gca (get current axis). Command clf clears the current figure window.

5.2 Special Two-Dimensional Plots


Besides the plot() and fplot() functions discussed earlier, line() function super-
imposes lines on the current plot. The difference is that line() function accepts only
two input arguments.
Other commonly used 2D graphics functions supported in MATLAB are shown
in . Table 5.4. In this section, some of the commonly used ones are demonstrated.
112 Chapter 5 · MATLAB Graphics

. Table 5.4 Commonly used special graphics functions

Syntax Descriptions Syntax Descriptions

comet(x, y) Comet trajectory bar(x, y) 2D bar plot

compass(x, y) Compass plot errorbar(x, y, ym , yM ) Error plot

feather(x, y) Feather plot fill(x, y, c) 2D filled plot

hist( y,n) Histogram loglog(x, y) Log plot

quiver(x, y) Quiver plot polarplot(x, y) Polar plot

5 stairs(x, y) Staircase plot semilogx(x, y) x axis in logarithmic

stem(x, y) Stem plot semilogy(x, y) y axis in logarithmic

5.2.1 Polar Plots


The polar coordinate system is a 2D coordinate system in which each point on a
plane is determined by a distance ρ from a reference point and an angle θ from a
reference direction. The ordered pair (ρ, θ ) is the polar coordinate. The explicit polar
coordinate is expressed ρ = ρ(θ ), referred to as polar equation. Under traditional
definition, ρ ≥ 0. It can be extended to real space. The equation can be understood
as generalized polar equations.
Function polarplot() is provided in MATLAB, with the syntax polarplot
(θ ,ρ), where θ and ρ are given vectors. The earlier version of polar() is still used.
Even though ρ < 0, polar plot can still be drawn under coordinate system transfor-
mation. If the curves when ρ < 0 is not expected, the functions values when ρ < 0 can
be set to NaN, such that the points are not shown on the polar plots.

 Example 5.9
Draw the polar plot of the function ρ = 5 sin(4θ/3).
Solutions In elementary mathematics courses, it is known that the period of the function
is 3π/2. To draw the polar plot, a vector θ can be generated first, and the function value
vector ρ can be found. Calling the polarplot() function, the polar plot is . Fig. 5.11a
can be found.

>> theta=0:0.01:3*pi/2; rho=5*sin(4*theta/3); % generate polar vectors


polarplot(theta,rho) % draw polar plot
If the part when ρ < 0 is omitted, the function values when ρ < 0 can be set to NaN.
Therefore, the corresponding points are not displayed, and the new polar plot is shown in
. Fig. 5.11b.
>> rho(rho<0)=NaN; polarplot(theta,rho) % exclude the NaN points
5.2 · Special Two-Dimensional Plots
113 5

90° 90°
5 5
120° 60° 120° 60°
4 4

3 3
150° 30° 150° 30°
2 2

1 1

180° 0 0° 180° 0 0°

210° 330° 210° 330°

240° 300° 240° 300°


270° 270°

(a) ∈ (0, 3π/ 2) (b) polar plot when 0

. Fig. 5.11 Polar plots

It seems that the polar plot thus obtained is not complete. How to get complete polar plot?
Many polar functions are periodic. If the correct period is found, the complete polar plot
can be obtained. This leads us to a new question—how to determine the period? In fact,
there is in reality no need to find out the actual period. To draw the complete polar plot,
just select a large range of vector θ . For instance, 0 ≤ θ ≤ 20π or larger range. The complete
polar plot is shown in . Fig. 5.12a. In fact, the actual period is 6π. If only the polar plot
when ρ ≥ 0 are expected, the new polar plot is shown in . Fig. 5.12b.

>> theta=0:0.01:20*pi; rho=5*sin(4*theta/3); % generate new vector


polarplot(theta,rho) % draw polar plot
figure; rho(rho<0)=NaN; polarplot(theta,rho)


90° 90°
5 5
120° 60° 120° 60°
4 4

3 3
150° 30° 150° 30°
2 2

1 1

180° 0 0° 180° 0 0°

210° 330° 210° 330°

240° 300° 240° 300°


270° 270°

(a) ∈ (0, 20π) (b) ≥ 0

. Fig. 5.12 Polar plot over a larger range


114 Chapter 5 · MATLAB Graphics

 Example 5.10
Draw the polar plot for the aperiodic function ρ = e−0.1θ sin 3θ .
Solutions Select the range of the θ variable to θ ∈ (0, 10π), the data for the polar plot can
be generated, such that the polar plots in . Fig. 5.13a and (9) can be obtained.

>> theta=0:0.001:10*pi;
rho=exp(-0.1*theta).*sin(3*theta); polarplot(theta,rho)
figure; rho(rho<0)=NaN; polarplot(theta,rho)
Many polar functions are periodic. Therefore, select the points θ in a certain range, the
complete polar plot can be found. This function is not a periodic one. Thus, no matter what
the range is chosen, the polar plot is not a complete one. 
5
5.2.2 Representation of Discrete Signals
Definition of discrete signals is presented first. The MATLAB-based representation
of discrete signals is presented, and the output signal through zero-order hold is
obtained.
Discrete sequence can be expressed as time series y1 , y2 , · · · , yn . Discrete signals
can of course be represented directly with plot() function. It is more appropriate to
use stem() function to draw stem plot, with syntax stem(t, y), where t is the time
vector. If the discrete signal is connected to a zero-order hold (ZOH), the signal is kept
constant within each sample time. Such a function can be displayed with stairs()
function, with the syntax stairs(t, y).

 Example 5.11
Assume that the mathematical form of discrete signal is f (t) = sin t sin 7t, where t = kT ,
k = 0, 1, · · · , 31, T = 0.1 s is known as sample time, indicating in each 0.1 seconds, the
signal is measured once. Use graphical method to represent sequence.

90° 90°
1 1
120° 60° 120° 60°
0.8 0.8

0.6 0.6
150° 30° 150° 30°
0.4 0.4

0.2 0.2

180° 0 0° 180° 0 0°

210° 330° 210° 330°

240° 300° 240° 300°


270° 270°

(a) generalized polar plot (b) the ≥ 0 part

. Fig. 5.13 Polar plot of the aperiodic function


5.2 · Special Two-Dimensional Plots
115 5
Solutions With the sample time, the following commands generate time vector t, and
compute the function values. Graphical representation of the results can be obtained, as
shown in . Fig. 5.14a.

>> T=0.1; t=(0:31)*T; % generate time samples


f=sin(t).*sin(7*t); stem(t,f) % compute function values and plot
If the function stem() is replaced by stairs(), the staircase plot can be obtained, as
shown in . Fig. 5.14b.

>> stairs(t,f) % draw the staircase plot




5.2.3 Statistical Plots


Histograms and pie charts are commonly used graphical tools in statistics. In this
section, the definitions of histogram and frequencies are defined first. Examples are
presented to show the use of histograms and pie charts.
Assume that a set of discrete samples x1 , x2 , · · · , xn are measured. These samples
are distributed in the (a, b) interval. Therefore, the interval can be divided into m

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3 3.5
(a) stem plot
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3 3.5
(b) staircase plot

. Fig. 5.14 Representation of discrete signal


116 Chapter 5 · MATLAB Graphics

equally spaced subintervals, such that b1 = a and bm+1 = b. The random numbers xi
are thrown into the subintervals according to its values. Denote that the number of
points falling into the interval (bj , bj+1 ) is kj , j = 1, 2, · · · , m, the quantities known
as frequency can be obtained from fj = kj /n.
Function histogram() computes frequency vector in each subinterval
k=histogram(x,b); % the returned k is a structured variable
f =k.Values/n; bar(b(1:end-1)+δ/2, f /δ);
where δ = x2 − x1 is the width of equally spaced subintervals. Select vectors b and f ,
the frequency histogram can be drawn. Note that, the length of the vectors obtained
by the histogram function is short by 1 than the b vector. Besides, b vector can be
5 shifted half the subinterval width backward in the function bar(). Then the new
histogram() function can be called. It is not recommended to use hist() functions
in the earlier versions. Examples are presented next to demonstrate the presentation
of histogram and other graphical presentations.

 Example 5.12
Select a parameter b = 1, a 30000×1 pseudorandom vector satisfying Rayleigh distribution
can be generated. Validate with histogram method and see whether the data generated
satisfy the expected distribution.
Solutions Generate a 30000 × 1 pseudorandom vector with raylrnd() function. Select
a vector x, function histogram() counts the numbers falling into each subinterval. The
returned argument is a structured variable, whose Values member contains the numbers
falling in each subinterval. Function bar() draws the approximate probability density
function, as shown in . Fig. 5.15. The theoretical value of the probability density function
of Rayleigh distribution can be found. It can be seen that the matching of the two agree
well.

>> b=1; p=raylrnd(1,30000,1); x=0:0.1:4; % subinterval creations


y=histogram(p,x); yy=y.Values/(30000*0.1); % histogram data
x0=x(1:end-1)+0.05; bar(x0,yy), y=raylpdf(x,1); line(x,y) % exact ones

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5 4

. Fig. 5.15 Probability density function and its approximation


5.2 · Special Two-Dimensional Plots
117 5
The bar plot for probability density function from measured data can be alternatively
drawn with the following command, and the same bar plot can be obtained.

>> histogram(p,x,'Normalization','pdf')


From the frequency vector f obtained, pie chart can be drawn, with the syntax
pie( f ). In the pie chart, the percentage of the points falling into the subintervals is
displayed.

 Example 5.13
Consider again the data in Example 5.12. Fewer subintervals can be made [0, 0.5], (0, 5, 1],
· · · , (3.5, 4]. Use pie chart for the interval distribution.
Solutions The frequency vector can be constructed with the above-demonstrated method.
Based on the frequency vector, the pie chart can be drawn, as shown in . Fig. 5.16.

>> b=1; p=raylrnd(1,30000,1);


x=0:0.5:4; y=histogram(p,x); f=y.Values/30000; pie(f), f1=f*100
It can be seen that the pie chart display is quite straightforward, but the correspondences
between the pie chart portions and the subintervals are not very clear. The percentage vector
is f1 = [11.5, 28.2, 27.8, 19.1, 8.9, 3.4, 0.8, 0.2]%. 

5.2.4 Filled Plots


If a set of coordinates A1 (x1 , y1 ), A2 (x2 , y2 ), · · · , An (xn , yn ) are known, the poly-line
from A1 to An can be drawn, also the line from An to A1 is drawn, such that a closed-
path can be obtained. MATLAB provides a function fill(), to fill the interior of the
closed-path with a specific color, such that filled plots can be drawn. The syntax of
the function is fill(x, y,c), where c is the color identifier. For instance, the option

< 1% 3%
12% < 1%
9%

19%
28%

28%

. Fig. 5.16 Pie chart


118 Chapter 5 · MATLAB Graphics

'g' can be used to represent green color, see . Table 5.1. The option c can also be
a vector for the primary colors, such as [1, 0, 0] for red.
To let the coordinates Ai and the x axis to form a closed-path, and x vector
is arranged in ascending order, two extra points can be added to the vectors. For
instance, the two extra points (x1 , 0) and (xn , 0) can be added, such that x = [x1 , x, xn ]
and y = [0, y, 0]. Function fill() can then be used to draw the filled plot.

 Example 5.14
Consider the Rayleigh distribution studied in Example 5.12. Use color filling method to
draw the probability density function curve such that 95% of area is covered.
5 Solutions Generate a row vector x ∈ (0, 4), the probability density function values of
Rayleigh distribution can be found. In this example, the important step is to find the key
point, where 95% of area is covered. This point can be evaluated directly with function
raylinv(), denoted by x0 . It is found from the following commands that x0 = 2.4477.
Since at the left end x = 0, the PDF value is 0. Therefore, there is no need to introduce
an extra point here. At the right end, the points in x satisfying x < x0 can be extracted.
Two extra points at x0 can be added to the vector. The corresponding values at x0 are
respectively the PDF value and 0, such that the bounded area is within a closed-path. The
obtained filled plot is shown in . Fig. 5.17.

>> x=0:0.1:4; b=1; y=raylpdf(x,b); x0=raylinv(0.95,b)


ii=x<=x0; x1=[x(ii) x0, x0]; y1=[y(ii),raylpdf(x0,b),0];
plot(x,y), hold on; fill(x1,y1,'g'), hold off


5.2.5 Logarithmic Plots


In specific fields, such as digital signal processing and automatic control, frequency
domain analysis of signals and systems, are often encountered. Bode diagram is an
effective way in frequency domain analysis.

0.7

0.6

0.5

0.4

0.3

0.2
0 = 2.4477
0.1

0
0 0.5 1 1.5 2 2.5 3 3.5 4

. Fig. 5.17 Rayleigh cumulative density function and 95% area


5.2 · Special Two-Dimensional Plots
119 5
At frequencies ωk , the variable s = jω1 , jω2 , · · · , jωm can be created, and the values
of the transfer function G(s) can be evaluated. The gain G(jω) are in fact complex quan-
tities. The magnitude |G(jω)| and phase ∠G(jω) describe the complex quantities. Nor-
mally, Bode diagram is composed of two plots, representing the relationship between
frequency with magnitude and phase, respectively. The horizontal axis represents fre-
quency, arranged in logarithmic scale. The magnitude can be further transformed to
20 lg |G(jω)|, with unit deci-Bell (dB). The unit of the phase is degree.
If in a plot, the horizontal axis is in logarithmic scale, while the vertical one is
linear, function semilogx() draws the plot directly. If the horizontal axis is in linear
scale, while the vertical one is in logarithmic scale, function semilogy() can be used.
If both the two axes are in logarithmic scale, function loglog() can be used.

 Example 5.15
Consider the transfer function model

2(s0.4 − 2)0.3
G(s) = √ .
s(s0.3 + 3)0.8 (s0.4 − 1)0.5

Selecting frequency points in ω ∈ (0.01, 1000), draw the relationship between magnitude
and frequency in Bode diagram format.
Solutions In normal cases, the frequency points are generated directly such that the frequen-
cies are distributed in equally spaced under logarithmic scale. Therefore, from the given
transfer function model, the magnitude can be evaluated in dB scale. The semi-logarithmic
plot is then obtained, as shown in . Fig. 5.18.

>> G=@(s)2*(s.^0.4-2).^0.3./sqrt(s)./(s.^0.3+3).^0.8./(s.^0.4-1).^0.5;
w=logspace(-2,3,100); M=20*log10(abs(G(1i*w))); % convert to dB
semilogx(w,M) % draw semi-logarithmic plot


30

20

10

-10

-20

-30

-40

-50
-2 -1 0 1 2 3
10 10 10 10 10 10

. Fig. 5.18 Bode magnitude plot


120 Chapter 5 · MATLAB Graphics

5.2.6 Dynamic Trajectory and Animation


Static curve plotting facilities are discussed earlier. If a curve is regarded as the tra-
jectory of a particle moving from one place to another, the above-mentioned method
may only display the static result. How to witness the moving trajectory of the par-
ticle? If function plot() is substituted by comet(), the dynamic trajectory of the
particle can be displayed.

 Example 5.16
Draw dynamically the movement trajectory of the particle in Example 5.1.
5 Solutions Select a step size of 0.001, the following commands can be used to dynamically
show the trajectory of the moving particle.

>> x=-pi:0.001:pi; y=sin(tan(x))-tan(sin(x)); comet(x,y)




It seems that the trajectory of the particle movement can be drawn dynamically
from the commands. Consider now another application situation. If a plotting com-
mand is followed by time-consuming computational commands, the plotting com-
mand will not be executed immediately under the MATLAB mechanism. After the
execution of the computational commands, the plot can then be drawn. This mech-
anism is not good in making animations. MATLAB command drawnow executes
immediately the plotting command, and suspends the following computational com-
mands. Using this method, animation can be implemented.
Another key point in creating animation is how to update the positions of data
such that they can be made live. If function plot() returns the handle, the data are
stored in the fields XData andYData. The new positions can be computed and passed
to the fields, such that the position information can be updated, and the animation
effect can be implemented. Examples are presented next to demonstrate the animation
processing methods.

 Example 5.17
Consider a swarm of particles in Brownian motion. The number of particles is n = 30, and
the observation region is [−30, 30]. The position of each particle is xi+1,k = xi,k + σ xi,k
and yi+1,k = yi,k + σ yi,k , k = 1, · · · , n, where, σ is the scaling factor. The increments
xi,k and yi,k satisfy standard normal distribution. Make animation of the particles in
Brownian motion.
Solutions The pseudorandom numbers satisfying standard normal distribution can be
generated directly with function randn(). Selecting a scaling factor σ = 0.3, the animation
can be carried out in an infinite loop. The animation process can be terminated at any time
by pressing Ctrl+C keys.

>> n=30; x=randn(1,n); y=randn(1,n); s=0.3; % generate random numbers


figure(gcf), hold off; % bring graphics window to the front
h=plot(x,y,'o'); axis([-30,30,-30,30]) % fix the axis
while (1) % infinite loop for animation
x=x+s*randn(1,n); y=y+s*randn(1,n); % compute new positions
5.3 · Three-Dimensional Plots in MATLAB
121 5
h.XData=x; h.YData=y; drawnow % update particle positions
end


5.2.7 Graphics Window Divisions


In real applications, usually, we need to divide the graphics window into several por-
tions. In each portion, a different plot can be drawn. Regular and irregular partition
methods are presented, and applications of the methods are illustrated.
Regular partition means that the entire graphics window is divided into m × n
partitions, such that different plots can be drawn in the partitions. Regular partition
method is very useful in real applications. Function subplot() carries out graphics
window partition, with the command subplot(m,n,k), where k is the number of the
partition. An output argument can be obtained, in the syntax h=subplot(m,n,k),
with h the handle of the partitioned axis.

 Example 5.18
Draw the Bode diagram of the fractional-order system G(s) in Example 5.15.
Solutions In Bode diagrams, graphical window is divided into two partitions, the upper
one and lower one. It is quite suitable to use subplot() function to divide the window,
that is, to divide it into 2 × 1 partitions, with the upper one marked 1, and the lower one,
2. After partition, the magnitude−frequency plot and phase−frequency plots can be drawn,
respectively, in the two partitions. The magnitude−frequency plot in be obtained with the
commands in Example 5.15, and the phase−frequency plot should be used to be directly
computed from the corresponding formula. The plots are shown in . Fig. 5.19.

>> G=@(s)2*(s.^0.4-2).^0.3./sqrt(s)./(s.^0.3+3).^0.8./(s.^0.4-1).^0.5;
w=logspace(-2,3,100); subplot(211) % or use subplot(2,1,1)
G0=G(1i*w); M=20*log10(abs(G0)); semilogx(w,M) % magnitude plot
subplot(212), P=angle(G0)*180/pi; semilogx(w,P) % phase plot


Irregular partition means to use the Insert → Axis menu item to insert an axis. The
user is allowed to draw a desired axis with mouse. Therefore, new commands can be
used to draw plots in the newly added axis.

5.3 Three-Dimensional Plots in MATLAB


Some mathematical functions and measured data can be represented in curves or
surface in a 3D axis, depending on the form and definition of the functions and data.
In this section, 3D graphics are presented.
122 Chapter 5 · MATLAB Graphics

20

-20

-40
-2 -1 0 1 2 3
10 10 10 10 10 10
-50

-60

-70

5
-80
-2 -1 0 1 2 3
10 10 10 10 10 10

. Fig. 5.19 Bode diagram of a fractional-order system

5.3.1 Three-Dimensional Curves


Consider a particle moving in a 3D space. If at time t, the location of the particle is
described by the parametric equation x(t), y(t) and z(t), the trajectory of the particle
forms a 3D curve.
Function plot() can be extended into its 3D version in plot3() function, with
the syntaxes
plot3(x, y,z)
plot3(x 1 , y1 ,z 1 ,option1 ,x 2 , y2 ,z 2 ,option2 ,· · · ,x m , ym ,z m ,optionm )
where options are the same as the ones in 2D plots shown in . Table 5.1. The vectors
x, y and z store the locations of the particle at time t.
Similar to 2D cases, other 3D graphics facilities are supported. For instance,
stem3() draw the 3D stem plots, fill3() draws the filled plots, while bar3() draws
the 3D bar charts. If function comet3() is used, 3D dynamical trajectory can be
displayed. The syntaxes of these functions are quite similar to their 2D counterparts.

 Example 5.19
Draw the 3D curve of the parametric equation x(t) = t3 e−t sin 3t, y(t) = t3 e−t cos 3t and
z = t2 .
Solutions To draw the curve of the parametric equation, a time vector t can be generated
first. The vectors x, y and z can be computed. With function plot3(), the 3D curve can
be drawn, as shown in . Fig. 5.20. Note that, dot operations must be used in computing
the function values.
>> t=0:0.01:2*pi; % pay attention to the dot operations next
x=t.^3.*exp(-t).*sin(3*t); y=t.^3.*exp(-t).*cos(3*t); z=t.^2;
plot3(x,y,z), grid % draw 3D curve and show the grids


5.3 · Three-Dimensional Plots in MATLAB
123 5

. Fig. 5.20 Three-dimensional curve

5.3.2 Three-Dimensional Parametric Equation Curves


If the mathematical forms of the parametric equation x(t), y(t) and z(t) are known,
function fplot3() draws directly the 3D curve, in the syntaxes
fplot3(fx ,fy ,fz ), fplot3(fx ,fy ,fz ,[tm ,tM ])
where fx , fy and fz are the function handles of the parametric equation, either in
symbolic expressions, or in anonymous functions. The default range of t is [0, 5].

 Example 5.20
Consider again the spatial particle function in Example 5.19. Draw the 3D surface plot
directly from the mathematical formula.
Solutions The parametric equation can be described by the symbolic expression. Therefore
the following commands can be issued. Function fplot3() can be called so that the same
plot in Example 5.19 can be obtained.

>> syms t; x=t^3*exp(-t)*sin(3*t);


y=t^3*exp(-t)*cos(3*t); z=t^2; fplot3(x,y,z,[0,2*pi])
The parametric equation can also be expressed with anonymous function, and the fol-
lowing commands draw the same surface plots.
>> x=@(t)t.^3.*exp(-t).*sin(3*t); y=@(t)t.^3.*exp(-t).*cos(3*t);
z=@(t)t.^2; fplot3(x,y,z,[0,2*pi]);

5.3.3 Three-Dimensional Surfaces


If a 2D function is z = f (x, y), some mesh grids can be generated from the xy plane.
Then the function values z on each mesh grid point can be evaluated. Based on these
data, the 3D surface of the function can be drawn.
124 Chapter 5 · MATLAB Graphics

The mesh grid generation method with meshgrid() function has been demon-
strated in Example 3.13, where two matrices x and y are generated. If the two matrices
are piled up, the coordinates x and y of each mesh grid is created. If the mathematical
function z = f (x, y) is known, dot operations evaluate function values at the mesh
grid points z. With the three matrices, functions mesh() and surf() draw directly
the mesh plot and surface plot. The syntaxes of the two functions are mesh(x, y,z)
and surf(x, y,z). Function surf() also returns the handle of the surface, such that
the next operations on the surface can be carried out.

 Example 5.21
For the 2D function z = f (x, y) = (x2 − 2x)e−x −y −xy , where −3 ≤ x ≤ 2 and −2 ≤
2 2
5 y ≤ 2. Draw the 3D surface plot for the function.
Solutions Selecting an increment 0.1, then call meshgrid() function to generate mesh grid
matrices x and y on the xy plane. From the given formula, the function value matrix z can
be worked out. Function surf() can then be used to draw the 3D surface, as shown in
. Fig. 5.21.
>> [x,y]=meshgrid(-3:0.1:2,-2:0.1:2); % the mesh grid matrices x and y
z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); % compute function vslues z
surf(x,y,z) % draw 3D surface


If the mathematical form of the 2D function is known, function fsurf() can


also be used to draw the surface, with the syntaxes fsurf(f ) or fsurf(f ,[xm ,xM ,ym ,
yM ]), where f is the symbolic expression or anonymous function handle. The default
plotting range is −5 ≤ x, y ≤ 5.

 Example 5.22
Draw the 3D surface in Example 5.21 with fsurf() function.
Solutions Symbolic expression can be used to describe the function. Then function fsurf()
draws the 3D surface of the function, which is the same as the one in . Fig. 5.21.

. Fig. 5.21 Surface of the function


5.3 · Three-Dimensional Plots in MATLAB
125 5
>> syms x y; f=(x^2-2*x)*exp(-x^2-y^2-x*y); % express symbolic expression
fsurf(f,[-3,2,-2,2]) % draw the surface in the expected range
Anonymous function can also be used to express the given function, where dot operations
must be used, to replace f . Function fsurf() above draws the surface, where identical
results are found.
>> f=@(x,y)(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); fsurf(f,[-3,2,-2,2])

5.3.4 Viewpoint Setting


Click the icon in the axis toolbar in a graphics window (. Fig. 5.10c), mouse
button dragging method changes directly the viewpoint in a visual way. An alternative
method is to set the viewpoint with the view() function.
The definition of 3D viewpoint is shown in . Fig. 5.22. The viewpoint is described
uniquely by two angles, the azimuth α and the elevation β. The azimuth is defined as
the angle between the projection line and the negative y-axis. The projection line is the
projection of the line from the viewpoint to the origin on the xy plane, with default
value of α = −37.5◦ . The elevation β is the angle between the line from the viewpoint
to the origin and the xy plane, with default value β = 30◦ . Command [α,β]=view(3)
extracts the current angles. To change the viewpoint, the command view(α, β) can
be used.
In engineering sketching, orthographic views are often used to view objects. The
overhead view looks at the object in a downward direction. The elevation is 90◦ and
the azimuth is 0◦ . Therefore, the command view(0,90) sets the viewpoint. Similarly,
commands view(0,0) and view(90,0) can be used to set the front view and side
view. When the surface is drawn with surf() function, the viewpoint is set with these
commands so as to achieve orthographic views. The orthographic view display of a
surface is demonstrated next using an example.

axis viewpoint

axis

elevation
axis

azimuth

. Fig. 5.22 Viewpoint illustration


126 Chapter 5 · MATLAB Graphics

 Example 5.23
Consider again the function in Example 5.21. Draw the orthographic views of the surface.
Solutions The graphics window can be divided into 2 × 2 partitions. Therefore, different
commands can be used to draw orthographic views in the corresponding partitions, as
shown in . Fig. 5.23.

>> syms x y; f=(x^2-2*x)*exp(-x^2-y^2-x*y);


subplot(221), fsurf(f,[-3,2,-2,2]), view(0,90) % plan view
subplot(222), fsurf(f,[-3,2,-2,2]), view(-90,0) % side view
subplot(223), fsurf(f,[-3,2,-2,2]), view(0,0) % front view
subplot(224), fsurf(f,[-3,2,-2,2]) % 3D surface
5 

5.3.5 Surface of Parametric Equations with Two Parameters


The parametric equation with one parameter is discussed earlier, which yields a 3D
curve. If the parametric equation has two parameters u and v, the mathematical form
of the parametric equation is

x = fx (u, v), y = fy (u, v), z = fz (u, v), (5.2)

where um  u  uM and vm  v  vM . Function fsurf(fx ,fy ,fz ,[um ,uM ,vm ,vM ]) draws
directly the 3D surface plots, where the default ranges of u and v are (−5, 5). The

(a) plan view (b) side view

(c) front view (d) 3D surface

. Fig. 5.23 Orthographic views of the surface


5.3 · Three-Dimensional Plots in MATLAB
127 5
ezsurf() function in earlier versions of MATLAB can also be used to draw surface
plots. It is not recommended to use such a function.

 Example 5.24
The mathematical model of the well-known Möbius strip is

x = cos u + v cos u cos u/2, y = sin u + v sin u cos u/2, z = v sin u/2.

If 0  u  2π, −0.5  v  0.5, draw the 3D surface of the Möbius strip.


Solutions Two symbolic variables u and v can be declared first, and the parametric equation
can be written into MATLAB workspace. The following commands draw directly the
Möbius strip, as shown in . Fig. 5.24.
>> syms u v; x=cos(u)+v*cos(u)*cos(u/2); y=sin(u)+v*sin(u)*cos(u/2);
z=v*sin(u/2); fsurf(x,y,z,[0,2*pi,-0.5,0.5]) % draw Möbius strip

5.3.6 Three-Dimensional Animation


If a 3D surface is a function of time, function getframe() can be used at each time
sample to extract a handle of 3D surface. In this way, a series of such handles can be
extracted. With the handles, function movie() can be called to make a 3D animation
video. In this section, examples are presented to demonstrate 3D animation making
and play methods.

 Example 5.25
Consider the time-varying function z(x, y, t) = sin(x2 t + y2 ), where 0 ≤ t ≤ 1, −2 ≤
x, y ≤ 2. Use animation method to represent the surface of the function, while the value of
t is changing.
Solutions 3D animation processing can be divided into two parts. The first one is to make
the animation, where the surface data at each time instance are generated, and 3D surface

. Fig. 5.24 Möbius strip (rotated manually)


128 Chapter 5 · MATLAB Graphics

can be drawn. Then function getframe() can be used to extract the handle of a frame of
image. In this way, a series of handles can be generated. To make the animation stabilized,
function axis() is called to fix the axis of each frame of image. The second part is to play
animation. With a series of handles for the animation, function movie() can be called to
playback the animation. The previous presentation can be directly implemented with the
following statements, such that the expected 3D animation result can be obtained.

>> t=linspace(0,1); [x,y]=meshgrid(-2:0.1:2);


for i=1:length(t) % process each time instance in a loop
z=sin(x.^2*t(i)+y.^2); surf(x,y,z); % draw 3D surface
axis([-2,2,-2,2,-1,1]); h(i)=getframe; % extract a frame of image
end
5 figure, movie(h) % directly play the animation


It is noted that getframe() function not only extracts a frame of image of a


3D surface, it also works for 2D curves. Therefore 2D images can also be made in
animation form. Besides, VideoWriter() function opens a video file, writeVideo()
function writes a frame into a video file. An example is given next to demonstrate the
animation video making process.

 Example 5.26
Write the Brownian motion animation in Example 5.17 into a video file.
Solutions Assume that there are 200 steps of movement. The following commands generate
data for animation, and make the animation into a video file. After the execution of the
commands, generate a video file brown.avi, which can be played by any media players.

>> n=30; x=randn(1,n); y=randn(1,n); s=0.3; % initial positions


figure(gcf), hold off; % bring figure window to front, if none, open one
h=plot(x,y,'o'); axis([-30,30,-30,30])
vid=VideoWriter('brown.avi'); open(vid); % open blank video file
for k=1:200 % animation for 200 steps move
x=x+s*randn(1,n); y=y+s*randn(1,n); % update particle position
h.XData=x; h.YData=y; drawnow % generate a frame image
hVid=getframe; writeVideo(vid,hVid); % write a frame to video
end, close(vid) % close video file


5.4 Implicit Function Plotting


In the earlier curve and surface plotting, the explicit functions are studied. Implicit
functions cannot be directly drawn with the methods discussed earlier. Dedicated
implicit function facilities must be introduced. In this section, the plotting facilities
for 2D and 3D implicit functions are presented.
5.4 · Implicit Function Plotting
129 5
5.4.1 Two-Dimensional Implicit Function Curves
Implicit equation describes the relationship between x and y, satisfying the equation
f (x, y) = 0. With the plotting methods discussed earlier, it is almost impossible
to draw the curves. For instance, many implicit equations do not have the explicit
relationship between x and y. Therefore it is not possible to find the value vector
y based on the generated x vector. Therefore, function plot() cannot be used to
draw the curves. Besides, even though the explicit relationship between x and y exists,
since it is no longer single-valued function, the low-level plotting facilities is rather
complicated. With the function fplot() presented earlier, the implicit curve of the
equation cannot be found.
Function fimplicit() provided in MATLAB draws directly the curves of an
implicit function, with the syntax fimplicit(implicit function expression), where
implicit function expression is the symbolic expression or anonymous function in
dot operations. The syntax fimplicit(implicit function expression,[xm ,xM ]) is also
used to specify the plotting range. The default range is [−5, 5].
In earlier versions of MATLAB, a practical function ezplot() can be used, and
its syntax is close to the function fimplicit(), where strings can be used to describe
the implicit function. Function ezplot() cannot be used to handle piecewise function
expressions described by the function piecewise(). Examples are used to demon-
strate the implicit function plotting.

 Example 5.27
Draw the curves of the implicit function y2 cos(x + y2 ) + x2 ex+y = 0, x, y ∈ (−2π, 2π).
Solutions It can be seen from the given function that there is no method to find explicit
description of the function. Therefore the function plot() cannot be used to draw the
curves. The following MATLAB commands are issued such that the implicit function
can be drawn, as shown in . Fig. 5.25a. Therefore, the plotting procedures of implicit
functions are very simple. If the implicit function can be described, the curves can be drawn
immediately.

>> syms x y; f=y^2*cos(x+y^2)+x^2*exp(x+y); % symbolic expression


fimplicit(f,[-2*pi,2*pi]) % draw implicit function, specify range
It can be seen from the curves that they are not quite smooth under the default settings.
There are burrs in some places. The MeshDensity option should be modified, and set it to
1000 or other large values. The smooth plot obtained is obtained, as shown in . Fig. 5.25b.

>> fimplicit(f,[-2*pi,2*pi],'MeshDensity',1000) % smooth curves


The implicit functions can be expressed in anonymous functions. Dot operations should
be used in defining the function. With the function described, fimplicit() command can
be called, and the same results can be obtained.

>> f=@(x,y)y.^2.*cos(x+y.^2)+x.^2.*exp(x+y); % anonymous function



130 Chapter 5 · MATLAB Graphics

-2

-4

5 -6
-6 -4 -2 0 2 4 6
(a) curves under default setting
6

-2

-4

-6
-6 -4 -2 0 2 4 6
(b) smooth curves

. Fig. 5.25 Implicit function curves

 Example 5.28
Use graphical method to find all the solutions in the range −2π ≤ x, y ≤ 2π, for the following
simultaneous equations.

x2 e−xy /2 + e−x/2 sin(xy) = 0


2

y2 cos(y + x2 ) + x2 ex+y = 0.

Solutions Each equation above can be regarded as an implicit function. Therefore, the
fimplicit() function draws the two implicit functions simultaneously. The curves are
obtained as shown in . Fig. 5.26. Therefore, the intersections of the two sets of curves are
the solutions of the simultaneous equations (the solution of Exercise (8) in 7 Chap. 1).

>> syms x y; f1=x^2*exp(-x*y^2/2)+exp(-x/2)*sin(x*y);


f2=y^2*cos(y+x^2)+x^2*exp(x+y);
fimplicit([f1,f2],[-2*pi,2*pi],'MeshDensity',1000)

5.4 · Implicit Function Plotting
131 5

-2

-4

-6
-6 -4 -2 0 2 4 6

. Fig. 5.26 Graphical solutions of simultaneous equations

If the user is interested in a particular intersection, the zooming facilities in MAT-


LAB graph window can be used again and again, to read the values of the solution
x and y. This method is known as graphical method. Unfortunately, it is extremely
complicated to find all the intersections one by one. In Chap. 9, numerical solutions
of equations with multiple solutions are presented to find all the solutions in one
function call.

5.4.2 Three-Dimensional Implicit Function Surfaces


If a 3D surface is described by implicit function g(x, y, z) = 0, MATLAB command
fimplicit3() draws the surface, with the syntax fimplicit3(fun,[xm ,xM ,ym ,
yM ,zm , zM ]), where fun can be anonymous function or symbolic expression. The
ranges of the variables are xm , xM , ym , yM , zm and zM , with the default values ±5. If
only one pair of bound xm and xM is specified, the settings of the three axes are the
same.

 Example 5.29
Assume that a 3D implicit function is described as
  
x(x, y, z) = x sin y + z2 + y2 cos x + z + zx cos z + y2 = 0,

and the interested area is x, y, z ∈ (−1, 1), draw the 3D surface.


Solutions Symbolic expressions or anonymous functions can be used to describe the original
implicit function. The two descriptions can be used in the same way. Draw the 3D surface
of the functions with the following commands, as shown in . Fig. 5.27a.

>> syms x y z; f=x*sin(y+z^2)+y^2*cos(x+z)+z*x*cos(z+y^2);


fimplicit3(f,[-1 1]) % 3D implicit function surface
In fact, the 3D implicit function can also be described by an anonymous function, and
the result thus obtained are the same.
132 Chapter 5 · MATLAB Graphics

5 (a) 3D surface

(b) super imposed a sphere

. Fig. 5.27 3D surfaces of the implicit functions

>> f=@(x,y,z)x.*sin(y+z.^2)+y.^2.*cos(x+z)+z.*x.*cos(z+y.^2);
fimplicit3(f,[-1,1])
The surface of a unit sphere x2 + y2 + z2 = 1 can be superimposed on the original
surface, as shown in . Fig. 5.27b.

>> f1=x^2+y^2+z^2-1; fimplicit3([f f1],[-1 1]); % surfaces of 2 functions




5.5 Exercises
(1) Draw the function curve y(x) = sin πx/(πx), where x ∈ (−4, 4).
(2) Select a suitable step sizes to draw the plot sin 1/t, where t ∈ (−1, 1).
(3) Select suitable step size and draw the curve of tan t, where t ∈ (−π, π). Observe
the manipulation of the discontinuous behaviors.
(4) Draw the following functions
(a) f (x) = x sin x, x ∈ (−50, 50), (b) f (x) = x sin 1/x, x ∈ (−1, 1).
5.5 · Exercises
133 5
(5) Select a suitable range of t and draw the phase plane trajectory of the parametric
equation x = sin t and y = sin 2t. If a particle is moving on the curve, draw the
dynamic display of the particle.
(6) Draw the three curves of sin x, sin 2x and sin 3x in the interval t ∈ (0, 2π).
(7) Use MATLAB command to draw an equilateral triangle. Using loop structure,
write a program to draw a set of equilateral triangles, such that the triangle
rotates around its center for one degree each time. Observe the triangles.
(8) Draw the plot of x sin x + y sin y = 0 in the interval −50  x, y  50.
(9) Draw the piecewise function

sin t + cos t, t ≤ 0
y(t) =
tan t, t > 0.

(10) The probability density function of normal distribution is,

1
e−(x−μ)
2 /(2σ 2 )
p(x) = √
2πσ

where μ is the mean, and σ is the variance. Draw the probability density func-
tion plots for different values of μ and σ .
(11) Find the first 40 terms of the sequence defined below and observe the trend with
stem() function.

1 1 1
xk = 1 + + + ··· + − ln k.
2 3 k

(12) For the given iterative model, the initial value is x0 = 0, y0 = 0, the subsequent
values can be found from

xk+1 = 1 + yk − 1.4xk2
yk+1 = 0.3xk .

Perform 30000 iterations, such that the results can be saved in the vectors x and
y. Draw the relationship between xi and yi with '.' option. Note that the plot
obtained is referred to as the Hénon attraction. The random points generated
look like attraction lines.
(13) Assume that a series function is defined as


N
x2n
f (x) = lim (−1)n .
N→∞ (2n)!
n=1

If N is large enough, the series f (x) converges to a function f̂ (x). Write an


M-function to draw the curve of f (x) in x ∈ (0, π), and find out what is the
mathematical expression of f̂ (x).
(14) Draw the curve of function sin t2 in t ∈ (0, π). If the curve is not very clear at
a certain point, use zooming facilities to observe the details.
134 Chapter 5 · MATLAB Graphics

(15) Select suitable θ ranges, and draw the polar plots.


(a) ρ = 1.0013θ 2 , (b) ρ = cos 7θ/2, (c) ρ = sin θ/θ , (d) ρ = 1 − cos3 7θ .
(16) Draw the curve of the parametric equation x = (1 + sin 5t/5) cos t, y =
(1 + sin 5t/5) sin t, t ∈ (0, 2π). If the value of 5 is changed to other values,
what is the result?
(17) Find the approximate solutions of the simultaneous equations with graphical
method
 2
e−(x+y) +π/2 sin(5x + 2y) = 0
2
x + y2 = 3xy2
(a) (b)
x3 − x2 = y2 − y, (x2 − y2 + xy)e−x −y −xy = 0.
2 2

(18) For the given sinusoidal function y = sin(ωt + 20◦ ), t ∈ (0, 2π), ω ∈ (0.01, 10),
5 draw the animation of the curve when the sinusoidal function changes with ω.
(19) The equations of a moving particle in space are given by x(t) = cos t + t sin t,
y(t) = sin t − t cos t, z(t) = t2 , and t ∈ (0, 2π). Draw its moving trajectory, and
draw the animation of the particle moving in 3D space.
(20) Draw the 3D surfaces for the functions xy, sin xy and e2x/(x +y ) .
2 2

 
(21) Draw the 3D surface of the function f (x, y) = sin x2 + y2 / x2 + y2 , −8 
x, y  8.
(22) Draw the 3D surface of the following parametric equations [2].
(a) x = 2 sin2 u cos2 v, y = 2 sin u sin2 v, z = 2 cos u sin2 v, −π/2  u, v  π/2,
(b) x = u − u3 /3 + uv2 , y = v − v3 /3 + vu2 , z = u2 − v2 , −2  u, v  2.
(23) Draw the surface of the following functions. Also try functions waterfall(),
surfc() and surfl(), and observe the results.
(x − 1)2 y2
, (d) z = −xy e−2(x +y ) .
2 2
(a) z = xy, (b) z = sin x2 y3 , (c) z =
(x − 1) + y
2 2

(24) For the given parametric equations x = u sin t, y = u cos t, z = t/3, t ∈ (0, 15),
u ∈ (−1, 1), draw the surface of the equations.
(25) In the graphics commands, if the value of the function is NaN, the corresponding
point is not displayed. Draw the surface of the function z = sin xy, and then
cut off the part satisfying x2 + y2  0.52 .
(26) Draw the 3D surface of the function x(z, y) = (z2 − 2z)e−z −y −zy .
2 2

(27) For the given parametric equation x = cos t(3+cos u), sin t(3+cos u), z = sin u,
and t ∈ (0, 2π), u ∈ (0, 2π), draw the surface.
(28) For the function f (x, y) = x sin(1/y) + y sin(1/x), investigate the behaviors of
the around the (0, 0) point. √ √
(29) Draw the plot for the implicit function (r − 3) r + 0.75 + sin 8 r cos 6θ −
0.75 sin 5θ = 0, where r = x2 + y2 and θ = arctan(y/|x|).
(30) Draw the surface of the 3D implicit function (x2 + xy + xz)e−z + z2 yx + sin(x +
y + z2 ) = 0.
(31) Draw the surfaces of the two curves x2 + y2 + z2 = 64 and y + z = 0, and
observe the intersections.
(32) MATLAB command treeplot() draws binary tree plot. For instance, the
binary tree in Fig. 4.8 can be drawn with the commands
5.6 · Mini-Projects
135 5
>> nodes=[0,1,1,2,2,3,3,4,4,5,5,6,6,8,8]; treeplot(nodes)
Understand the meanings of the above statements. Extend the plot and draw the
binary tree plot for k = 7 for Fibonacci sequence. Write a MATLAB function
to draw the binary tree plot for ak .

5.6 Mini-Projects

1. Mandelbrot Images
American mathematician Benoît Mandelbrot coined a term fractal and initiated field
known as fractal geometry. Also, Mandelbrot set is defined, from which, beautiful
computer images can be generated by simple mathematical formulas.
Consider a point c in a complex plane. Consider also point z in the complex plane,
and it is safe to assume z = 0. If the mapping z = z2 + c is carried out repeatedly,
and z is still bounded, it is a point in the Mandelbrot set. If z diverges after a number
of mappings, it is not in the Mandelbrot set. A criterion |z| < 2 is usually made, such
that if the mapping is made d times, and the criterion is still satisfied, the index at this
point is set to d, where d is the predefined value, known as depth. If the point z is
mapped k times, and the criterion is no longer satisfied, then the index for z is set to
k − 1.
In Reference [3], a simple computer code is provided, and it is modified using the
variable names above.
>> x=0:0.05:0.80; y=0:0.05:0.80; d=32;
n=length(x); z=zeros(n); M=z; [X,Y]=meshgrid(x,y); c=X+Y*1i;
for k=1:d
z=z.^2+c; M(abs(z)<2)=k;
end
image(M), axis image, colormap(flipud(jet(d)))
The first line in the above code can be modified by the user, where x and y vectors
specify the region in the complex plane, while d is the depth, which can be set to 256.
If the region is specified as center c0 , width w and grid number m mode, the x and y
vectors can be computed with
>> hw=0.5*w; rc=real(c0); ic=imag(c0);
x=linspace(rc-hw,rc+hw,m); y=linspace(ic-hw,ic+hw,m);
Rewrite the above relevant code into a reusable function. Then draw the image
with c0 = −0.5, w = 3, m = 512 and d = 256. Changing the interested region, for
instance to the following two suggested one c0 = −1.6735−0.0003318j, w = 1.5×10−4 ,
m = 1026, n = 160. Try different color maps, for instance, flag.
Draw the Mandelbrot set images. You can choose your own center, with and grid
number, depth information and see whether you can obtain beautiful images.
136 Chapter 5 · MATLAB Graphics

2. Intersections of Surfaces
Consider . Fig. 5.27b. The mathematical interpretation is that, there are two sur-
faces, described by implicit functions with three independent variables. It is natural
to ask, what are the intersection curves of the two given surfaces?
There are no immediate functions which can be used to solve directly the problem
and extract the intersections. A useful example and method are illustrated in Reference
[4]. Read the materials in the relevant references, and try to understand the meanings
of each MATLAB sentence, and consider where these codes can be modified and
used, to draw the intersection curves in Example 5.29. Select different step sizes and
see the impact of the step sizes on the smoothness of the intersection curves, and also
the time elapses. Superimpose the intersections on the surfaces in . Fig. 5.27b.
5
References
1. Xue DY, Chen YQ (2008) Solving applied mathematical problems with MATLAB[M]. CRC Press,
Boca Raton
2. Majewski M (2004) MuPAD pro computing essentials[M], 2nd edn. Springer, Berlin
3. Molor CB (2013) Experiment with MATLAB[M]. BUAA Press, Beijing
4. Garrity M (2015) Implicit surface intersections[OL]. 7 https://blogs.mathworks.com/graphics/2015/
07/22/implicit-surface-intersections
137 6

Object-Oriented
Programming
Contents

6.1 Essential Concepts in Object-Oriented


Programming – 138

6.2 Classes and Objects Design – 139


6.2.1 Class Data Structure – 139
6.2.2 Input and Display of Classes – 140
6.2.3 Overload Functions for Addition and Subtraction – 142
6.2.4 Overload Function of Multiplication – 144
6.2.5 Overload Function of Power Operations – 146
6.2.6 Overload Function for Like-Term Collection – 147

6.3 Interface Design of Apps – 147


6.3.1 User Interface Objects – 148
6.3.2 Simple Dialog Boxes – 148
6.3.3 Programming and Applications of Standard Dialog
Boxes – 149
6.3.4 App Designer Programming – 151

6.4 Exercises – 156

6.5 Mini-Projects – 156

References – 157

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_6
138 Chapter 6 · Object-Oriented Programming

Many programming methods are discussed earlier. All of them are conventional ones.
In this chapter, a brand-new programming method—object-oriented programming
(OOP)—is illustrated. The design and application of classes are presented first, fol-
lowed by the design of graphical user interfaces and Apps.
In 7 Sect. 6.1, fundamental concepts in OOP are presented first, and the essential
information on OOP are introduced. The necessity of OOP and the essential differ-
ences between OOP and conventional programming are illustrated. In 7 Sect. 6.2,
the design method of a class is presented, based on a special polynomial—pseudo-
polynomial. Various practical programming details are demonstrated with examples.
The program implementation of algebraic operations for the class is demonstrated
with examples. In 7 Sect. 6.3, the essential knowledge and tools are presented for
App design. The use of the standard dialog boxes is introduced, followed by the
demonstrations on the use of App Designer, to develop Apps.
6
6.1 Essential Concepts in Object-Oriented Programming
Object-oriented programming is a very important programming method. The pro-
gramming method is established upon the concept of objects, such that programs can
be written. Object-oriented programming mechanism is well implemented in MAT-
LAB. In this section, the fundamental concepts and background knowledge of OOP
are presented, so as to establish a good foundation for the introduction of OOP
techniques.
Object is a way to represent data. An object has its fields, also known as attributes,
membership variables or simply members.
A set of objects sharing the same structures and properties is referred to as a class.
The processing functions based on OOP are referred to as methods of the objects.
It other words, if a class is designed, then object is an instance of the class. All the
fields and methods in the class can be used in the object.
In OOP programming, the methods of the objects may read or modify the fields
of the objects, so as to implement their facilities.
There are significant differences between conventional programming and OOPs.
In the conventional programs, the statements are executed in certain order, while in
OOP, the methods are prepared for the objects. These functions and methods are not
executed in normal cases. If an event happens, the object is triggered, such that the
corresponding methods are called automatically to respond to the events. Microsoft
Windows interface is usually implemented in OOP. If a menu item is clicked, an
event is generated, and Windows executes a piece of code to respond to the event
automatically. It can be seen that OOP styles are everywhere. The users may also
experience the importance of this programming style.
Compared with conventional programming style, OOP is more readable and
reusable, and expandable.
For ordinary users, there are two forms in using object-oriented programming
techniques. One is the clients’ form, and the other the programmers’ form [1].
In the former form, the existing classes and objects can be used directly, and the
user does not need to understand too much on low-level programming in classes
and objects. Most users belong to this form. In the programmers’ form, the user
needs to learn how to write low-level programs in object-oriented programming,
6.2 · Classes and Objects Design
139 6
including how to create a class, how to write low-level code for the objects. In the next
section, a simple example is given, to demonstrate the whole process in object-oriented
programming. With low-level OOP technique, the user may better use MATLAB, so
as to better solve scientific computing problems.

6.2 Classes and Objects Design


In OOP, the users need to define first a class. The procedures are: select a class
name, design the fields for the class, and finally create the class. When a class is
created, response functions should be written for the class. In this section, pseudo-
polynomial is used as an example, to demonstrate the class creation and response
function programming methods.

6.2.1 Class Data Structure


In MATLAB, a variable name can be used to describe an object. For instance, the tf
object provided in Control System Toolbox describes a transfer function model, while
with ss, it represents a state space model. With class defined, a variable name can
then be used to describe an object under the class. For instance, variable G describes
a transfer function object.
To design a class, the fields for the class must be selected first. For instance, the
existing fields of a transfer function class can be expressed directly with the numerator
and denominator polynomial coefficient vectors. Therefore the fields num and den
are designed for the class. If Bode diagram for a transfer function class is expected, a
method is needed. For instance, the function bode() in the Control System Toolbox
can be used as a method to process the object, with the command bode(G). Function
bode() is a method for the class. In this book, methods are referred to as response
functions.
If the reader wants to understand OOP from the programmer’s viewpoint, a name
should be selected first for the class, and create a dedicated folder for it. In the folder,
all the functions needed are written for the class, including a class definition file, a
class display file, also a group of response functions. For convenience of manipulating
such classes, the response function names should be selected the same as the ones in
other classes. The functions with the same name are referred to as overload functions.
Different functions under the same name belong to their own classes, therefore the use
of these functions is not mixed up, which are governed by the MATLAB mechanism.
The following procedures are needed to design a class:
(1) Select a class name. The naming regulations of class are the same as those for
variable names.
(2) Create a blank folder. A folder led by @ is needed, followed by the class name. If
the current path is already in the MATLAB search path, it is not necessary to include
the class folder into the search path.
(3) Design fields. Fields can be used to store necessary parameters of the class.
(4) Write two essential functions. When a class is designed, at least two functions
should be written, in the created folder. One is the file under the same name, used to
140 Chapter 6 · Object-Oriented Programming

allow the user to input an object for the class, while the other one is named display.m,
used to display the object.
(5) Design the necessary overload functions. Define the actions to operate an object.
The actions include the basic ones such as plus, minus, times and so on. The function
names must be the same as the ones conventionally used. For instance, to use +
operator, a function plus.m should be written. A newly designed class does not
have any methods (functions). Any of the operations must be defined for the class,
otherwise the operators, no matter how simple it is, cannot be used.
The mathematical form of a pseudo-polynomial is as follows:

p(s) = a1 sα1 + a2 sα2 + · · · + an sαn , (6.1)

where ai are coefficients, αi are orders, i = 1, 2, . . . , n. The orders here are not
6 restricted to integers. Therefore the polynomial is referred to as pseudo-polynomials.
In this section, pseudo-polynomial is used as an example to demonstrate the class
design method.

 Example 6.1
Design a MATLAB class for the pseudo-polynomials.
Solutions To design a class for pseudo-polynomials, a class name must be selected first, for
instance, ppoly. Therefore a blank folder named @ppoly can be created first. Besides, to
uniquely describe pseudo-polynomial, two vectors can be introduced. One is the coefficient
vector a =[a1 ,a2 , · · · ,an ], the other one is the order vector α =[α1 ,α2 ,· · · ,αn ]. The two
vectors named a and na can be selected as fields (or members) of the ppoly class. 

6.2.2 Input and Display of Classes


Class definition function has its own fixed structure, which is slightly different to
other MATLAB functions, while its structure is easy to understand. An example is
given next to demonstrate the programming in class definition function.

 Example 6.2
Write a class definition function for the class ppoly.
Solutions Before writing the class definition function, the possible syntaxes of the function
call should be designed. At the beginning, it does not matter if proposed syntaxes are not
complete. The function can be extended later. For the time being, the pseudo-polynomial
class definition function has the three syntaxes:
(1) p =ppoly(a,α), (2) p =ppoly(a), (3) p = ppoly('s')
where in the first syntax, the coefficient and order vectors are both specified; in the second
one, a is the coefficient vector for integer-order polynomial; in the third syntax, p is s
operator. Based on the considerations, the class definition function can be written.

classdef ppoly % class definition function


properties, a, na, end % properties, delimited with end
methods % methods (response functions)
6.2 · Classes and Objects Design
141 6
function p=ppoly(a,na)
if nargin==1 % judge number of input arguments, if it is 1
if isa(a,'double'), p=ppoly(a,length(a)-1:-1:0); % syntax (2)
elseif isa(a,'ppoly'), p=a; % if already ppoly, pass to output
elseif a=='s', p=ppoly(1,1); end % syntax (3)
elseif length(a)==length(na), p.a=a; p.na=na; % syntax (1)
else, error('Error: miss matching in a and na'); end
end % end to the function statement
end % end to the methods statement
end % end to the classdef statement
This piece of code is led by classdef command, used in the ppoly class definition.
In the code led by the properties statement, list all the field names, delimited
with end.
The remaining code is led by the methods statement, describing the methods, referred to
as the response functions. A class definition file may contain several response functions, or
even, all the response functions can be included in a single file. Each response function has
its own end statement. When writing independent response function, end command can
be omitted. In calling ordinary MATLAB functions, if the end of file is reached, it means
that the function is completed. However in class definition files, end command must be
provided at the end of the function file. Otherwise it may lead to error.
It can be seen that each structure in the file should be paired with the end statement,
otherwise these may bring errors. 

With such a file, the user is allowed to input a ppoly object in one of the three
syntaxes. If such an object is created, the contents of it must be displayed. Therefore
a display.m file must be written, and the file can also be embedded into the main
function, or as a separate display.m file.

 Example 6.3
Write a display function for the ppoly class.
Solutions Consider the formula in (6.1), a string is considered to express the class. Besides,
some special expressions should be simplified. For instance, in the substring +1*s, 1* should
be removed. Therefore a statement can be written to substitute +1*s by +s. Function
strrep() carries out the string substitution. Such a simple statement can be written. The
program can be executed for some examples, and the user may test the code, and see whether
there are other substrings to be substituted, such that the display function can be completed.
Finally, the following display function can be written:

function str=display(p)
np=p.na; p=p.a; if length(np)==0, p=0; np=0; end
P=''; [np,ii]=sort(np,'descend'); p=p(ii); % sort the orders
for i=1:length(p) % process each term in the polynomial with a loop
P=[P,'+',num2str(p(i)),'*s^{',num2str(np(i)),'}'];
end
P=P(2:end); P=strrep(P,'s^{0}',''); P=strrep(P,'+-','-');
P=strrep(P,'^{1}',''); P=strrep(P,'+1*s','+s'); % string substitution
P=strrep(P,'*+','+'); P=strrep(P,'*-','-');
142 Chapter 6 · Object-Oriented Programming

strP=strrep(P,'-1*s','-s'); nP=length(strP);
if nP>=3 & strP(1:3)=='1*s', strP=strP(3:end); end
if strP(end)=='*', strP(end)=''; end,
if nargout==0, disp(strP), else, str=strP; end
end

Note that the new function must be placed in the @ppoly folder, otherwise it may not
be found by such an object. 

 Example 6.4
Input and display the following expressions in ppoly object:

p1 (s) = s1.5 + 4s0.8 + 3 + s0.7 + 5, p2 (s) = s3 + 3s2 + 3s + 1.


6
Solutions Two methods can be used to input the pseudo-polynomials. One is to use coef-
ficient and order vectors directly. An alternative way is to define operator s first as a
ppoly object. Then the object can be entered with an expression. In p1 (s), the two vectors
a =[1,4,3,5] and n =[1.5,0.8,0.7,0] can be used first, such that the object can be cre-
ated. While in p2 (s), from the coefficient vector a =[1,3,3,1], the ppoly object can also
be created. Therefore the two methods can be used to input the two pseudo-polynomials,
and the results are identical. Of course, the input command in pi2 (s) can only be completed
if plus and times overload functions are defined.

>> a=[1,4,3,5]; n=[1.5,0.8,0.7,0]; p11=ppoly(a,n)


s=ppoly('s'); p12=s^1.5+4*s^0.8+3*s^0.7+5
p21=ppoly([1,3,3,1]), p22=s^3+3*s^2+3*s+1


6.2.3 Overload Functions for Addition and Subtraction


Arithmetic or other operations of pseudo-polynomial object p(s) are often required.
For the newly created ppoly class, no operations are supported in nature. The user
must write his own processing functions. When defining the operations of the pseudo-
polynomial objects, it is suggested to select the same function name as in ordinary
operations. For instance, to add up two ppoly objects, the overload function name
plus() is recommended, so that the operator + can be used in carry out addition
actions. Similarly, other overload function names should be assigned accordingly.
To write processing functions for the ppoly class, there is an important rule. That
is if p1 and p2 are all ppoly object, the arithmetic operation results must also be a
ppoly object. Otherwise there is no need to write processing functions for it. It can
be seen from the rule that, addition, subtraction and multiplication all yield a ppoly
object, while division does not satisfy the rule. In . Table 6.1, information of some of
the commonly used arithmetic operations are given, and the program design methods
are demonstrated next in dedicated examples.
6.2 · Classes and Objects Design
143 6

. Table 6.1 Overload functions for algebraic operations

Operations Functions Descriptions

Addition plus p = p1 + p2 computes the sum of two


pseudo-polynomials can easily be found in
mathematics—Join the two fields a into one and join
two na fields into another. Use collect() function to
carry out like-term collections and simplify it

Unary minus uminus p = −p1 , multiplies the a field by −1

Subtraction minus p = p1 − p2 , with uminus, subtraction can be found


with p = p1 + (−p2 )

Multiplication mtimes p = p1 * p2 , to be illustrated later in the dedicated


example

Power mpower p=p1 ^n computes the power; if n is a positive integer, the


p1 object is multiplied n times; if n is not a positive
integer, and there is only one term in a field in p1 object,
the power can be found immediately; in other cases,
display error message

Collection collect p = collect(p1 ), sort the na field in p first, and


manipulate a fields simultaneously, then find the
like-terms in na to add the coefficients up. Delete the
terms with zero coefficients

 Example 6.5
Write overload functions for addition and subtractions for the ppoly class.
Solutions Assume that the two pseudo-polynomials to be added are given by

p1 (s) = a1 sα1 + a2 sα2 + · · · + an sαn , p2 (s) = b1 sβ1 + b2 sβ2 + · · · + bm sβm , (6.2)

the sum of them, p(s) = p1 (s) + p2 (s), can be written as

p(s) = a1 sα1 + a2 sα2 + · · · + an sαn + b1 sβ1 + b2 sβ2 + · · · + bm sβm . (6.3)

It can be seen that coefficient and order vectors of the sum can be obtained by catenating
the vectors of the two pseudo-polynomials

â = [a1 , a2 , . . . , an , b1 , b2 , . . . , bm ], α̂ = [α1 , α2 , · · · , αn , β1 , β2 , · · · , βm ]. (6.4)

Collection of like-terms can be made to find the sum.


Create a plus.m file in the folder @ppoly. The following program can be written:

function p=plus(p1,p2)
p1=ppoly(p1); p2=ppoly(p2); % unify the input arguments into ppoly object
a=[p1.a,p2.a]; na=[p1.na,p2.na]; p=collect(ppoly(a,na));
end
144 Chapter 6 · Object-Oriented Programming

In the function, the two input arguments are unified to ppoly object. This is because if
one of them is a scalar, it does not have a and na members, so the next statements cannot
be executed. Therefore they should be unified to ppoly objects.
It is indicated in . Table 6.1 that, before writing the subtraction overload function, a
unary minus function should be written first. The two overload functions can be written
directly as follows:

function p=uminus(p1)
p1=ppoly(p1); p=ppoly(-p1.a,p1.na); % invert the signs of the coefficients
end
function p=minus(p1,p2)
p1=ppoly(p1); p2=ppoly(p2); p=p1+(-p2); % convert minus to plus
end

6
6.2.4 Overload Function of Multiplication
Before introducing multiplication operations, the definitions of Kronecker operations
of matrices are presented first.
The Kronecker product of any two matrices A and B is defined as
⎡ ⎤
a11 B ··· a1m B
⎢ .. .. .. ⎥ .
C = A⊗ B =⎣ . . . ⎦ (6.5)
an1 B ··· anm B

Accordingly the Kronecker sum A ⊕ B of matrices A and B is defined as


⎡ ⎤
a11 + B ··· a1m + B
⎢ .. .. .. ⎥
D = A⊕ B =⎣ . . . ⎦. (6.6)
an1 + B ··· anm + B

Kronecker product A ⊗ B can be evaluated directly with C=kron( A,B), and


there is no existing MATLAB function for Kronecker sum. Referencing the code in
kron(), the function kronsum() for Kronecker sum is written as
function C=kronsum(A,B)
[ma,na]=size(A); [mb,nb]=size(B);
A=reshape(A,[1 ma 1 na]); B=reshape(B,[mb 1 nb 1]);
C=reshape(A+B,[ma*mb na*nb]);
end

 Example 6.6
Write a multiplication overload function for ppoly class.
Solutions Assume that the two pseudo-polynomials are given in (6.2). The product of the
two pseudo-polynomials can be obtained from
6.2 · Classes and Objects Design
145 6
p(s) = p1 (s)p2 (s) = a1 sα1 p2 (s) + a2 sα2 p2 (s) + · · · + an sαn p2 (s)
= a1 b1 sα1 +β1 + a1 b2 sα1 +β2 + · · · + a1 bm sα1 +βm +
a2 b1 sα2 +β1 + a2 b2 sα2 +β2 + · · · + a2 bm sα2 +βm + (6.7)
···+
an b1 sαn +β1 + an b2 sαn +β2 + · · · + an bm sαn +βm .

It is seen from (6.7) that the two vectors of the product are

â = [a1 b, a2 b, · · · , an b] = a ⊗ b, α̂ = [α1 + β, α2 + β, . . . , αn + β] = α ⊕ β. (6.8)

That is, the coefficients of the result pseudo-polynomial can be obtained with Kronecker
product, while the orders can be obtained by the Kronecker sum. Like-term collection is
needed to simplify the results so that the product of two ppoly objects can be found. Based
on this idea, the following multiplication overload function can be written:

function p=mtimes(p1,p2)
p1=ppoly(p1); p2=ppoly(p2); a=kron(p1.a,p2.a);
na=kronsum(p1.na,p2.na); p=collect(ppoly(a,na));
end
Note that at the entry point of the function, ppoly() function is called to ensure that
the two input arguments are provided as ppoly objects, where ppoly.m is called first. As it
is indicated earlier, ppoly.m function provides the conversion facilities to convert different
data types into a ppoly object. 

 Example 6.7
If p1 (s) = 3s0.7 + 4s + 5 and p2 (s) = 2s0.4 + 6s + 6s0.3 + 4, compute p1 (s)p2 (s).
Solutions With the multiplication overload function, the multiplication operation can be
carried out in MATLAB, such that the two ppoly objects are created and multiplied.

>> p1=ppoly([3 4 5],[0.7 1 0]);


p2=ppoly([2 6 6 4],[0.4 1 0.3 0]); p=p1*p2
The product of the two ppoly objects is

p(s) = 24s2 + 18s1.7 + 8s1.4 + 24s1.3 + 6s1.1 + 64s + 12s0.7 + 10s0.4 + 30s0.3 + 20.

 Example 6.8
For the ppoly objects p1 (s) and p2 (s) in Example 6.7, compute p(s) = p41 (s)p22 (s).
Solutions With the overload mtimes() function, the product can be found from the fol-
lowing commands:

>> p1=ppoly([3 4 5],[0.7 1 0]);


p2=ppoly([2 6 6 4],[0.4 1 0.3 0]); p=p1*p1*p1*p1*p2*p2
Since the result is too complicated, it is omitted here. 
146 Chapter 6 · Object-Oriented Programming

6.2.5 Overload Function of Power Operations


Power computation can be described in an overload function mpower() in MATLAB.
With such a function, the operator ^ computes the power to a given object. The class
ppoly is used again to demonstrate the programming of the power function.

 Example 6.9
Write an overload function for the power operation for ppoly class.
Solutions Consider the two kinds of powers and its applications in . Table 6.1. The
following overload function can then be written:

function p1=mpower(p,n)
arguments, p, n(1,1); end
6 if isscalar(p.a), p1=ppoly(p.a^n,p.na*n); % only one term
elseif (n>=0 && n==floor(n)) % integer power
p1=ppoly(1); for i=1:n, p1=p1*p; end % loops can be used
else, error('n must be a nonnegative integer'), end
end


 Example 6.10
Input again the pseudo-polynomial model p(s) = 3s0.7 + 4s + 5 in Example 6.8.
Solutions In Example 6.7, the coefficient and order vectors are extracted first, then the
pseudo-polynomial model can be established. Since the arithmetic operations are defined
for the pseudo-polynomial, an s operator can be defined first, then simple arithmetic expres-
sions can be used to compute the pseudo-polynomial model. The following MATLAB
commands can be issued:

>> s=ppoly('s'); p=3*s^0.7+4*s+5


With the expression, the ppoly object is manipulated automatically in MATLAB, such
that a single ppoly object can be found, which is identical to the result in Example 6.8. 

 Example 6.11
Use the power overload function to compute the power in Example 6.8.
Solutions Find the product p41 (s)p22 (s) using two methods. The following commands can be
used to compute the formula, where identical results can be found. The difference is zero.

>> p1=ppoly([3 4 5],[0.7 1 0]);


p2=ppoly([2 6 6 4],[0.4 1 0.3 0]);
p0=p1*p1*p1*p1*p2*p2, p=p1^4*p2^2, p-p0

6.3 · Interface Design of Apps
147 6
6.2.6 Overload Function for Like-Term Collection
In the previous presentation, if two pseudo-polynomials are added, the coefficient
and order vectors are joined together to get longer vectors. Then the like-terms are
collected to simplify the results. Specific considerations on like-term collections are
made.
(1) The order vector can be sorted in descending order first, and the coefficients
are arranged accordingly. The difference of the orders is obtained. A loop can be
constructed to handle each term. If the difference in the order is zero, the absolute
of difference is smaller than 10−10 , then this term is a like-term of the previous one,
such that it is added to the previous term, and then delete the current one.
(2) When the loop is completed, the coefficients in each term are examined again.
To test whether a term is zero or not, we usually check whether the absolute value of
its coefficient is smaller than eps or not. If it is, then delete it.

 Example 6.12
Write a like-term collection function collect() for the ppoly function.
Solutions Summarizing the above considerations, an overload function for like-term col-
lection activities can be written.

function p=collect(p)
a=p.a; na=p.na; % extract the coefficient and order vectors
[na,ii]=sort(na,'descend'); a=a(ii); ax=diff(na); key=1;
for i=1:length(ax) % find each term in the order difference
if abs(ax(i))<=1e-10 % if the term is a like term, collect it, and then delete it
a(key)=a(key)+a(key+1); a(key+1)=[]; na(key+1)=[];
else, key=key+1; end
end
ii=find(abs(a)>eps); a=a(ii); na=na(ii); p=ppoly(a,na);
end


6.3 Interface Design of Apps


For a successful software, the fundamental facilities it provided are the most important
issues. Besides, the interfaces it provided are also important factors of its quality, since
the graphical user interface (GUI) is quite similar to the packaging of the products.
Therefore, learning to use the graphical user design techniques is also very important
in MATLAB programming.
In this section, some of the background knowledge on the commonly used objects
are presented. The applications of some of the commonly used dialog boxes are illus-
trated. Finally, a powerful tool named App Designer is demonstrated in designing
App interfaces.
148 Chapter 6 · Object-Oriented Programming

6.3.1 User Interface Objects


Many objects are provided in MATLAB. The hierarchical structure of the objects is
shown in . Fig. 6.1. When get accessed into MATLAB environment, a root object is
created first. It is the MATLAB command window object, whose handle is 0. Based on
the root object, graphical window objects are established, whose handles are always
positive integers.
Each graphical window object has four lower-level objects, that is, the menu
objects, control objects, axes objects and shortcut menu objects. The menu object
is in fact the menu system of the graph window. The control objects are responsible in
creating controls on the window, such as buttons, listboxes and so on. The shortcut
menus can be displayed by clicking right mouse button at an object.
Under the axis object, there are quite a lot of lower-level objects, and some of
them have been discussed earlier. In fact, these objects and their properties can be
6 modified directly with commands and the tools such as App Designer.

6.3.2 Simple Dialog Boxes


For the convenience of interface design, some easy-to-use dialog boxes are provided
in MATLAB, as listed in . Table 6.2. These dialog boxes can be used directly. An
example is given next to demonstrate the use of parameter input dialog box. The use
of other dialog boxes is simple and straightforward. The readers are advised to try
themselves.

 Example 6.13
Input the numerator and denominator coefficient vectors for a transfer function with the
parameter dialog box.
Solutions The following command opens a parameter dialog box, as shown in . Fig. 6.2.
Compare the commands and the displayed dialog box, so as to better understand the use
of such a function.

line object
shortcut menu
uicontextmenu
text object
window menu object
figure surface object
uimenu
..
. image object
root object window control object
root figure uicontrol light object

axis object patch object


axis
rectangle object

. Fig. 6.1 The illustrations of graphical objects


6.3 · Interface Design of Apps
149 6

. Table 6.2 Commonly used simple dialog boxes

Dialog box Descriptions

Message box msgbox(string,title) displays the information in the string. The dialog box
has a OK button, and can be closed by clicking it

Warning box warndlg(string,title) displays warning information

Error box errordlg(string,title) displays error information

Q/A dialog box key=questdlg(string,title) displays a question and answer dialog box,
with three buttons, Yes, No and Cancel, It returns a string such as 'Yes',
'No' or 'Cancel'

Input box var=inputdlg({prompt 1,· · · ,prompt n},title,rows,default values)


displays a parameter dialog box, allowing the user to input a set of
variables. The returned var is a cell array

List box key=listdlg('PromptString',prompt,'ListString',lst), where,


lst is a cell array, listing all the possible items

. Fig. 6.2 Transfer function dialog box

>> mod=inputdlg({'Input the numerator coefficients num',...


'Denominator coefficient den'},...
'Transfer Function',1,{'1','[1,3,3,1]'}) % open a dialog box
The numerator and denominator vectors can be specified in the dialog box. Then click
the OK button to accept the vectors. The strings of the vectors are then stored in the cell
arrays mod{1} and mod{2}. To retrieve the coefficient vectors, the commands str2num(mod
{2}) or eval(mod{2}) can be used. 

6.3.3 Programming and Applications of Standard Dialog Boxes


Several standard dialog box functions are provided in MATLAB, as shown in . Table
6.3. The readers may call these functions directly to open corresponding dialog boxes.
Observe the dialog boxes so as to better learn the use of the functions.
150 Chapter 6 · Object-Oriented Programming

. Table 6.3 Commonly used standard dialog box functions

Dialog box Description

File name [f , p] = uigetfile(spec), details see Table 2.8; save file dialog box with the
function uiputfile()

Color setting c = uisetcolor opens a standard color setting dialog box. The returned
argument is a 1 × 3 vector, containing the red, green, blue components of a
primitive color, each in the interval [0,1]

Font setting hFont = uisetfont(string, handle, title) is used in font setting. The returned
hFont is a structured variable

Printer setting printdlg(h) opens a printer setting dialog box for the window handle of h

6
 Example 6.14
Open the dialog box for font setting. Select the appropriate options and observe the returned
argument.
Solutions A standard font setting dialog box in . Fig. 6.3 can be opened directly by the
hFont=uisetfont command. The user can change some of the font specifications from
the dialog box, then click OK button to accept the setting. The returned argument hFont
is a structured variable, with members FontName (default 'Arial'), FontWeight (in bold
or not, 'normal'), FontAngle (in italic or not, default 'normal'), FontUnits (default of
'points') and FontSize (with default 10).


. Fig. 6.3 Standard font setting dialog box


6.3 · Interface Design of Apps
151 6
6.3.4 App Designer Programming
In the old versions of MATLAB, it was always suggested to use guide program
to design graphical user interface [2]. A new App Designer is released since 2016a
version, and becoming more and more powerful in App design.
The main facilities provided in the APP Designer are to help user to draw the
graphical user interface and generate the framework of the program. Callback func-
tions can be programmed in such a framework. It is similar to guide, but much more
powerful and convenient.
Issue the command appdesigner, the start page of App Designer is opened, as
shown in . Fig. 6.4. The existing programs written by guide program can also be
converted into the new framework of App Designer, such that it can be maintained
with the new tool. Introductory information is also provided in the program.
Select Blank App icon, a blank App design interface is opened, as shown in
. Fig. 6.5.
The interface had left, middle and right zones. The left one is labeled Component
Library; the one in the middle is the prototype window to be designed; the one on the
right is the Component Browser. There is a button named App Details, which allows
the user to specify more information about the App.
Expand the Component Library, all the components are shown in . Fig. 6.6. The
components can be dragged into the prototype window, and design the interface of
the problem. The program interface can then be designed in the prototype window,
and the initial properties can be set in the Component Browser on the right. Finally
the program framework can be generated.

. Fig. 6.4 Start page of APP Designer


152 Chapter 6 · Object-Oriented Programming

. Fig. 6.5 App Designer interface

. Fig. 6.6 Commonly used controls

An easy example is presented next to demonstrate the interface design methods


and the ideas in programming, with final implementations.

 Example 6.15
Design an App. Open a window with two controls on the window—one is a label and the
other is a push button. When the button is pressed, “Hello World!” string is displayed on
the label.
Solutions The design of OOP programs is different from the conventional ones. The most
important part is to write the response functions for the possible events. In this interface,
there are two controls. The push button can be considered as the active control. When
the button is pressed, an event message happens and is sent to the interface, to call the
corresponding response function. The action of the callback function is to modify the
contents of the label object. The label control is a passive one, who only accepts actions
from other controls. The passive ones do not have their own callback functions. Therefore
the crucial step in OOP is to design the corresponding callback functions. In this example,
6.3 · Interface Design of Apps
153 6
the button takes two actions, one is to find the label control, then modify the Text property
of the control to “Hello World!”.
Issue the command appdesigner, the APP Designer can be launched directly. The
icon in the lower-right corner of the prototype window can be dragged to the appropriate
size with the mouse. Then, the button and label control icons can be dragged to the prototype
window, as shown in . Fig. 6.7. The size and positions of the two controls can be assigned
with the mouse.
It can be seen that there are two controls on the prototype window. One is the label,
the other is the button. The user can also modify the Text property of the label control to
blank, with the interface. The handle app.Label is reserved for this object, listed in the
listbox on the right. The other properties such as font and font size can be adjusted in the
Component browser window on the right.
Another control is the button, whose Text property can be set to Press me. A handle
name app.PressmeButton can be assigned automatically to the button. The two items are
displayed in the Component browser. Also displayed is the one labeled app.UIFigure, which
is the handle of the window itself.
After drawing the prototype window, it can be saved to c6mapp1.mlapp file (or other
file names), with a suffix of mlapp, which is a new format for MATLAB interface. The
command can be executed directly in MATLAB command window, as if it is an m file.
Click the app.PressmeButton item in the Component browser, and click the Callbacks
tag, an overload function can be created. Let us review the tasks assigned to the button
earlier. Its task is to find the label and set its Text property to “Hello World!”. How to
find the control? The handle of the control is app.Label. How to modify its properties?
The modification of properties is simple. There is no need to use the set() in the earlier
versions. A statement can be added directly in the automatically generated framework for
the callback function. Then the program design is completed.

function PressmeButtonPushed(app, event)


app.Label.Text='Hello World!'; % set the string directly into the Text property
end
When the file is saved, type command c6mapp1 in the MATLAB command window, the
user interface is opened directly. Click the Press me button, the static string “Hello World!”
appears in the window. 

. Fig. 6.7 Prototype window and component browser (file name: c6mapp1.mlapp)
154 Chapter 6 · Object-Oriented Programming

Very good prompting facilities are provided in App Designer. For instance, if the
user inputs app., all the component names under app are listed; if a letter L is typed,
all the component names started by L are listed. In this example, the name Label is
filled in the code directly. If a decimal point (.) is then typed, all the property names
of the component are listed. In this way, callback functions can be written easily.
It can be seen that the programming procedures are simple and straightforward.
The three steps should be used—draw the interface, assign the tasks and finally write
the callback functions. The program can then be written.

 Example 6.16
Consider the Brownian motion animation problem in Example 5.26. If the user wants to
adjust the parameters such as scaling factor and number of particles, create an App to
demonstrate Brownian motion animation.
6 Solutions Open the App Designer, and draw the prototype of the interface, as shown in
. Fig. 6.8. It can be seen that two edit boxes are designed for Particles N and Scaled factor
s, used to input the variables N and s; a Slider control is also added, to input also the
value of N. Therefore, the Slider should be associated with the edit box Particles N; an axis
control is UIAxes, where the properties Font Name is set to Times-Roman, FontSize is set to
12; a push button Animation is designed to activate the animation process. The properties
of each control can be further assigned, but they are not discussed any more here. The
interested readers can open the program using App Designer, observe the interface and
read the functions.
When the prototype interface is drawn, the tasks should be assigned to the two active
controls. For instance, Particles N and Slider controls are associated. If one of them is
altered, the other one should be updated and assigned to the same Values. Therefore
the following callback function pairs can be written. Note that the scalar values can be
adjusted to decimal points, while since the particle number should be integers, such that
integer rounding command should be used in the callback function.

function SliderValueChanged(app, event)


app.ParticlesNEditField.Value=round(app.Slider.Value);
end

. Fig. 6.8 Prototype window for Brownian motion animation (file name: c6mbrown.mlapp)
6.3 · Interface Design of Apps
155 6
function ParticlesNEditFieldValueChanged(app, event)
app.Slider.Value=app.ParticlesNEditField.Value;
end
Another active control is the Animation button, whose tasks assigned are get the number
of particles n and the scaling factor s from the edit boxes; get a file name for videos; open
the file, modify and embed the code in Example 5.26 to the callback function. The term
edit above indicates to modify the axes. After writing the file, close the file. Therefore the
following callback function can be written:

function AnimationButtonPushed(app, event)


h=app.UIAxes; % get the axis handle, and draw plot in the next command
h0=plot(h,1,1,'o','MarkerSize',2); axis([-30,30,-30,30])
[f,p]=uiputfile('*.avi','Select a file name'); % open a file dialog box
if length(f)~=0, vfile=[p,f]; else, vfile='brown.avi'; end
n=round(app.ParticlesNEditField.Value); % round edit box number
s=app.ScaledfactorsEditField.Value; % get the values of 2 variables
x=randn(1,n); y=randn(1,n); vid=VideoWriter(vfile); open(vid);
for k=1:200 % animate for 200 steps in a loop
x=x+s*randn(1,n); y=y+s*randn(1,n); % update particles' locations
h0.XData=x; h0.YData=y; drawnow % make a frame of image
hVid=getframe(h); writeVideo(vid,hVid); % write a frame to the video
end, close(vid)
end


 Example 6.17
After writing a program, the next step is to check whether there are bugs in the program. If
there are, how to fix them? For the program written in Example 6.16, check whether there
are bugs, and fix the possible bugs.
Solutions Analyzing the program in Example 6.16, it can be seen that the Edit Field(Numeric)
are used, therefore, non-numeric quantities are not allowed to fill in the edit boxes. The
only possible bug may exist in the Particles N edit box, since it should be associated with
the Slider. If the value entered in the edit box exceeds the [0, 100] limit of the Slider, errors
occur. To fix the bug, if the value specified in the edit box exceeds the limit, it can be set to
100, then the two components are updated simultaneously. Therefore the callback function
can be modified as follows:

function ParticlesNEditFieldValueChanged(app, event)


v=app.ParticlesNEditField.Value; % read the value if the edit box
if v<=1 || v>100, v=100; end % if exceeds the limit, set it to 100
app.ParticlesNEditField.Value=v; app.Slider.Value=v;
end

156 Chapter 6 · Object-Oriented Programming

6.4 Exercises
(1) Consider a new operator a * b = (a + b) + 2(a − b). Use OOP method to create
such a class, and compute the new operations 123 * 54, 123 * (32 * 23). In fact, if
OOP is not used, a new function newtimes() can be written to redefine the new
operation. Unfortunately, if it is implemented like this, the operator * cannot
be used.
(2) Write an overload function latex() for ppoly class, such that the object can
be converted into a LATEX string.
(3) Write an overload function eq() for ppoly object to check whether two ppoly
objects are equal or not. If they are equal, it returns logic 1, otherwise, 0 is
returned.
(4) Write a set() overload function for the ppoly class, with the syntax
set(p,property,value), such that it specifies values for several fields simulta-
6 neously. If the property is no one of 'a' or 'na', an error message is displayed.
(5) Design a temperature converting App, such that the Fahrenheit and Celsius
systems can be interchanged. Two edit boxes can be placed in the interface,
representing Fahrenheit and Celsius respectively. If one of them is modified,
the other is converted automatically. Note that the converting formula is C =
5(F − 32)/9.
(6) Set the printer of the current window in the Orientation property to portrait.
(7) Design a simple interface. Allowing to input the magnitude, frequency and
initial phase in three edit boxes. Then Press the button, the sinusoidal function
curve can be draw in the axis. Also design a list box, allowing the user to select
sine, cosine and tangent functions from it.
(8) Add more tunable parameters in the App in Exercise 6.16, such as the symbol
size, the number of loops and so on.

6.5 Mini-Projects
1. Fractional-Order Transfer Function

Consider the fractional-order transfer function (FOTF) given below:

b1 sγ1 + b2 sγ2 + · · · + bm sγm


G(s) = . (6.9)
a1 sη1 + a2 sη2 + · · · + an−1 sηn−1 + an sηn

It can be seen that FOTF model is in fact the ratio of two pseudo-polynomials.
Based on the existing ppoly class, design a high-level class for FOTFs. It is advised
that the name fotf is not used, select an alternative one for your own. The designed
class should contain at least the following overload functions:
(1) The definition function, allowing at least the input commands G = myfun
('s'), G = myfun(a,η,b,γ ), G = myfun(pd ,pn ).
(2) A display function.
(3) Arithmetic operation with the operators +, -, *, /, \, ^, and an overload function
feedback().
References
157 6
(4) A like-term collection function to simplify the FOTF.
Once the class is designed, use it to solve the following problem:
Assume that under typical unity negative feedback connections, the plant and
controller models are given, respectively, as [3]

0.8s1.2 + 2 1.2s0.72 + 1.5s0.33


G(s) = , G c (s) =
1.1s1.8 + 0.8s1.3 + 1.9s0.5 + 0.4 3s0.8

find the closed-loop model.

2. An App Design Task

Design an App to display mathematical function curves. The App should contain at
least the following controls and tasks:
(1) An edit box allowing the user to specify mathematical functions.
(2) An axis object where the function curves are drawn.
(3) A button, when it is clicked, the string in the edit box is acquired and processed
so that the mathematical function can be built up. Then the curve of the function is
drawn in the axis object.
(4) Other supporting objects, such as a checkbox to determine whether “hold on”
mode is enabled; a pair of edit boxes to accept plotting interval information.
(5) Fault tolerance facilities, such that if the mathematical function input is invalid,
an error box is shown.
Use your imaginations and talent to build a powerful graphical tool.

References
1. Register AH (2007) A guide to MATLAB object-oriented programming[M]. Chapman & Hall/CRC,
Boca Raton
2. Xue DY (2020) MATLAB programming−Mathematical problem solutions[M]. De Gruyter, Berlin
3. Xue DY, Bai L (2023) Fractional calculus: high-precision algorithms and numerical applications
implementations[M]. Springer, Singapore
159 II

Scientific Computing
161 7

Calculus and Integral


Transforms
Contents

7.1 Analytical Solution of Calculus Problems – 162


7.1.1 Limit of Univariate Functions – 163
7.1.2 Limits of Multivariate Functions – 168
7.1.3 Derivatives – 170
7.1.4 Integrals – 177

7.2 Series Approximation of Functions – 181


7.2.1 Taylor Series – 181
7.2.2 Fourier Series – 184
7.2.3 Series Sums – 185
7.2.4 Product of Sequences – 188
7.2.5 Convergence of Infinite Series – 190

7.3 Numerical Calculus Solutions – 191


7.3.1 Numerical Differentiation – 192
7.3.2 Numerical Integrals – 193

7.4 Introduction to Integral Transforms – 200


7.4.1 Laplace Transform – 200
7.4.2 Numerical Laplace Transform – 202
7.4.3 Fourier Transform – 204
7.4.4 z Transform – 205

7.5 Exercises – 206

7.6 Mini-Projects – 213

References – 214

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_7
162 Chapter 7 · Calculus and Integral Transforms

In the calculus course, the solutions of limit, differentiation, integrals, series and
series approximations of given functions are mainly studied. The solution methods
are all manual methods, where a lot of exercises must be worked out, and different
skills in solving these problems should be mastered. Many functions are provided in
the Symbolic Math Toolbox in MATLAB to solve the calculus problems directly.
These functions cover all aspects of calculus and can be used to solve analytical
calculus problems directly. Numerical differentiation, integral problems and integral
transforms are also presented in this chapter.
In 7 Sect. 7.1, the solutions of limit, differentiation and integrals can be found.
Univariate and multivariate problem solutions are both considered. In 7 Sect. 7.2,
Taylor and Fourier series expansion and approximation to given functions are stud-
ied. Graphical facilities in MATLAB are used to assess approximation results. Also,
sum and product of finite and infinite series can be solved, and convergence test of
infinite series is explored. With all the methods introduced above, the computing
problems in calculus work books, such as Reference [1], can be solved easily, and
with the help of MATLAB graphical facilities, much more useful information can be
7 found. In 7 Sect. 7.3, numerical differentiation and integral methods are illustrated.
If the original functions are unknown, only a set of samples are given, the calculus
problem can still be solved. Besides, when the analytical solutions to integrals are not
available, numerical integrals can be worked out. In 7 Sect. 7.4, the Laplace, Fourier
and z transforms are also addressed. If there are no analytical solutions, numerical
integral transforms are also studied.
There is another important problem in the traditional calculus course—solutions
of differential equation solutions. This topic is not covered in this chapter, and
7 Chap. 10 is dedicated to the analytical and numerical solutions of various dif-
ferential equations.

7.1 Analytical Solution of Calculus Problems


Limit, differentiation and integral problems are the essential problems in calculus. In
this section, the solutions to limit problems are introduced first, and the derivative
and partial derivatives of explicit function are presented, followed by derivatives
of implicit functions and parametric equations. Finally, different integrals such as
indefinite, definite, infinite and improper integrals are also solved analytically. These
analytical solution functions are summarized in . Table 7.1.
Solutions to path and surface integrals are not discussed in this book. Interested
readers may refer References [2, 3], where the two functions, path_integral() and
surf_integral() written by the author can be used to solve directly the related
problems.
7.1 · Analytical Solution of Calculus Problems
163 7

. Table 7.1 Commonly used solvers for analytical calculus solvers

Operations Descriptions

Limit L=limit(f , x, x0 ) evaluates L = lim f (x), where f is the symbolic variable


x→x0
containing unknowns. If f contains only one variable, x can be omitted. x0 can
be constant, function or inf. One-sided limit can be found with L =limit (f ,x,
x0 ,'left') or L=limit(f ,x, x0 ,'right')

Derivative D = diff(f , x, n) computes D = dn f /dxn . If n = 1, it can be omitted; it also


applies in partial derivative computing, For instance, D=diff(f ,x,x,x,y) yields
∂ 4 f /∂x3 ∂y

Derivative D = paradiff(y, x, t, n), the author’s MATLAB function for finding derivatives
of parametric of parametric equations, where y(t) and x(t) are described as symbolic variables y
equations and x, while t in independent variable, n is the order, such that D = dn y/dxn

Derivative D = impldiff(f , x, y, n), the author’s MATLAB function for implicit function
of implicit f (x, y) = 0, where f , x and y are symbolic expressions, n is the order. The return
functions D is dn y/dxn

Integral F = int(f , x) finds the indefinite integral F = f (x)dx; F =int(f ,x,a,b)
 b
compute directly definite integral F = f (x)dx; a and b can be variables or inf;
a
multiple integrals can be found by the nested use of int() function

7.1.1 Limit of Univariate Functions


In this section, the solutions of various limit problems are addressed. This includes
function and sequence limit problems, one-sided limit problems. If needed, graphical
facilities in MATLAB can be employed, so as to better describe the convergency and
tendency in limit problems, and better handle these problems.

1. Limit of a Function
Limit problems are the mathematical foundation of the entire calculus course. It is
even pointed out in Reference [4] that calculus is the study of limit problems. Assume
that f (x) is known, the mathematical form of the limit problem can be expressed as

L = lim f (x), (7.1)


x→x0

whose physical interpretation is that when the independent variable x tends to x0


infinitely, the function f (x) tends to which value.
Limit problems can be solved directly with limit() function in Symbolic Math
Toolbox. The syntaxes of the function are
L=limit(f ,x0 ), % default independent variable
L=limit(f ,x,x0 ), % ordinary statement
164 Chapter 7 · Calculus and Integral Transforms

Before solving the problem, variable x should be declared as a symbolic one first,
then define the function expression f , which can either be a symbolic expression or a
symbolic function. If x0 is ∞, the constant inf can be used. In this section, examples
are illustrated to show computer solutions of limit problems.

 Example 7.1
sin x
Solve the important limit problem lim .
x→0 x
Solutions Three steps are involved in the solution of limit problems:
(1) Declare necessary symbolic variables. In this example, declare x.
(2) Express f (x) = sin x/x in MATLAB.
(3) Call MATLAB solver limit() to find the limit directly.
To implement the three steps in MATLAB, the following commands should be issued.
After execution, the solution is L = 1.
7 >> syms x; f(x)=sin(x)/x; L=limit(f,0) % solve limit problem directly
Since symbolic function is used to describe function f (x), x can be omitted in the limit()
function call. Of course, the following statements can also be used, and the results are the
same.
>> x0=-0.1+1e-6:0.001:0.1; % x vector, bypass x=0 point
plot(x0,f(x0),0,1,'o'), ylim([0.99,1.001]) % draw the curve of the function
With powerful tools such as MATLAB, the curve of the function in the interval x ∈
(−0.1, 0.1) can be drawn, as shown in . Fig. 7.1. We can observe the behaviors of the
function in any specified interval. Note that since at x = 0, the function value is NaN, a
small offset 10−6 is introduced in generating x vector, to deliberately bypass the x = 0
point.
>> syms x a b; f(x)=x*(1+a/x)^x*sin(b/x); L=limit(f,inf) % compute directly


1
0.999
0.998
0.997
0.996
0.995
0.994
0.993
0.992
0.991
0.99
-0.1 -0.08 -0.06 -0.04 -0.02 0 0.02 0.04 0.06 0.08 0.1

. Fig. 7.1 The behaviors of the function about x = 0


7.1 · Analytical Solution of Calculus Problems
165 7

 Example 7.2
  
a x b
Solve the limit problem lim x 1 + sin .
x→∞ x x
Solutions With MATLAB, symbolic variables a, b and x are declared first. Then define
the function. Finally call limit() function to compute the limit, and the solution is ea b.
It is seen that the solution of the problem is as simple as the one in Example 7.1, from the
user’s viewpoint.
>> syms x a b; f(x)=x*(1+a/x)^x*sin(b/x); L=limit(f,inf) % compute directly
For the previous code, symbolic function was used to describe the function. If symbolic
expression is used to describe the function, it is necessary to indicate the symbolic variable
x, since it is not the unique symbolic variable. The following commands yield the same
result:
>> f=x*(1+a/x)^x*sin(b/x); L=limit(f,x,inf) % specify independent variable


 Example 7.3
1 1
Solve the limit problem: lim  √ −  √ .
x→1 2 1 − x 3 1− 3 x
Solutions To solve the problem, a symbolic variable is declared first. The function is fed into
MATLAB workspace, then, call limit() function to get the solution, which is L = 1/12.
>> syms x; f(x)=1/2/(1-sqrt(x))-1/3/(1-x^(1/3)); L=limit(f,1)


 Example 7.4
Compute lim xn and lim xn .
x→∞ n→∞

Solutions If the manual method is used, we have to consider the problems in several cases,
where each case is solved individually. If MATLAB is used, no manual classification is
needed. The following commands can be used directly:
>> syms x n real; f=x^n; % describe the original function
L1=limit(f,n,inf), L2=limit(f,x,inf) % compute the two limits
which yields piecewise functions as the results. For instance, L2 is
piecewise([n ==0,1],[0 < n,inf],[n < 0,0])
The two limits are expressed mathematically as follows.

⎪ 1, x=1 ⎧

⎨ ⎨ 1, n = 0
∞, x>1
L1 = L2 = ∞, n > 0
⎪ no limit,
⎪ x < −1 ⎩
⎩ 0, n < 0.
0, 0 < x < 1 or − 1 < x < 0,


166 Chapter 7 · Calculus and Integral Transforms

2. Limit of a Sequence
For sequence limit problems, the above commands can be used directly. Normally
there is really no need to specify n as an integer symbolic variable. Ordinary symbolic
variables are sufficient.

 Example 7.5
2
Compute the sequence limit lim (n!)1/n .
n→∞
Solutions Declare n as a symbolic variable. It can also be specified as an integer sym-
2
bolic variable. The expression (n!)1/n can then be described, where n! is computed with
factorial() function. Therefore the following commands compute the limit, and the
result is L = 1.
>> syms n; % or issue the command syms n integer
f=factorial(n)^(1/n^2); L=limit(f,n,inf) % compute the limit directly

7 For the pure sequence problem, MATLAB graphics facilities can be used, to draw the stem
plot of the sequence, as shown in . Fig. 7.2. It can be used to better describe the trend of the
sequence. For this particular example, it can be seen that the sequence value is smaller and
smaller. When n = 1000, the function value is 1.0059. Further increasing n, the sequence
values tend to 1.
>> n0=1:50; y=subs(f,n,n0); stem(n0,y), double(subs(f,n,1000))


 Example 7.6
Solve the limit problem.
   
lim n arctan
1
tan n π + x .
n→∞ n(x2 + 1) + x 4 2n

Solutions The expression here is a sequence of a function. But this does not introduce extra
difficulties in solving the problem. The two symbolic variables n and x are specified. With

1.4

1.2

0.8

0.6

0.4

0.2

0
0 5 10 15 20 25 30 35 40 45 50

. Fig. 7.2 The trend of the sequence


7.1 · Analytical Solution of Calculus Problems
167 7
the following commands, which yields the result ex /(x2 + 1). It can be seen that for the
users, the solution of the problem is as simple as the sin x/x limit problem.
>> syms x n; f(x)=n*atan(1/(n*(x^2+1)+x))*tan(pi/4+x/2/n)^n;
L=limit(f,n,inf) % compute the limit directly


3. One-Sided Limits
In the previous limits, x → x0 usually means x approaches to x0 in either of the
directions. While in real applications, sometimes it may only allow x tends to x0 from
left, or from right only. The is the so-called one-sided limit problem.
The mathematical form of one-sided limit problem is either

L1 = lim f (x), or L2 = lim f (x). (7.2)


x→x0− x→x0+

It can be seen that the former one means x tends to x0 point from the left, thus
it is referred to as left limit, while the latter is right limit problem. One-sided limit
problem can also be solved with limit() function, in either the forms.
L=limit(f ,x,x0 ,'left'), or , L =limit(f ,x,x0 ,'right')

 Example 7.7
Find the one-sided limit

   
       
 1    1  
1   1 1 1  1   1 1 1
lim  + + + + − − + − + .
x→0+ x x x x x x x x x x

Solutions Solving such a problem is as simple as solving other limit problems, where the
procedures are the same. Declare first a symbolic variable, the original function can be
expressed in MATLAB. Then limit() function can be called directly to find the expected
one-sided limit. The result is 1. In fact, if the multiples of the function are increased, the
result is also 1.
>> syms x positive
f(x)=sqrt(1/x+sqrt(1/x+sqrt(1/x+sqrt(1/x+sqrt(1/x)))))-...
sqrt(1/x-sqrt(1/x+sqrt(1/x-sqrt(1/x+sqrt(1/x)))));
L=limit(f,x,0,'right')
For this particular function, if x < 0, the function is not defined in real framework. Therefore
x must be specified as positive values. Also when x = 0, then 0 is used as the divisor, the
function is also meaningless. We can only investigate the x > 0 case, thus we need to declare
x as a positive symbolic variable. The curve of the function in a small neighborhood of
x = 0 can be drawn, as shown in . Fig. 7.3. It is seen that when x → 0+ , the function is
indeed approaching to 1.
>> fplot(f,[-0.001,0.01]), hold on, plot(0,1,'o'), hold off

168 Chapter 7 · Calculus and Integral Transforms

1.05
1.045
1.04
1.035
1.03
1.025
1.02
1.015
1.01
1.005
1
-1 0 1 2 3 4 5 6 7 8 9
10-3

. Fig. 7.3 Curve of the function in a neighborhood of x = 0

7 7.1.2 Limits of Multivariate Functions


For multivariate functions, the limit problems can be classified into two cases. One
is the sequential limit, and the other is multiple limit. In this section, the definitions
of the two cases are presented, and the solution methods are explored.

1. Sequential Limits
When the independent variables in a multivariate function f (x1 , x2 , . . . , xn ) tend to
their target values in a certain order, the limit is referred to as sequential limit. For a
given function f (x, y), the two sequential limits are defined as
   
L1 = lim lim f (x, y) , or L2 = lim lim f (x, y) , (7.3)
x→x0 y→y0 y→y0 x→x0

where x0 and y0 can be values or even functions.


Consider L2 . The physical interpretation can be understood as for the limit of the
function f (x, y) when x → x0 can be found first, then for the result, find the limit
when y → y0 . Here in the inner limit, x0 can be constant or infinity, or even a function
of y.
With MATLAB, the sequential limits are evaluated with the following statements,
where the limit() function is used in a nested way.
L1 =limit(limit(f ,y,y0 ),x,x0 ), % limit when y first then x
or L2 =limit(limit(f ,x,x0 ),y,y0 ), % x first then y

 Example 7.8
Compute the sequential limit of the function
 2 2
2 
2 sin x

1 x+a y
lim√ e−1/(y +x ) 2
2
lim 1+ 2 .
y→∞ x→1/ y x y
7.1 · Analytical Solution of Calculus Problems
169 7

Solutions Since y term is involved, the variable y should be declared as a positive symbolic
variable. Therefore the following commands compute directly the sequential limit, whose
2
result is ea .
>> syms x a; syms y positive; % declare symbolic variables and let y positive
f(x,y)=exp(-1/(y^2+x^2))*sin(x)^2/x^2*(1+1/y^2)^(x+a^2*y^2);
L=limit(limit(f,x,1/sqrt(y)),y,inf) % solve direct the sequential limit problem


2. Multiple Limits
For the multivariate function f (x1 , x2 , . . . , xn ), if all the independent variables tend
to their targets simultaneously, the limit is referred to as multiple limit. For a function
f (x, y), the multiple limit is expressed as

L= lim f (x, y). (7.4)


(x,y)→(x0 ,y0 )

The physical interpretation of multiple limit is that, the two variables (x, y) tend
to the target (x0 , y0 ) along any direction simultaneously, the multiple limit can be
defined. On the current computers, there is no way to implement at any direction.
Therefore some specific directions can be selected. Normally if the limits obtained in
this way are identical, the multiple limit may probably equal to such a value. Besides,
there are cases when the two statements yield the same limit value, or the two are
equal, but the multiple limit does not exist. Therefore care must be taken to select
different specific directions and observe whether the consistent result can be found.
If the limit under a certain direction is clearly different from the ones in other
directions, it is sufficient to say that the multiple limit for the f (x, y) function does
not exist.

 Example 7.9
Compute the multiple limit lim x sin(1/y) + y sin(1/x).
(x,y)→(0,0)

Solutions For the particular example, three directions are selected, let y = kx, y → x2 or
x → y2 . All the three sequential limits are the same, L1 = L2 = L3 = 0. Therefore the
multiple limit is probably 0.
>> syms k x y;
f(x,y)=x*sin(1/y)+y*sin(1/x); L1=limit(f(x,k*x),x,0)
L2=limit(limit(f,x,y^2),y,0), L3=limit(limit(f,y,x^2),x,0)
Consider using MATLAB to generate some mesh grids around the origin with
meshgrid() function. Note that to avoid efficiently the points on the two lines x = 0
and y = 0, a small offset can be selected. The following commands compute z values at the
mesh grids, and the surface can be obtained, as shown in . Fig. 7.4. It can be seen that
around the (0, 0) point, the surface is rather flat, which means that the multiple limit exists
and equals 0 (The solution of Exercise (28)) in Chap. 5.
>> [x0 y0]=meshgrid((-0.1+1e-6):0.002:0.1); % generate mesh grids
z=double(f(x0,y0)); surf(x0,y0,z) % draw surface
170 Chapter 7 · Calculus and Integral Transforms

. Fig. 7.4 The surface about the (0, 0) point

To better demonstrate the limit problem graphically, it is not recommended to use fsurf()
7 function. The above commands are recommended. 

 Example 7.10
xy
Judge whether the multiple limit lim exists or not.
(x,y)→(0,0) x2 + y2

Solutions It is not really easy to compute the multiple limit of a certain problem with the
use of computers, since all the directions must be considered. To the contrary, it is much
easier to point out that a multiple limit does not exist. Since if we can find any limits in
different directions are different, for instance, y = rx, where r is a symbolic variable, and
the sequential limit is dependent upon r, it is adequate to say that the multiple limit does
not exist. The following commands can be executed first:
>> syms r x y; f(x,y)=x*y/(x^2+y^2); L=limit(subs(f,y,r*x),x,0)
The result obtained is L = r/(r2 + 1), dependent upon r, therefore the multiple limit does
not exist.
If graphical method is used, the surface obtained is as shown in . Fig. 7.5. It can be seen
that around (0, 0) point, the limit values under different directions are different. The limit
can be any value in the (−0.5, 0.5) interval. Therefore the multiple limit does not exist.
>> [x0 y0]=meshgrid((-0.1+1e-6):0.002:0.1);
z=double(f(x0,y0)); surf(x0,y0,z)


7.1.3 Derivatives
Derivatives of functions are the essentials in differential calculus. It is also an impor-
tant tool in scientific research and engineering practice. In this section, the definition
of derivative is given, and MATLAB-based solutions are illustrated. Partial deriva-
tives, derivatives of implicit functions and parametric equations are introduced.
7.1 · Analytical Solution of Calculus Problems
171 7

. Fig. 7.5 The surface around the (0, 0) point

1. Derivatives and High-Order Derivatives


The first-order derivative of function y = f (x) with respect to x is defined as

df (x) f (x + x) − f (x)


f  (x) = = lim . (7.5)
dx x→0 x

 Example 7.11
sin x
For function f (x) = 2 , find the first-order derivative from definition.
x + 4x + 3
Solutions With the above-mentioned computing method for limits, the first-order derivative
of the given function can be found from definition.
>> syms x h; f(x)=sin(x)/(x^2+4*x+3); % declare symbolic variable, and function
F=limit((f(x+h)-f(x))/h,h,0) % find derivative fromdefinition
The result obtained is

cos x (2x + 4) sin x


F (x) = 2 − 2 .
x + 4x + 3 x2 + 4x + 3


The second-order derivative of f (x) with respective to x is the derivative of the


function f  (x) with respect to x, denoted as f  (x). Third-order derivative is denoted
as f  (x). Similarly, the nth-order derivative is denoted as dn f (x)/dxn or f (n) (x).
If the function and independent variables are known and are all symbolic variables,
function diff() gets various derivatives, with the syntax f1 =diff(f ,x,n), where f is
the given function, x is the independent variable. The two variables are both symbolic
variables. The variable n is the order of the derivative, which can only be given integer
values. If n is omitted, the first-order derivative is found. If f is the expression with
only one symbolic variable, or if f is a symbolic function, variable x can be omitted.
172 Chapter 7 · Calculus and Integral Transforms

 Example 7.12
sin x d4 f (x)
For the function f (x) = 2 , compute .
x + 4x + 3 dx4
Solutions To find the derivative, the following three steps are used:
(1) Declare symbolic variable x
(2) Use MATLAB command to describe the original function
(3) Call function diff() directly to compute the derivative.
The following commands can be used to implement the three steps. The first-order deriva-
tive can be found, which is the same as the one in Example 7.11.
>> syms x; f(x)=sin(x)/(x^2+4*x+3); f1=diff(f)
The fourth-order derivative of the function can also be found with
>> f4=diff(f,x,4); % fourth-order derivative, see Chapter 1
Higher-order derivatives can be found in MATLAB with diff() function. For instance,
7 the hundredth-order derivative of the function can be found within 3 s.
>> tic, diff(f,x,100); toc % find 100th-order derivative, measure time elapse


 Example 7.13
Find the nth-order derivative of function y(x) = (ax + b)/(cx + d).
Solutions The nth-order derivative of f (x) cannot be found with diff() function directly.
Select several finite integers for n, the results can be found. Check the results and see whether
some useful conclusions can be summarized from the results.
>> syms x a b c d; f(x)=(a*x+b)/(c*x+d);
f1=simplify(diff(f,x,1)), f2=simplify(diff(f,x,2))
f3=simplify(diff(f,x,3)), f4=simplify(diff(f,x,4))
f10=simplify(diff(f,x,10)), f11=simplify(diff(f,x,11))
It is immediately found that

ad − bc 2c(ad − bc)
f1 = , f2 = − ,
(d + cx)2 (d + cx)3
6c2 (ad − bc) 24c3 (ad − bc)
f3 = , f4 = − ,
(d + cx)4 (d + cx)5
−3628800c9 (ad − bc) 39916800c10 (ad − bc)
f10 = , f11 = .
(d + cx) 11 (d + cx)12

It can be concluded from the results that


 
dn ax + b (−1)n+1 n! cn−1 (ad − bc)
= . (7.6)
dxn cx + d (d + cx)n+1


7.1 · Analytical Solution of Calculus Problems
173 7
2. Partial Derivatives of Multivariate Functions
For the function z = f (x, y), the firth-order partial derivatives of z with respect to x
is defined as
∂f (x, y) f (x + x, y) − f (x, y)
= lim . (7.7)
∂x x→0 x
More generally, although multivariate function is directly related with several
variables, when taking partial derivative with respect to x, the remaining variables
are regarded as constants, thus the function is only a function of x. In this way the
result can be found.
Similarly, the partial derivative with respect to y can be written as ∂f (x, y)/∂y,
and the high-order partial derivatives can also be defined.
There is no dedicated function in MATLAB for solving partial derivative prob-
lems. The partial derivatives can still be evaluated with the function diff().
For a given function f (x, y), MATLAB function diff() can be directly called to
compute ∂ m+n f /(∂xm ∂yn ) in a nested way.
f1 =diff(diff(f ,x,m),y,n) or f1 =diff(diff(f ,y,n),x,m)
In recent versions, the following format can be alternatively used:
f1 =diff(f ,x, · · · , x, y, · · · , y)
     
m terms n terms
Due to the use of the new format, the variable n cannot be used to get nth-order
derivative. Otherwise, it may be misunderstood as taking derivative with respect to
n. Therefore the derivative obtained is 0.

 Example 7.14
Find the first-order derivatives of function z = (x2 − 2x)e−x −y −xy , and use graphical
2 2

method to show the results.


Solutions With the following commands: ∂z/∂x and ∂z/∂y can be found.
>> syms x y; z(x,y)=(x^2-2*x)*exp(-x^2-y^2-x*y);
zx=simplify(diff(z,x)), zy=diff(z,y)
and the mathematical forms (also known as gradient) are, respectively.

∂z(x, y)
= −e−x −y −xy (−2x + 2 + 2x3 + x2 y − 4x2 − 2xy),
2 2

∂x
∂z(x, y)
= −x(x − 2)(2y + x)e−x −y −xy .
2 2

∂y

In the range x ∈ (−3, 2), y ∈ (−2, 2), mesh grids can be generated to evaluate the func-
tion and its partial derivatives. The following commands draw the 3D surface, shown in
Fig. 5.21.
>> [x0,y0]=meshgrid(-3:.2:2,-2:.2:2); z0=double(z(x0,y0));
surf(x0,y0,z0), zlim([-0.7 1.5]) % draw the 3D surface
Since the two first-order partial derivatives are found, quiver() function can be called to
draw the quivers, and superimpose them on the contour by contour() function, as shown
in . Fig. 7.6. If a ball is placed on the surface, it rolls down along the arrows, and the
174 Chapter 7 · Calculus and Integral Transforms

1.5

0.5

-0.5

-1

-1.5

-2
-3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2

. Fig. 7.6 Quiver plots of the gradient functions

7 speed can be described by the length of the arrow. More information on the function can
be found with doc quiver command.
>> contour(x0,y0,z0,30), hold on; % draw the contour lines
zx0=double(zx(x0,y0)); zy0=double(zy(x0,y0));
quiver(x0,y0,-zx0,-zy0) % negative values


 Example 7.15
∂ 4 f (x, y, z)
of f (x, y, z) = sin(x2 y)e−x y−z .
2 2
Find the partial derivative
∂x2 ∂y∂z
Solutions Symbolic variables are declared first, and the following MATLAB commands
compute the expected partial derivatives:
>> syms x y z;
f(x,y,z)=sin(x^2*y)*exp(-x^2*y-z^2); % declare variables and function
F=diff(f,x,x,y,z) % compute directly partial derivative
The result obtained is
2 
F = −4ze−x y−z cos x2 y−10yx2 cos x2 y+4x4 y2 sin x2 y+4x4 y2 cos x2 y−sin x2 y .
2

3. Partial Derivatives of Implicit Functions


For implicit functions, there is no existing solver provided to find partial derivatives.
The mathematical methods should be revisited, such that a universal solver can be
written.
Consider the implicit function f (x, y) = 0. Denote that F0 (x, y) = f (x, y), the
first-order partial derivative can be written as
7.1 · Analytical Solution of Calculus Problems
175 7
∂F0 (x, y)/∂x
F1 (x, y) = ∂y/∂x = − .
∂F0 (x, y)/∂y

The second-order derivative function can be found easily as

∂ 2y ∂F1 (x, y) ∂F1 (x, y)


F2 (x, y) = = + F1 (x, y). (7.8)
∂x2 ∂x ∂y

The nth-order partial derivative can be derived in a recursive way as

∂ ny ∂Fn−1 (x, y) ∂Fn−1 (x, y)


Fn (x, y) = = + F1 (x, y). (7.9)
∂x n ∂x ∂y

The high-order derivatives of the implicit function can easily be evaluated from
(7.9), and it is easy to implement the algorithm in MATLAB. The partial derivative
f1 = ∂ n y/∂xn can be found with the command f1 =impldiff(f ,x,y,n).
function dy=impldiff(f,x,y,n)
arguments
f, x, y, n(1,1){mustBePositive, mustBeInteger}=1;
end
F1=-simplify(diff(f,x)/diff(f,y)); dy=F1; % 1st-order
for i=2:n, dy=simplify(diff(dy,x)+diff(dy,y)*F1); % (7.9)
end, end

 Example 7.16
For the given implicit function x2 sin y + y2 z + z2 cos y − 4z = 0, find the partial derivatives
∂z/∂x and ∂ 2 z/∂x2 .
Solutions The original function is in fact f (x, y, z) = 0, with three independent variables.
The partial derivatives between x and z are needed. Therefore, in the original function, y
can be regarded as a constant. The following commands can be issued:
>> syms x y z;
f(x,y,z)=x^2*sin(y)+y^2*z+z^2*cos(y)-4*z;
F1=simplify(impldiff(f,x,z,1)), F2=simplify(impldiff(f,x,z,2))
The results obtained are

∂z −2x sin y
F1 = = ,
∂x 2z cos y + y2 − 4
∂ 2z −2 sin y 8x2 cos y sin2 y
F2 = = − .
∂x2 2z cos y + y2 − 4 (2z cos y + y2 − 4)3


176 Chapter 7 · Calculus and Integral Transforms

4. Derivatives of Parametric Equations


There are no existing solvers in MATLAB for finding derivatives for parametric
equations, once again a solver is needed for the problem.
For the given parametric equation y = f (t), x = g(t), the nth-order derivative
dn y/dxn can be recursively evaluated from

dy f  (t)
=  ,
dx g (t)
   
2
d y d f  (t) 1 d dy 1
= = ,
dx2 dt g  (t) g  (t) dt dx g  (t) (7.10)
..
.  
dn y d dn−1 y 1
= 
.
dx n dt dx n−1 g (t)

7 Based on the recursive formulas, a universal solver can be written as follows, where
loop structure is used such that the efficiency is higher than the one in Reference [2].
function result=paradiff(y,x,t,n)
arguments
y, x, t, n(1,1){mustBePositive, mustBeInteger}=1;
end
g1=diff(x,t); result=diff(y,t)/g1;
for i=2:n, result=diff(result,t)/g1; end
end

 Example 7.17
sin t cos t d3 y
For the parametric equation y(t) = , x(t) = , compute .
(t + 1)3 (t + 1)3 dx3
Solutions With the new function above, the third-order derivative can be found.

>> syms t; y=sin(t)/(t+1)^3; x=cos(t)/(t+1)^3;


f=simplify(paradiff(y,x,t,3))
The result obtained is

3 (t + 1)7 23 cos t + 24 sin t − 6t2 cos t − 4t3 cos t − t4 cos t

d3 y + 12t2 sin t + 4t3 sin t − 4t cos t + 32t sin t
=  5 .
dx3 3 cos t + sin t + t sin t


7.1 · Analytical Solution of Calculus Problems
177 7
7.1.4 Integrals
Integral problems are often regarded as the inverse problems of derivatives. For a
function F (x), the derivative f (x) can be found by the derivative methods presented
earlier. If function f (x) is known, how to find F (x)? This is the problem to be solved
in integral calculus. In this section, concentrations are made on the solutions of indefi-
nite, definite and improper integrals. Also multiple integrals of multivariate functions
are addressed.

1. Indefinite Integrals
The indefinite integral of function f (x) is defined as

F (x) = f (x)dx, (7.11)

where f (x) is the integrand, and F (x) is referred as primitive function.


Function int() provided in Symbolic Math Toolbox finds the infinite integral of
the given function, with F =int(f ,x). If the integrand f has only one symbolic variable,
or f is a symbolic function, the argument x can be omitted.
It should be noted that the result F (x) should be a cluster of functions F (x) + C,
where C is an arbitrary constant.

 Example 7.18
Consider the problem in Example 7.12. Use diff() function to find the derivative of f (x).
Compute its integral and see whether the original function can be restored.
Solutions Find the derivative first, then take integral to the result
>> syms x; y(x)=sin(x)/(x^2+4*x+3); % describe the original function
y1=diff(y); y0=simplify(int(y1)) % derivative then integral
the original function can be restored. In fact, the result should further be written as y1 (x) =
sin x/(x2 + 4x + 3) + C, where C is an arbitrary constant. If a point in the original function
is known, for instance, x = 0, y1 = 1, the undetermined coefficients can be uniquely found.
Substituting x = 0 into y1 (x) expression, it is found that C = 1.
Take fourth-order derivative to the function, and integrate the result four times, the
original function is restored.
>> y4=diff(y,4); y0=int(int(int(int(y4)))); % nested use of int() function
I=simplify(y0) % simplify integral results
Considering undetermined coefficients, the indefinite integral is

sin x
F (x) = 2 + C1 + C2 x + C3 x2 + C4 x3 .
x + 4x + 3

The undetermined coefficients are in fact the undetermined polynomial. To uniquely deter-
mine the coefficients, four given points on the original function must be provided. 
178 Chapter 7 · Calculus and Integral Transforms

 Example 7.19
Compute the indefinite integral

 4  4  3
I= sin3 x2 + 1 cos x2 + 1 x2 + 1 x dx.

Solutions If manual method is used, some skills must be needed. For instance, with variable
substitution method [4]. With MATLAB, there is no need to consider these information,
nor using other skills. The direct use of the commands solves the problem.
>> syms x; F(x)=sin((x^2+1)^4)^3*cos((x^2+1)^4)*(x^2+1)^3*x;
I=int(F,x)
The indefinite integral is

1 1
I= cos 4(x2 + 1)4 − cos 2(x2 + 1)4 + C.
256 64

7 

2. Definite Integral
In the previously presented indefinite integral problem, a cluster of functions can be
found. If the interval of integral is specified, definite integral problem can be posed,
and a unique integral function can be found. The mathematical form of definite
integral is given by
 b
I= f (x) dx. (7.12)
a
Function int() in MATLAB can still be used in finding definite integral prob-
lems, with the syntax I =int(f ,x,a,b), where x is the independent variable, (a, b) is
the interval. If a or b are infinite quantities, they can be represented by -inf or inf.
Function vpa() can also be used to find the high-precision solution of the integral
problem, if necessary.

 Example 7.20
Solve the definite integral problem
 1
y2 + 4y − 4
I=  dy.
0 y3 + 6y2 − 12y + 9

Solutions The following commands can be used directly to compute the definite integral:
>> syms y; f(y)=(y^2+4*y-4)/sqrt(y^3+6*y^2-12*y+9);
I=int(f,y,0,1), vpa(I)
The solution is rather complicated, and cannot be further simplified. With vpa() function,
it can be seen that the result approaches to −2/3 infinitely. The following commands can
be used to draw the filled plot of the integrand, as shown in . Fig. 7.7. The definite integral
of the problem is in fact the area of the filled zone. Since there is a zero-crossing point, the
eventual area is the sum of the positive area and the negative area.
7.1 · Analytical Solution of Calculus Problems
179 7

0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1.2
-1.4
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

. Fig. 7.7 The area bounded by the integrand

>> x0=0:0.01:1; f1=double(f(x0));


x0=[0 x0 1]; f1=[0 f1 0]; fill(x0,f1,'g')


3. Improper Integrals
If in the interval (a, b), the function f (x) is continuous, except at c point, where
lim |f (c)| = ∞, the integral is referred to as improper integral.
x→c
The singularity c divides the interval into two subintervals [ a, c1 ) and (c2 , b ]. The
improper integral can be mathematically evaluated from
 b  c1  b
f (x) dx = lim f (x) dx + lim f (x) dx. (7.13)
a c1 →c− a c2 →c+ c2

Such a rule is embedded in the integral solver in MATLAB, so that int() can
be called directly, as if there were no singularities. There is no need to find the
singularities, and there is no need to evaluate the one-sided limits, such that the
improper integral process is significantly simplified.

 Example 7.21
 2e
1
Compute the improper integral  dx.
1 x 1 − ln2 x
Solutions It can be seen that at x = e, the integrand is not continuous. Therefore the integral
is an improper one. The problemcan be solved directly with the following statements. The
solution to the problem is arcsin ln 2 + 1 ≈ 1.5708 − 1.1182j.
>> syms x; f(x)=1/x/sqrt(1-log(x)^2);
I=int(f,x,1,2*exp(sym(1))), vpa(I) % compute improper integral directly

180 Chapter 7 · Calculus and Integral Transforms

4. Multiple Integrals
The mathematical form of double integral is
 xM  yM (x)
I= f (x, y)dydx. (7.14)
xm ym (x)

Triple integral problem is


 xM  yM (x)  zM (x,y)
I= f (x, y, z)dzdydx. (7.15)
xm ym (x) zm (x,y)

It can be seen from the mathematical expression that if there is no analytical


solution in the inner integral, difficulties may be encountered on outer integrals.
Sometimes the analytical solutions to the entire integral problem cannot be found.
The symbolic int() function can be tried to get high-precision solution with the help
7 of vpa() function. If there is still no solution found, pure numerical solution solvers
should be employed.
Multiple integrals can be evaluated by the nested call of the int() function. There
is no need to make any special processing. Examples are used next to demonstrate
the computation of multiple integral problems.

 Example 7.22
 1  √1−y2
e−x /2 sinh(x2 + y) dxdy.
2
Compute the double integral J = √
−1 − 1−y2

Solutions We can still use the regular MATLAB commands to compute the multiple
integrals. In the solution process, make sure the lower and upper bounds are matched.
>> syms x y; f(x,y)=exp(-x^2/2)*sinh(x^2+y);
I=int(int(f,x,-sqrt(1-y^2),sqrt(1-y^2)),y,-1,1),
tic, I1=vpa(I), toc
Unfortunately, there is no analytical solution to the integral. Function vpa() can be used
to get high-precision solutions, I1 = 0.70412133490335689947800312022517. The high-
precision solutions are obtained by the embedded numerical algorithm in the symbolic
engine. Due to the use of such a mechanism, the solution speed may be very time-consuming.
In this example, the total time elapse is 354 s. 

 Example 7.23
 2 π π
4xze−x y−z dzdydx.
2 2
Solve the triple integral problem
0 0 0
Solutions The following commands immediately solve the triple integral problem:
>> syms x y z; F(x,y,z)=4*x*z*exp(-x^2*y-z^2); % original function
I=int(int(int(F,x,0,2),y,0,pi),z,0,pi), vpa(I) % triple integral
7.2 · Series Approximation of Functions
181 7
where the result obtained is −(e−π −1)(γ + ln(4π) − Ei(−4π)), where γ is the Euler
2

z
constant, Ei(z) is the integral Ei(z) = e−t t−1 dt. From the analytical solution, the
−∞
numerical solution can be found as 3.1080794020854127228346146476714. 

7.2 Series Approximation of Functions


Series problems are the earliest explored problem in the entire calculus. Several series-
related functions are provided in MATLAB, and they are listed in . Table 7.2. In this
section, series problems and solutions are presented, including Taylor and Fourier
series expansion approximations to given functions and convergence test of infinite
series. Series sum and sequence product problems are also discussed in this section.

7.2.1 Taylor Series


Taylor series is a representation of a polynomial function to approximate any given
functions. Here, the simple mathematical description of Taylor series is given first,
then concentrations are made on how to use MATLAB to find Taylor series, and
assess the approximation quality.
Expand the function around x = a point, the kth-order Taylor series is
 
f (x) = b1 + b2 (x − a) + b3 (x − a)2 + · · · + bk (x − a)k−1 + O (x − a)k , (7.16)
 
where k indicates the error O (x − a)k is of kth order, and the coefficients bi can be
written as

. Table 7.2 Commonly used series functions

Operations Syntaxes and descriptions

Taylor series F = taylor(f , x, a,'Order',n), finds the nth-order Taylor series


expansion F of function f about x = a point

Fourier series F = fseries(f , x, n, a, b), author’s MATLAB solver, nth-order Fourier


series expansion F of the function f defined in the interval [a, b]

Convergency test key = isconverge(f , k), author’s MATLAB solver, test convergency of
infinite series

kn

Series sum F = synsum(f , k, k0 , kn ), computes F = fk , where k0 and kn can be
k=k0
set to inf

kn
Sequence product F = symprod(f , k, k0 , kn ), computes F = fk , where k0 and kn can be
k=k0
set to inf
182 Chapter 7 · Calculus and Integral Transforms

1 di−1
bi = lim f (x), i = 1, 2, 3, . . . . (7.17)
(i − 1)! x→a dxi−1
In Symbolic Math Toolbox, function taylor() finds the Taylor series expansion.
F =taylor(f ,x,a,'Order',k), % kth-order Taylor series about x = a point
where f is a symbolic expression for the given function, and x is the independent
variable. If the function has only one variable, it can be omitted. The order is denoted
by k, with default 6. If a is not given, Taylor series about x = 0 is obtained. Examples
are given next to show Taylor expansion problems.

 Example 7.24
Consider the function in Example 7.12, f (x) = sin x/(x2 + 4x + 3). Find the nineth-order
Taylor series expansion, and observe the fitting quality.
Solutions The function can be entered into MATLAB, and then function taylor() can be
called for the function.
7 >> syms x; f(x)=sin(x)/(x^2+4*x+3);
y=taylor(f,x,'Order',9) % Taylor series expansion
The nineth-order Taylor series expansion can be found

386459 8 515273 7 3067 6 4087 5 34 4 23 3 4 1


y(x) ≈ − x + x − x + x − x + x − x2 + x.
918540 1224720 7290 9720 81 54 9 3

In traditional calculus textbooks, Taylor series is in fact infinite series, with convergent
interval x ∈ (−∞, ∞). In real applications, infinite series cannot be constructed. Finite-
order Taylor series are usually adopted to approximate the original functions. Therefore,
it is inevitable for the user to answer the important questions. If a finite-order Taylor
series is used to approximate a given function, what is the fitting results? In which interval
the series can be used? To get the approximation in a desired interval, how to select the
fitting order? Since the traditional calculus textbooks do not have graphical support from
computers,  these questions cannot be answered properly. The only answer is the error
bound O (x − a)k . With MATLAB, all these questions can be answered immediately. The
following commands draw together the original function curve and nineth-order Taylor
series curve over the interval (−1, 1), as shown in . Fig. 7.8. The two curves obtained have
significant differences when x is large. The user may use the zooming facilities on the curve
and see which interval the fitting is satisfactory.
>> fplot([f y],[-1,1]) % function comparisons
After comparing the fitting, it can be seen that the fitting interval is reduced to [−0.6, 0.6].
It can be seen that the fitting is acceptable in this interval. 

 Example 7.25
Carry out Taylor series fitting to the sinusoidal function y = sin x, and observe the fitting
intervals under different orders.
Solutions Based on the problem, the following commands can be used. A loop can be used
to try different orders. The fitting is obtained as shown in . Fig. 7.9.
7.2 · Series Approximation of Functions
183 7

-0.5

ies
ser
-1
lor
Tay

ction
-1.5 al fun
origin

-2

-2.5
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1

. Fig. 7.8 Taylor series approximation in the (−0.6, 0.6) interval

>> syms x; y=sin(x); fplot(y,[-2*pi,2*pi]), hold on % original function


for n=[6:2:16] % try different orders
p=taylor(y,x,'Order',n), fplot(p,[-2*pi,2*pi]) % Taylor series
end, hold off
If the fitting order is low, the fitting interval is small. Increasing the fitting order, the
fitting interval is significantly increased. For this example, if we select n = 16, the fitting is
satisfactory in the interval (−2π, 2π), where the sixteenth-order Taylor series is

x3 x5 x7 x9 x11 x13 x15


sin x ≈ x − + − + − + − .
6 120 5040 362880 39916800 6227020800 1307674368000

1
=8
0.8
0.6
0.4
0.2
0
= 14

= 10
-0.2
-0.4
-0.6
-0.8
=6
-1
-6 -4 -2 0 2 4 6

. Fig. 7.9 Taylor series approximation


184 Chapter 7 · Calculus and Integral Transforms

7.2.2 Fourier Series


Before discussing Fourier series approximation to any functions, let us have a look
Fourier series approximation to the function f (x) defined in the symmetrical interval
x ∈ (−L, L).
For the periodic function f (x), where x ∈ [−L, L], it is found that the period
is T = 2L. Outside the interval, periodic extensions are defined, such that f (x) =
f (kT + x), where k is an arbitrary integer. Fourier series can be written in the form.

a0   nπ 


F (x) = + an cos x + bn sin x , (7.18)
2 L L
n=1

where ⎧ 

⎪ 1 L nπx

⎨ an = f (x) cos dx, n = 0, 1, 2, . . .
L −L L
⎪  (7.19)
7 ⎪

⎩ bn =
1 L
f (x) sin
nπx
dx, n = 1, 2, 3, . . . ,
L −L L
where an and bn are referred to as Fourier coefficients.
Similar to Taylor series approximation, finite Fourier series approximation for
given functions is usually studied. For instance, preserve p sets of coefficients, (7.18)
can be rewritten as

a0   nπ 
p

F (x) ≈ + an cos x + bn sin x . (7.20)
2 L L
n=1

If arbitrary interval x ∈ (a, b) is considered, the period can be worked out, where
L = (b − a)/2. Introducing x̂, such that x = x̂ + L + a, then function f (x̂) can
be mapped into the interval (−L, L). Carrying out Fourier series expansion, then
substituting x̂ = x − L − a, the function F (x) obtained can be mapped back into the
function of x.
There are not any existing MATLAB functions for finding Fourier coefficients
and Fourier series. It is not difficult to write the following MATLAB function, based
on the above formulas.
function [F,A,B]=fseries(f,x,p,a,b)
arguments, f, x, p(1,1){mustBePositive, mustBeInteger}=6
a(1,1) double=-pi, b(1,1) double {mustBeGreaterThan(b,a)}=pi
end
syms n; L=(b-a)/2; f=subs(f,x,x+L+a);
a0=int(f,x,-L,L)/L/2; A(n)=int(f*cos(n*pi*x/L),x,-L,L)/L;
B(n)=int(f*sin(n*pi*x/L),x,-L,L)/L;
fn=A*cos(n*pi*x/L)+B*sin(n*pi*x/L); % compute general term
if nargout>1, A1=[a0,A(1:p)]; B1=B(1:p); end
F=a0+symsum(fn,n,1,p); F=subs(F,x,x-L-a);
end
7.2 · Series Approximation of Functions
185 7
The syntax of the function is [F , A,B]=fseries(f ,x,p,a,b), where f is the original
function, x is an independent variable, p the preserved terms, with default of 6. The
arguments a and b describe the interval of x, with default [−π, π]. The returned A
and B are Fourier coefficient vectors, F is the Fourier series expression.

 Example 7.26
Find the Fourier series of the function y = x(x − π)(x − 2π), x ∈ (0, 2π).
Solutions The Fourier series can be naturally obtained with the following statements:
>> syms x; f=x*(x-pi)*(x-2*pi); % describe the original function
[F,A,B]=fseries(f,x,12,0,2*pi); F % find the Fourier series
and the first 12 pairs of terms of Fourier series are

3 4 3 12 1 12
F (x) = 12 sin x+ sin 2x+ sin 3x+ sin 4x+ sin 5x+ sin 6x+ sin 7x
2 9 16 125 18 343
3 4 3 12 1
+ sin 8x + sin 9x + sin 10x + sin 11x + sin 12x,
128 243 250 1331 144

which can be summarized as



 12
F (x) = sin nx.
n3
n=1
The following command draws together the first 12 pairs of terms Fourier series and the
original function curves are obtained (omitted) and it can be seen that they are almost
identical, where the difference cannot be observed.
>> fplot([f,F],[0,2*pi]) % the results are almost identical sine curves


7.2.3 Series Sums


The mathematical form of a series is


kn
S = ak0 + ak0 +1 + · · · + akn = ak , (7.21)
k=k0

where ak is the general term in the series, k in the independent variable, k0 and kn are
the first and last terms of the series.
Function symsum() provided in MATLAB evaluates finite or infinite sums
directly, with the syntax S=symsum(ak ,k,k0 ,kn ), where the first term can be −inf,
and the last term can be inf, but not taken infinite terms at the same time. If there is
only one variable in the ak expression, k can be omitted.
186 Chapter 7 · Calculus and Integral Transforms

 Example 7.27
Compute the sum of finite series.


63
S = 20 + 21 + 22 + 23 + 24 + · · · + 262 + 263 = 2i .
i=0

Solutions Function symsum() can be used directly, and the sum is 18446744073709551615.
>> syms k; symsum(2^k,0,63) % or use sum(sym(2).^[0:63])


 Example 7.28
Find the infinite sum of the following series:

1 1 1 1 1 1 1 1
7 S=
2

3
+
4
+
9
+
8
− + +
27 16 81
+ ··· .

Solutions The first step to evaluate series sum is to find an appropriate general term. If the
term cannot be specified properly, the sum cannot be found. By observing the series, it is
not hard to find that, if we rearrange the terms here in pairs, then
       
1 1 1 1 1 1 1 1
S= − + + + − + + + ··· .
2 3 4 9 8 27 16 81

The problem is then made clear, and the general term is

1 (−1)n
an = n + , n = 1, 2, . . . .
2 3n

With the general term expression, the following commands can be used to describe it and
find the infinite sum of S = 3/4. Since n is the only variable in the expression, it can be
omitted.
>> syms n; a=1/2^n+(-1)^n/3^n; S=symsum(a,n,1,inf)


 Example 7.29
Find the finite and infinite sum of the following series:

1 1 1 1 1 1
S= √ −√ +√ −√ +√ −√ + ··· .
2−1 2+1 3−1 3+1 4−1 4+1

Solutions Again the series can be rewritten in pairs such that


     
1 1 1 1 1 1
S= √ −√ + √ −√ + √ −√ + ··· .
2−1 2+1 3−1 3+1 4−1 4+1
7.2 · Series Approximation of Functions
187 7
The general term can then be written as

1 1
an = √ −√ , n = 1, 2, . . . .
n+1−1 n+1+1

The general term expression sometimes is not unique. It can be alternatively written as

1 1
bn = √ −√ , n = 2, 3, . . . .
n−1 n+1

It can be seen that the general term is important, and the first, last terms are equally
important. With the general term, the following commands can be tried to find the infinite
sum. Unfortunately, no analytical solution can be found.
>> syms n;
S1=symsum(1/(sqrt(n+1)-1)-1/(sqrt(n+1)+1),n,1,inf)
S2=symsum(1/(sqrt(n)-1)-1/(sqrt(n)+1),n,2,inf)
How to tackle the problem when there are no analytical solutions found? Of course we can
use the numerical method, since it is a numeric series. The first n terms can be found for
different values of n and observe the trend. For instance, the following commands can be
tried and the results are shown in . Table 7.3. It can be seen that the sum is increasing, and
there is no sign to stop increasing. Therefore it is quite likely that the series is divergent.
>> N0=[10,100,1000,10000,100000,1000000 10000000]; T=[];
for N=N0 % select number of terms and find the sum
n=1:N; y=sum(1./(sqrt(n+1)-1)-1./(sqrt(n+1)+1));
T=[T [N; y]]; % store the results to generate table
end
It can be seen that sometimes it is necessary to examine the convergency of the series.
Convergency test methods will be given later for infinite series. 

In fact, functional series can also be evaluated with symsum() function. The general
term can also be used in the symsum() function, with no extra burden. It is noted that,
sometimes the convergent condition can also be found with symsum() function.

 Example 7.30

 1
Find the infinite sum J = 2 .
(2n + 1)(2x + 1)2n+1
n=0

Solutions Since in the general term, the variable x is contained, therefore numerical method
cannot be used to find the series sum. Symbolic method is the only choice. The following

. Table 7.3 Finite sums in different terms

Number of terms 10 100 1000 10000 100000 1000000 10000000

Finite sum 5.8579 10.375 14.971 19.575 24.18 28.785 33.391


188 Chapter 7 · Calculus and Integral Transforms

commands can be issued, and the simplest result found is 2 atanh(1/(2x + 1)). Meanwhile
the convergent condition is provided, as |2x + 1| > 1.
>> syms n x;
s1=symsum(2/((2*n+1)*(2*x+1)^(2*n+1)),n,0,inf); simplify(s1)


 Example 7.31
Find the infinite sum
     
1 π 2 2π n−1 (n − 1)π
S = 1 + 2 sin 2 + 1 + 2 sin 2 + · · · + 1 + 2 sin + ··· .
n n n n n n2

Solutions Since the numerator in the general term is changing from 1 to n − 1, it is hard
to find the solution to the infinite series problem with symsum() only. A slightly different
idea should be posed. Let n is a given integer, the finite sum can be found with symsum()
7 function. Then let n → ∞, so that the problem is converted into a limit problem.
!      "
1 π 2 2π n−1 (n − 1)π
S = lim 1+ 2 sin 2 + 1 + 2 sin 2 + · · · + 1 + 2 sin .
n→∞ n n n n n n2

From the above problem, the general term is crucial. It can be seen that n2 term appears on
all the denominators, it is retained in the denominators in the general term. The numerator
terms are changing so it can be denoted as k. Therefore the general term can be written as
   
k kπ
ak = 1 + 2 sin , k = 1, 2, . . . , n − 1.
n n2

The following commands can be used directly to find the infinite sum, where S = π/2.
>> syms n k;
S=simplify(limit(symsum((1+k/n^2)*sin(k*pi/n^2),k,1,n-1),n,inf))


7.2.4 Product of Sequences


The product of the sequence can be expressed as

kn
P = ak0 ak0 +1 · · · akn = ak . (7.22)
k=k0

Function symprod() provided in the Symbolic Math Toolbox finds the product
of the sequence with P=symprod(ak ,k,k0 ,kn ).
7.2 · Series Approximation of Functions
189 7

 Example 7.32
n  
1
Find the finite and infinite product P = 1+ 3 .
k
k=1

Solutions The following MATLAB commands can be used to find the finite and infinite
products of the given sequence.
>> syms k n; p1=symprod(1+1/k^3,k,1,n); p1=simplify(p1) % finite product
p2=symprod(1+1/k^3,k,1,inf); p2=simplify(p2), vpa(p2) % infinite product
The results are
 √   √   √ 
(n + 1)! −1 + 3 i 1 − 3i 1 + 3i
p1 = − sin π  n+  n+ ,
π(n!)3 2 2 2

√ 
p2 = cos 3πj/2 /π ≈ 2.4281897920988703287360414361791.


 Example 7.33
Find the infinite sum.

1 1×3 1×3×5 1×3×5×7 1×3×5×7×9


S =1− + − + − + ··· .
2 2 × 4 × 6 2 × 4 × 6 2 × 4 × 6 × 8 2 × 4 × 6 × 8 × 10

Solutions For the time being, just do not consider the first term in S. The remaining problem
is the series sum problem, with the general term

n
2k − 1
an = (−1)n , n = 1, 2, . . . , ∞.
2k
k=1

while the general term is in fact a sequence product problem. Function symprod() can be
used to express the general term. Then function symsum() can be called to find the sum,
and finally the√first term of 1 can be added back. With the following MATLAB commands,
the sum S = 2/2 can be found.
>> syms k n
S=1+symsum((-1)^n*symprod((2*k-1)/(2*k),k,1,n),n,1,inf)


 Example 7.34
∞ 
x  −x/n
Find the product of the functional sequence P = 1+ e .
n
n=1

Solutions The following commands can be used to solve the problem:


>> syms n x; P=symprod((1+x/n)*exp(-x/n),n,1,inf) % solve directly
and a piecewise function is obtained
190 Chapter 7 · Calculus and Integral Transforms

#
0, x is a negative integer
P=
e−γ x / (x + 1), otherwise, where γ is an Euler constant,

where (·) is a Gamma function, which is also a special function, and can be evaluated
directly with MATLAB function gamma(). 

7.2.5 Convergence of Infinite Series


Sometimes, symsum() function or other tools may fail to get closed-form solution to
the infinite series. Therefore it is necessary to test the convergency of the series. This
has been demonstrated in Example 7.29. In this section, the convergency test methods
for infinite series are explored.
For a given series, if the sum S tends to a specific limited value when n → ∞,
the series is convergent, otherwise it is divergent. There are no available MATLAB
functions to test convergency. Several mathematical methods are listed, from which
7 a universal solver is written for the problem.
The four test criteria can be used to test the convergency of infinite series with
positive terms.
(1) Necessary condition. The necessary condition for the convergence of infinite
series is that lim an = 0. If the condition is not satisfied, the series is divergent.
n→∞
(2) D’Alembert test. Compute L = lim an+1 /an . If L < 1, the series is convergent;
n→∞
if L > 1, it is divergent; if L = 1, other test methods should be tried, for instance,
Criterion (3) next.
 
(3) Raabe test. If in Criterion (2), L = 1, compute R = lim n an /an+1 − 1 . If
n→∞
R > 1, the series is convergent; if R < 1, it is divergent; if R = 1, try the criterion next.
(4) Bertrand test [5]. If Criterion (3) cannot assess convergency, compute B.
 
an
B = lim ln n n −n−1 . (7.23)
n→∞ an+1

If B > 1, the series is convergent; if B < 1, the series is divergent; if B = 1, the


convergency cannot be assessed.
With the progressive criteria, the following universal MATLAB function can be
written to test the convergency of the positive series:
function key=isconverge(f,n)
if limit(f,n,inf)~=0, key=0; return; end % necessary condition
L=limit(subs(f,n,n+1)/f,n,inf); % D'Alembert test
if L>1, key=0; elseif L<1, key=1;
else % if L = 1, Raabe test
R=limit(n*(f/subs(f,n,n+1)-1),n,inf);
if R>1, key=1; elseif R<1, key=0;
else % if R = 1, Bertrand test
B=limit(log(n)*(n*f/subs(f,n,n+1)-n-1),n,inf);
if B>1, key=1; elseif B<1, key=0; else, key=-1;
end, end, end, end
7.3 · Numerical Calculus Solutions
191 7

 Example 7.35
Test convergency for the following infinite series:


 ∞
2n 2n
S= = .
1 × 3 × 5 × · · · × (2n − 1) $
n
n=1 n=1 (2k − 1)
k=1

Solutions For the positive series, the following commands can be issued, and the result is
key=1, indicating that the series is convergent.
>> syms n k; a=2^n/symprod(2*k-1,k,1,n) % input the general term
key=isconverge(a,n) % judge the convergency


 Example 7.36
Test the convergency of the series in Example 7.29.
Solutions The general term in Example 7.29 is

1 1
an = √ −√ , n = 1, 2, . . . .
n+1−1 n+1+1

With the general term of the positive series, the convergency can be tested directly. The
result is key=0, indicating the series is divergent, which is the same as the one observed in
Example 7.29.
>> syms n; a(n)=1/(sqrt(n+1)-1)+1/(sqrt(n+1)+1);
key=isconverge(a,n) % test the convergency


7.3 Numerical Calculus Solutions


If the mathematical expression of the function is known, diff() function finds ana-
lytical solutions of the derivatives of different orders. The results can be found easily.
Even to find hundredth-order derivatives, the results can be found in a few seconds.
It should be noted that the condition to get the afore-mentioned analytical solution
is that the function expression is given.
If the mathematical form of the function is unknown, we only have experimen-
tal data, sometimes we may also need to get the derivatives or integrals. Therefore
the methods discussed earlier cannot be used. Numerical methods must be adopted.
In this section, numerical differentiation and integrals are considered by the use of
MATLAB.
192 Chapter 7 · Calculus and Integral Transforms

7.3.1 Numerical Differentiation


If a set of samples y(k) are observed, briefly denoted as yk , k = 1, 2, . . . , m, with
a fixed step size of h, how to find the first-order derivative from the information
provided in vector y? Many people may compute derivatives using simple difference
formulas. For instance, the forward or backward difference formulas.
The forward and backward difference formulas for numerical differentiation are
yk yk+1 − yk
yk ≈ = , k = 1, 2, . . . , m − 1, (7.24)
h h
yk yk − yk−1
yk ≈ = , k = 2, 3, . . . , m. (7.25)
h h
If equal-space time vector with increment h is used to generate y vector, the fol-
lowing command finds approximately the first-order derivative y1 =diff( y,h). It is
a pity that the precision of the two algorithms is all O(h)-level. When h is large, the
7 error in the result is also large. In simple words, O(h) probably means that if h is
selected as 0.1, the error of the results is also at 0.1-level. Therefore, higher preci-
sion algorithms should be adopted in real applications. For example, O(h2 ) precision
difference algorithm can be expressed as

yk+1 − yk−1
yk = , k = 2, 3, . . . , m − 1. (7.26)
2h

It can be seen from the formulas that, in the forward formula, the first term in
the derivative is y1 , but the last term is ym−1
  . Therefore the differentiations at
, not ym
later points are sacrificed. While in backward algorithm, the term y1 is not evaluated.
It is sacrificed. The more accurate central difference algorithm sacrificed both at y1
and ym  . In many applications, it is more important to preserve the y term. Thus, the
1
high-precision forward difference algorithms are recommended later.
In Reference [2], central difference algorithm and MATLAB implementation of
precision O(h4 ) is provided. To pursued forward numerical differentiation with pre-
cision O(hp ), the solver num_diff() in Reference [3] can be adopted. The syntax of
the function is [z,t]=num_diff( y, h, n, p), where z returns the nth-order numerical
differentiation, t is the relative time vector. The actual time vector should be t = t1 + t.
The algorithms and listing of the function are not provided in this book. The inter-
ested readers may refer to Reference [3], or the source code provided in the toolbox
of this book.

 Example 7.37
In x ∈ (1.5, 3.5) and the step size is selected as h = 0.02. Generate a set of samples from
function
1 1 1 2x − 1
f (x) = ln(x + 1) − ln(x2 − x + 1) + √ arctan √ .
2 4 3 3
Find the first- to seventh-order numerical derivatives of the function, and find the maximum
errors.
Solutions The samples can be generated first. Selecting the precision p, the following state-
ments find numerical differentiation of various orders. Since the mathematical forms of
7.3 · Numerical Calculus Solutions
193 7
the function are known, theoretical values of the derivatives are also found, from which
the errors can be assessed, as shown in . Table 7.4. It can be seen that the seventh-order
derivative is far away from the theoretical values, and cannot be adopted. Larger values
of p can be used and the sixth-order derivative is compared in . Fig. 7.10. It can be seen
that very small discrepancies are observed in the results. If seventh-order derivatives are
expected, we may consider increasing the value of p.

>> syms x;
f(x)=log(1+x)/2-log(x^2-x+1)/4+atan((2*x-1)/sqrt(3))/sqrt(3);
h=0.02; x0=1.5:h:3.5; y0=double(f(x0)); % generate samples
for n=1:7 % try different orders of the algorithm
[z,t]=num_diff(y0,h,n,6); t=1.5+t; % numerical differentiation
f1=diff(f,n); y1=double(f1(t)); norm(z-y1), max(abs(z-y1))
end
[z,t]=num_diff(y0,h,6,6); t=1.5+t; % compute again 6th-order one
f1=diff(f,6); y1=double(f1(t)); plot(t,y1,t,z,'--')


7.3.2 Numerical Integrals


Numerical integral problems can be classified into two categories. One is that the
integrand is not known, only samples are given. How to find the integrals from the

. Table 7.4 Errors in numerical derivatives under different orders

Orders p 1 2 3 4 5 6 7

Error norm 9.47 × 10−10 2.94 × 10−8 4.45 × 10−7 6.58 × 10−6 0.0011 0.216 29.36

Maximum error 4.69 × 10−10 1.28 × 10−8 1.62 × 10−7 1.93 × 10−6 3.27 × 10−4 0.047 7.32

7
6
5
4
3
2
1
0
-1
-2
-3
1.6 1.8 2 2.2 2.4 2.6 2.8 3 3.2

. Fig. 7.10 Sixth-order numerical differentiation (solid line: theoretical, dash: numerical result)
194 Chapter 7 · Calculus and Integral Transforms

given samples? Another one is that although the integrand is known, the analytical
solution is not available, how to find the numerical integrals? Various numerical
integral problems are presented in this section.

1. Numerical Integral from Samples


If the samples are given in vectors t and y, while the integrand is unknown, trapezoidal
method evaluates the numerical integral, with I=trapz(t,y). The advantage is that t
can be unevenly spaced vector. The disadvantage is that the precision is O(h), which
is usually rather low. A high-precision solver is provided in Reference [3], with the
syntax S=num_integral(y,h), where y stores the samples of the function with equally
spaced x vector, and h is the step size. The result S is the approximate definite integral.
Improper integral problem cannot be solved with such a solver.
The algorithm selected is the seven-point formular [3] with maximum accuracy
of O(h8 ). The samples can be grouped with seven points each. Therefore it is recom-
mended that the length of y vector is 6k + 1, with k integers.

7
 Example 7.38
 3π/2
Compute numerical integral cos 15x dx.
0
Solutions The theoretical result is 1/15. It can be seen that the integrand is oscillatory. In the
current interval, there are more than 10 cycles. If the trapezoidal method is used, the step
size should be selected extremely small, to ensure high precision. For instance, 108 points
should be selected, h = 4.71 × 10−8 . The error thus obtained is 3.1503 × 10−15 , with total
time elapse of 0.919 s. If 10−16 -level of precision is required, even more points should be
selected.
>> x=linspace(0,3*pi/2,1e8); y=cos(15*x);
tic, I=trapz(x,y), toc, format long; abs(I-1/15)
If num_integral() function is adopted, about 1600 samples are sufficient. More specifi-
cally, N = 1603 to ensure 6k + 1. The step size is h = 0.0029, time elapse of 0.0016 s, and
the error is 7.6328 × 10−16 . It can be seen that the efficiency of the numerical method is
much higher than that of the trapz() function provided in MATLAB.
>> x=linspace(0,3*pi/2,1603); y=cos(15*x); h=x(2)-x(1)
tic, I=num_integral(y,h); toc, abs(I-1/15)


2. Numerical Definite Integral Computing


The adaptive step-size numerical integral function integral() is provided in MAT-
LAB, with the syntax I=integral(f,a,b,option pairs), where f is used to describe
the integrand. It can be an anonymous function or a function file like Fun.m, where
@Fun or 'Fun' is used to describe the integrand. The leading sentence is function
y=Fun(x). Parameters a and b are used to describe the lower and upper integral
bounds. Option pairs can be used to set control options, as shown in . Table 7.5.
Examples are used to illustrate numerical integral solutions.
7.3 · Numerical Calculus Solutions
195 7

. Table 7.5 Numerical integral options

Options Descriptions

'RelTol' Relative error tolerance, which specifies the accuracy. It can be set to eps
for the most accurate precisions

'AbsTol' Absolute error tolerance, also set it to eps

'ArrayValued' Vector parameter identifier. If the integrand contains parameters other


than the independent variables, it can be set to logic 1

'waypoint' Key points setting, they set deliberately discontinuous or singularities.


When addressing improper integrals, better methods will be introduced

 Example 7.39
 3π/2
Consider the definite integral problem in Example 7.38, I = cos 15x dx. If the upper
0
bound is changed from 3π/2 to 1000, solve the integral problem with integral() function.
Solutions From the method demonstrated in Example 7.38, it can be seen that the step
size must be selected small and satisfy the 6k + 1 condition, high-precision solution can
be found. Variable step numerical integral can be used. Anonymous function can be used
to represent the integrand, then call the function integral(), to get the solution S =
0.059561910527770. The error is 1.3518 × 10−12 , and time elapse is only 0.023 s.
>> f=@(x)cos(15*x); % dot operation in anonymous function
tic, S=integral(f,0,1000,'RelTol',eps), toc
syms x, I=int(cos(15*x),0,1000); double(S-I)


 Example 7.40
Solve the integral problem for the following piecewise integrand [6].

 4 %
2
I= f (x)dx, where f (x) = ex ,  0≤x≤2
0 80/ 4 − sin(16πx) , 2 < x ≤ 4.

Solutions The following commands can be used to draw the piecewise function. At the
break point, a small offset  is introduced to draw the filled plot, as shown in . Fig. 7.11.
It can be seen that there is a jump at x = 2.
>> x=[0:0.01:2, 2+eps:0.01:4,4];
y=exp(x.^2).*(x<=2)+80./(4-sin(16*pi*x)).*(x>2);
y(end)=0; x=[0,x]; y=[0,y]; fill(x,y,'g')
% filled plot of the integrand
196 Chapter 7 · Calculus and Integral Transforms

60

50

40

30

20

10

0
0 0.5 1 1.5 2 2.5 3 3.5 4

. Fig. 7.11 The filled plot of the integrand

7 Relational expression is used to express the integrand. Then function integral() is called
to compute the definite integral, with I1 = 57.764450125048505. Compared with the ana-
lytical solution, the error 7.6396 × 10−15 can be witnessed.
>> f=@(x)exp(x.^2).*(x<=2)+80./(4-sin(16*pi*x)).*(x>2);
I=integral(f,0,4,'RelTol',eps) % compute numerical integral
syms x; f=piecewise(x<=2,exp(x^2), x>2,80/(4-sin(16*pi*x)));
double(int(f,x,0,4)-I) % compute the error


Even though analytical solutions for some definite integrals cannot be found,
vpa() function can be called to the result such that high-precision numerical solutions
can be found. In certain cases, this method cannot be used. In the next example, the
definite integral problem with parameters is demonstrated.

 Example 7.41
 ∞
e−αx sin(α 2 x)dx, and draw the relationship curve
2
Solve the integral problem I (α) =
0
of I (α) versus α, where the range of the parameter is α ∈ (0, 4).
Solutions Since there is a parameter a, functions int() and vpa() cannot be used to solve
the problem. In this case, a series of sample values of α should be considered. Vectorized
function integral problem can then be solved. Since integral() function supports param-
eter vector with ArrayValue option, the problem can be solved without loop structure.
The following commands solve the problem, and the curve of the integral is shown in
. Fig. 7.12.
>> a=0:0.1:4; f=@(x)exp(-a*x.^2).*sin(a.^2*x); % with parameter vector
I=integral(f,0,inf,'RelTol',1e-20,'ArrayValued',true);
plot(a,I) % draw the curve of integral versus parameters

7.3 · Numerical Calculus Solutions
197 7

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5 4

. Fig. 7.12 The relationship between integral I (α) and parameter α

3. Numerical Double Integrals


The standard form of double integral is
 xM  yM (x)
I= f (x, y)dydx. (7.27)
xm ym (x)

With MATLAB function integral2(), the double integral can be solved with
the syntax I =integral2(f ,xm ,xM , ym ,yM ,option pairs), where option pairs are
close to those in integral() function, but the 'ArrayValued' option is not sup-
ported. Besides, ym and yM can be function handles for the inner integral bounds.
Note that, with integral2(), make sure the integration order is y-then-x.

 Example 7.42
Compute the double integral

 1  √1−x2 /2
e−x /2 sin(x2 + y)dydx.
2
J= √
−1/2 − 1−x2 /2

Solutions The integration order here is y-then-x, and it is the same as the ones in the
standard form. The following commands can be used to find the integral, and the solution
is I = 0.411929546173382, with an error of 2.9132 × 10−12 .
>> fh=@(x)sqrt(1-x.^2/2); fl=@(x)-sqrt(1-x.^2/2); % inner loop bounds
f=@(x,y)exp(-x.^2/2).*sin(x.^2+y); % input the integrand
I=integral2(f,-1/2,1,fl,fh,'RelTol',eps) % numerical integral
syms x y, xm=-sqrt(1-x^2/2); xM=sqrt(1-x^2/2); % analytical solution
i1=int(exp(-x^2/2)*sin(x^2+y),y,xm,xM); % warning in the commands
I1=int(i1,x,-1/2,1), double(I1-I) % error measurement

198 Chapter 7 · Calculus and Integral Transforms

The x-then-y integration order below is not supported directly in MATLAB.


 yM  xM (y)
I= f (x, y) dxdy. (7.28)
ym xm (y)

A method to convert it into standard form in (7.27) should be introduced, then


call integral2() to solve the problem. Let x̂ = y and ŷ = x, then (7.28) can be
equivalently transformed to
 x̂M  ŷM (x̂)
I= f (ŷ, x̂) dŷdx̂. (7.29)
x̂m ŷm (x̂)

Therefore, the simplest way is to alter the order in the arguments, and use
f =@(y,x) to describe the integrand. The other parts in the solution process can be kept
unchanged. An example is given next to demonstrate the double integral computing
problem.
7
 Example 7.43
 1  √1−y2
e−x /2 sinh(x2 + y) dxdy.
2
Compute double integral J = √
−1 − 1−y2
Solutions The problem does not have an analytical solution. With symbolic operations,
high-precision numerical solution can be found I =0.70412133490335689947800312022517,
with time elapse of 123.57 s.
>> syms x y, tic % declare symbolic variable and start timing
i1=int(exp(-x^2/2)*sinh(x^2+y),x,-sqrt(1-y^2),sqrt(1-y^2));
I=int(i1,y,-1,1), vpa(I), toc % find analytical and numerical solution
It can be seen that the integration order is x-then-y. There is no need to change the integrand.
Just alter the input arguments in the anonymous function. With the following statements,
the double integral can be found 0.704121334903362, and the time elapse is just 0.0195 s.
It can be seen that the efficiency of numerical solution is high.
>> tic, f=@(y,x)exp(-x.^2/2).*sinh(x.^2+y); % swap the order of the variables
fh=@(y)sqrt(1-y.^2); fl=@(y)-sqrt(1-y.^2);
I=integral2(f,-1,1,fl,fh,'RelTol',eps), toc


4. Numerical Triple Integrals


The standard triple integral is
 xM  yM (x)  zM (x,y)
I= f (x, y, z)dzdydx. (7.30)
xm ym (x) zm (x,y)

Pay attention to the integration order. The triple integral in standard form can be
solved with function integral3(), with the syntax
I =integral3(f ,xm ,xM ,ym ,yM ,zm ,zM , option pairs)
7.3 · Numerical Calculus Solutions
199 7
where f is the handle of the integrand, which can be M-functions or anonymous
functions. The selections of option pairs are the same as the ones in integral2()
function. The arguments ym , yM , zm and zM may also be function handles. If the
integral orders are different, the processing method in integral2() can be consulted,
then the numerical solution can be found.

 Example 7.44
Compute the triple integral with functional bounds

 1  √1−x2  √2−x2 −y2


z2 e−(x+y ) dzdydx.
2
I= √
0 0 x2 +y2

Solutions The integration order is the same as the one in the standard form. There-
fore the problem can be solved directly, and the numerical solution obtained is I =
0.237902335517189, with time elapse of 0.184 s.
>> tic, f=@(x,y,z)z.^2.*exp(-(x+y.^2)); % integrand
yM=@(x)sqrt(1-x.^2); zm=@(x,y)sqrt(x.^2+y.^2); % integral bounds
zM=@(x,y)sqrt(2-x.^2-y.^2);
I=integral3(f,0,1,0,yM,zm,zM,'RelTol',eps), toc % numerical triple integral
For the analytical solution, the following commands can be tried. After 40.87 s of waiting,
it is prompted that there is no solution to the problem.
>> syms x y z, zm=sqrt(x^2+y^2); zM=sqrt(2-x^2-y^2); tic % analytical solution
I=int(int(int(z^2*exp(-(x+y^2)),z,zm,zM),y,0,sqrt(1-x^2)),x,0,1)
vpa(I), toc


 Example 7.45
Compute the triple integral problem with functional bounds.

 1  √1−z2  √2−y2 −z2


z2 e−(x+y ) dxdydz.
2
I= √
0 0 y2 +z2

Solutions The integrand is the same as the one in Example 7.44, but the integration order
is different. Analytical solution method again prompts that there is no analytical solution.
Numerical method can be considered.
Compare to the standard form in (7.30), it can be seen that the entry arguments of the
integrand function can be written as (z, y, x). The following commands in Example 7.44
solve the problem (the variables in the inner integration bounds are changed. In fact there
is really no need to change them, the commands in Example 7.44 can be used directly). The
result obtained is I = 0.024204591786321, with time elapse of 0.071 s.
>> tic, f=@(z,y,x)z.^2.*exp(-(x+y.^2)); % modify the entry arguments
yM=@(z)sqrt(1-z.^2); xm=@(y,z)sqrt(y.^2+z.^2); % integral bounds
xM=@(y,z)sqrt(2-y.^2-z.^2);
I=integral3(f,0,1,0,yM,xm,xM,'RelTol',eps); toc % triple integral
200 Chapter 7 · Calculus and Integral Transforms

7.4 Introduction to Integral Transforms


Integral transform technique can be used to map problems from one domain into
another. For instance, Laplace transform maps time-domain function into complex
domain, such that linear differential equations in time domain can be mapped into
polynomial equations in complex domain one. Therefore, some properties of differ-
ential equations, such as stability and analytical equation solutions, can be easily
tackled in complex domain. The transform like this establishes the foundation of
classical control theory. In this section, the commonly used Laplace, Fourier and z
transforms are presented, with concentrations on how to use computers to directly
solve transform and inverse transform problems. When there are no analytical solu-
tions in Laplace and inverse Laplace transforms, the concept and solution tools of
numerical Laplace transform are introduced.
7
7.4.1 Laplace Transform
Laplace transform of a time-domain function f (t) is defined as
 ∞
L[f (t)] = f (t)e−st dt = F (s), (7.31)
0

where L[f (t)] is the simple notation of Laplace transform.


When Laplace transform is introduced, the time-domain function f (t) can be
mapped into an s domain signal F (s). Normally s can be understood as a complex
variable.
If the Laplace transform function F (s) is given, the inverse Laplace transform is
 σ +j∞
1
f (t) = L−1 [F (s)] = F (s)est ds, (7.32)
2πj σ −j∞

where σ is larger than any singularities of F (s).


Although powerful integral tools are provided in MATLAB, it is rather very
complicated to evaluate Laplace transform and its inverse from their definitions. The
solvers laplace() and ilaplace() are recommended to solve Laplace and inverse
Laplace transform problems. The procedures in solving Laplace transform are
(1) Use syms command to declare symbolic variables t, so as to describe time-
domain expression f .
(2) Call directly the laplace() function to compute the Laplace transform
F =laplace(f ), % default t is time variable
F =laplace(f ,v,u), % user declare time variable v and complex u
7.4 · Introduction to Integral Transforms
201 7
(3) For complicated problems, the result can be simplified with the simplify()
function. Besides, the transform result is sometimes difficult to read. Function
pretty() or latex() functions can be used to further processing.
If Laplace expression is known, symbolic variable s should be declared, the func-
tion F can be described. The function ilaplace() in the Symbolic Math Toolbox
takes its inverse, with the syntaxes
f =ilaplace(F ), % default s as complex variable
f =ilaplace(F ,u,v), % user specify time variable v and complex u
The result f should also be further simplified.

 Example 7.46
For the function f (t) = t2 e−2t sin(t + π), find its Laplace transform.
Solutions Time variable t can be declared as symbolic variable first, then function f (t) can
be described, and the following commands are used to evaluate the Laplace transform.
>> syms t; f=t^2*exp(-2*t)*sin(t+pi);
F=simplify(laplace(f)) % direct transform
The Laplace transform obtained is

2 2(2s + 4)2
F (s) =  2
−  3 .
(s + 2)2 + 1 (s + 2)2 + 1

 Example 7.47
Assume the function is f (x) = x2 e−2x sin(x + π), find its Laplace transform. Take inverse
Laplace transform to the result and see whether the original function is restored.
Solutions Function laplace() can be used to solve the problem.
>> syms x w; f=x^2*exp(-2*x)*sin(x+pi);
F=laplace(f,x,w), g=simplify(ilaplace(F))
It can be seen that the result is the same as the original function, where variable substitution
is needed. Inverse Laplace transform function ilaplace(F) yields the original function
−t2 e−2t sin t, since sin(t+π) = − sin t. 

 Example 7.48
1
For the time-domain function f (t) = √ , where a, b > 0. Find its Laplace trans-
t (at + b)
form.
Solutions Input the problem into computer to solve it with MATLAB directly.
>> syms t; syms a b positive
f(t)=1/sqrt(t)/(a*t+b); simplify(laplace(f))
202 Chapter 7 · Calculus and Integral Transforms

( ) ( )
c( ) ( )

forward ( )

( )

. Fig. 7.13 Closed-loop system structure

  
πebs/a bs
The Laplace transform is F (s) = √ 1−erf , where erf (·) is a special function,
ab a
 x
2
e−t dt. 
2
defined as erf (x) = √
π 0

7
7.4.2 Numerical Laplace Transform
The analytical solutions of Laplace transform of many functions do not exist, or not
suitable to find. Therefore, numerical methods should be considered to solve Laplace
transform problems. Juraj Valsa developed a MATLAB function to solve numerical
inverse Laplace transform, INVLAP() [7, 8], whose syntax is
[t, y]=INVLAP(f ,t0 ,tn ,N, other parameters)
where the function is described by a string containing s, (t0 , tn ) are the interested time
interval, where t0 = 0. N is the number of points to compute. Different values of N
can be used to validate the result. Other parameters may refer to the original function.
It is suggested here thus unless absolutely necessary, there is no need to modify the
default parameters manually.
In this book, necessary extensions are made to the INVLAP() function. The new
solver can be used to replace the original function, and the facilities are extended to
tackle more problems.
Consider the typical feedback control system shown in . Fig. 7.13. The forward
path is the series connection of P(s) and Gc (s), such that the equivalent forward
transfer function is P(s)Gc (s), simply denoted as G(s). If the Laplace transform of
the input signal is R(s). How can we find the Laplace transform Y (s) of output signal?
How to find the output signal y(t) in time domain?
Based on the INVLAP() function, a more powerful INVLAP_new() function is
written [2], and the new syntaxes are supported
[t, y]=INVLAP_new(G,t0 ,tn ,N), % inverse Laplace transform of G
[t, y]=INVLAP_new(G,t0 ,tn ,N,H), % impulse response of system G, H
[t, y]=INVLAP_new(G,t0 ,tn ,N,H,u), % u to describes the input
[t, y]=INVLAP_new(G,t0 ,tn ,N,H,t x ,ux ), % tx , ux are the samples
7.4 · Introduction to Integral Transforms
203 7
Various syntaxes are supported, where G is the string for Laplace transform
expression, and H is of string for the feedback path. If input signal is used, u can
either be the string for the Laplace transform of the input signal, or the anony-
mous function description of the time-domain function. The input signal can also be
described by sample vectors (t x , ux ) of the inputs. If the inverse Laplace transform
of G is expected, H can be set to 0.
Apart from the modifications above, other modifications are made, where t0 can
be set to 0, but this point is bypassed in the function. Also in dealing with strings, dot
operations are processed uniformly. Even though in some places, dot operations are
not originally used, they are added automatically.

 Example 7.49
Assume that the complicated irrational open-loop transfer function is given as follows [9],
draw the step response of the closed-loop system with unity negative feedback.

! √ "2
sinh(0.1 s) 1
G(s) = √ √ √ .
0.1 s s sinh( s)

Solutions The irrational open-loop transfer function can be expressed in a string. The
Laplace transform of the step input signal is 1/s. Therefore the step response curve of the
closed-loop system is obtained, as shown in . Fig. 7.14.
>> G='(sinh(0.1*sqrt(s))/0.1/sqrt(s))^2/sqrt(s)/sinh(sqrt(s))';
[t,y]=INVLAP_new(G,0,10,1000,1,'1/s'); plot(t,y) % step response


1.2

0.8

0.6

0.4

0.2

0
0 1 2 3 4 5 6 7 8 9 10

. Fig. 7.14 Step response of the closed-loop system


204 Chapter 7 · Calculus and Integral Transforms

7.4.3 Fourier Transform


In Laplace transform, the operator e−st is introduced. If s is substituted by jω, where
ω is the frequency, Fourier transform can be formulated.
The definition of Fourier transform is
 ∞
F[f (t)] = f (t)e−jωt dt = F (ω). (7.33)
−∞

If Fourier transform F (ω) is known, the inverse Fourier transform is defined as


 ∞
−1 1
f (t) = F [F (ω)] = F (ω)ejωt dω. (7.34)
2π −∞

Similar to Laplace transform, the symbolic variables should be declared first, then
describe the function f , then fourier() function evaluates Fourier transform, in the
7 following syntaxes:
F =fourier(f ), % compute Fourier transform
F =fourier(f ,v,u), % specify the variables
Inverse Fourier transform can be obtained with the function ifourier().
f =ifourier(F ), % inverse Fourier transform
f =ifourier(F ,u,v), % specify variables

 Example 7.50
Consider f (t) = 1/(t2 + a2 ), a > 0. Write out the Fourier transform expression.
Solutions The following commands find the Fourier transform for the original function.
The solution is F = πe−a|ω| /a. Taking inverse Fourier transform to the result, the original
function is restored.
>> syms t w; syms a positive
f(t)=1/(t^2+a^2); F=fourier(f,t,w) % direct transform
f1=ifourier(F,w,t) % inverse transform to the result


 Example 7.51
For the time-domain function f (t) = sin2 (at)/t, a > 0, find its Fourier transform.
Solutions The following MATLAB commands are given to find the Fourier transform of
function f (t):
>> syms t w; syms a positive % declare a as a positive symbolic variable
f(t)=sin(a*t)^2/t; F=fourier(f,t,w) % direct transform
The result obtained is

πj πj
− heaviside(−2a − ω) − heaviside(2a − ω) + πj heaviside(−ω),
2 2
7.4 · Introduction to Integral Transforms
205 7
where heaviside(x) function is the step function of x, also known as Heaviside function.
If x > 0, the value of the function is 1, and when x = 0, the function is 0.5, otherwise,
the function is 0. When ω > 2a, the three heaviside() functions are all 1, then F (ω) = 0.
If ω ≤ −2a, the three functions are all 0, thus F (ω) = 0. If 0 < ω < 2a, the 2nd and 3rd
heaviside() are 1, then F (ω) = −jπ/2. If 0 > ω > −2a, then F (ω) = jπ/2. Summarizing the
above cases, the original Fourier transform can be simplified manually as
#
0, |ω| > 2a
F[f (t)] =
−jπ sign(ω)/2, |ω| < 2a.

7.4.4 z Transform
Strictly speaking, z transform is not integral transform. However, since the definition,
properties and solution methods are quite similar to Laplace and Fourier transforms,
and is useful in describing sequence signals, it is also presented in this section.
The z transform of sequence f (k), k = 1, 2, . . . is defined as


Z[f (k)] = f (k)z−k = F (z). (7.35)
k=0

For the expression F (z), the inverse z transform is defined as


&
−1 1
f (k) = Z [f (k)] = F (z)zk−1 dz. (7.36)
2πj

With ztrans() and iztrans() functions provided in the Symbolic Math Tool-
box, the z and inverse z transforms can be obtained, in the syntaxes
F =ztrans(f ,k,z), % z transform of the given function
F =iztrans(f ,z,k), % inverse z transform
If the function has only one variable, there is no need to specify k or z.

 Example 7.52
Solve the z transform problem of the signal f (kT ) = akT − 2 + (akT + 2)e−akT .
Solutions The z transform can be evaluated with the following statements:
>> syms a T k; f=a*k*T-2+(a*k*T+2)*exp(-a*k*T); F=ztrans(f) % z transform
The result obtained is
 −1
aTz 2z aTze−aT aT z
Z[f (kT )] = − + 2 + 2ze − 1 .
(z − 1)2 z−1 z − e−aT e−aT


206 Chapter 7 · Calculus and Integral Transforms

 Example 7.53
bs + c
Find the z transform of the function F (s) = 2 .
s (s + a)
Solutions Since F (s) is a Laplace transform expression, function ilaplace() can be called
to compute the inverse Laplace transform to find the time-domain function f (t). Then z
transform can be taken, with the following statements:
>> syms a b c s; F=(b*s+c)/s^2/(s+a);
f=ilaplace(F); F1=simplify(ztrans(f))
The obtained z transform expression is

cz (c − ab) z (c − ab) z
F1 = + 2 − .
a(z − 1)2 a z − e−a a2 (z − 1)

7 7.5 Exercises
(1) Compute the limits
(x + 2)x+2 (x + 3)x+3
(a) lim (3x + 9x )1/x , (b) lim ,
x→∞ x→∞ (x + 5)2x+5
⎡ ⎤
 cot(x−a)
tan x 1 1
(c) lim , (d) lim ⎣   − ⎦.
x→a tan a x→0 ln x + 1 + x2 ln(1 + x)
!  "
3 3 ln (ex + x)
(2) Find the limits lim x +x +x+1− x +x+1
2 2 .
x→∞ x
(3) Solve the following limit problems:
 n  n
1 + x2 + x − 1 + x2 − x
(a) lim , n ≥ 0,
x→0 x
sin(a + 2x) − 2 sin(a + x) + sin a
(b) lim .
x→a x2
(4) Compute the limit

arcsinh sinh x − arcsinh sin x


lim ,
x→0 sinh x − sin x
  
where arcsinhx = ln x + 1 + x2 .
(5) Compute the limits
 2
4 sin x + x2 cos(4/x) (sin x − tan x) cos x − ex
(a) lim , (b) lim    .
x→0 (5 + 2 cos x) ln(1 + x) x→0 x 1 + x2 /2 − 1 + x2
(6) Compute the sequence limits.
√ √ √  √
n

n

n 
(a) lim n n+1− n , (b) lim 1 + 2 + · · · + 10 .
n→∞ n→∞
7.5 · Exercises
207 7
(7) Compute the one-sided limits
 π tan 2x  
ln ax
(a) lim tan +x , (b) lim ln(x ln a) ln , a > 1.
x→π/4+ 8 x→0+ ln(x/a)
(8) Consider the following sequence, find the general term an . Compute the limits
lim an and lim an+1 /an .
n→∞ n→∞


 cos 1! cos 2! cos 3! cos 4! cos 5!
S= an = + + + + + ··· .
1×2 2×3 3×4 4×5 5×6
n=1
 
(9) For the following functions, compute the limits F (x) = lim f (x+h)−f (x) /h.
h→0

1 + sin x √
(a) f (x) = sin cos sin 2x, (b) f (x) = ln √ + 2 arctan sin x.
1 − sin x
(10) Compute the double limits and observe the behavior around the targets.
x2 y + xy3 xy
(a) lim , (b) lim  ,
(x + y)
(x,y)→(−1,2) 3(x,y)→(0,0) xy + 1 − 1
 2 
1 − cos x + y2
(c) lim   .
(x,y)→(0,0) x2 + y2 ex2 +y2

(11) In Example 7.10, an offset is introduced in the plotting commands. If the offset
is not introduced, what is the result?
(12) Compute the following derivatives:
+ √
√ 1 − cos ax
(a) y(x) = x sin x 1 − e , (b) y = 
x √ ,
x 1 − cos ax
y 1 xn + a
(c) atan = ln(x2 + y2 ), (d) y(x) = − ln , n > 0.
x na xn
(13) Find the first-order derivatives.
 
(a) y(t) = arccos2 x + ln2 arccos x − ln arccos x + 1/2 ,

1 4 1
4
1 + x4 + 1
(b) y(t) = arctan 1 + x4 + ln  ,
2 4 4
1 + x4 − 1
e−x arcsin e−x
2 2
1  2
(c) y(x) = + + ln 1 − e−2x .
2
1 − e−2x
2

(14) Find the tenth-order derivative of the function



1 − cos ax
y(x) = √
x(1 − cos ax)
. ,
#
x = ln cos t dy d2 y ,,
(15) For the parametric equations compute and , .
y = cos t − t sin t, dx dx2 ,
t=π/3
208 Chapter 7 · Calculus and Integral Transforms

(16) Compute the first- and second-order derivatives for the following parametric
equations:
# #
x(t) = a(ln tan t/2 + cos t − sin t) x(t) = 2at/(1 + t3 )
(a) (b)
y(t) = a(sin t + cos t), y(t) = a(3at2 )/(1 + t3 ).
(17) If f (x) = x2 ax , a > 0, derive and prove the formula for f (n) (x).
(18) Compute dy/dx, d2 y/dx2 and d3 y/dx3 for the parametric equations.
(a) x = e2t cos2 t, y = e2t sin2 t,
 
(b) x = arcsint/ 1 + t2 , y = arccost/ 1 + t2 .

x ∂ 2 u(x, y) ∂ 2 u(x, y)
(19) For given function u(x, y) = arccos , show = .
y ∂x∂y ∂y∂x
(20) If u(x, y) = x − y + x2 + 2xy + y2 + x3 − 3x2 y − y3 + x4 − 4x2 y2 + y4 , compute
∂ 4 u(x, y) ∂ 4 u(x, y) ∂ 4 u(x, y)
the partial derivatives , and .
7 ∂x 4 ∂x ∂y
3 ∂x2 ∂y2
 xy
x2 ∂ 2 f (x, y) ∂ 2 f (x, y)
e−t dt, show that 2
2
(21) Assume that f (x, y) = = .
0 y ∂x2 ∂y2
(22) For a given function

√   √  
x x x x
y(x) = ex/ 2
C1 cos √ + C2 sin √ + e−x/ 2 C3 cos √ + C4 sin √ ,
2 2 2 2

show that for any constants C1 , C2 , C3 and C4 , the equation y(4) (x) + y(x) = 0
is satisfied.
1 ∂ 4u
(23) For u = ln  , compute .
(x − ξ )2 + (y − η)2 ∂x∂y∂ξ ∂η
  ∂z ∂z
(24) If z = ψ x2 + y2 , compute y −x .
∂x ∂y
∂ 2u ∂ 2u ∂ 2u
(25) For u = xφ(x + y) + yψ(x + y), compute −2 + 2.
∂x 2 ∂x∂y ∂y
(26) If z = F (r, θ ), where r and θ are functions of x and y: x = r cos θ y = r sin θ ,
compute ∂z/∂x and ∂z/∂y.
(27) Compute the indefinite integrals.
  √
3x2 + a x(x + 1)
(a) I (x) = −  2 dx, (b) I (x) = √ √ dx,
x2 x2 + a x+ 1+x
 
(c) I (x) = xeax cos bxdx, (d) I (x) = eax sin bx sin cxdx,
 
sin2 x − 4 sin x cos x + 3 cos2 x
(e) I (t) = (7t2 − 2)35t+1 dt, (f) dx.
sin x + cos x
7.5 · Exercises
209 7
(28) Compute the definite and improper integrals.
 ∞  1  1 ,  ,
cos x 1 + x2 , ,
(a) I = √ dx, (b) I = dx, (3) ,cos ln 1 , dx.
, x ,
0 1+x
x 4
0 e−2πn
(29) Find the definite integrals.
 0.75  1 √
1 arcsin x
(a)  dx, (b) √ dx,
0 (x+1) x2 +1 0 x(1 − x)
 π/4  
sin x − cos x 2n+1
(c) dx.
0 sin x + cos x
 s x x
e e −1
(30) Compute integral function and draw curve I (s) = dx.
0 ex + 3
(31) Assume that f (x) = e −5x sin (3x + π/3), find the integral
 t
R(t) = f (x)f (t + x)dx
0
.
(32) Compute the multiple integrals.
 π π  1  1−x
(a) |cos(x + y)| dxdy, (b) arcsin(x + y)dydx,
0 0 0 −1
 2  √4−x2 +  3  3−x  3−x−y
(c) 4 − x2 − y2 dydx, (d) xyz dzdydx,
0 0 0 0 0
  √ 2 √ 4−x2 4−x2 −y2
(e) z(x2 + y2 ) dzdydx,
 01  0x  y z
0

xyzue6−x −y −z −u dudzdydx,
2 2 2 2
(f)
0 0 0 0
 7/10  4/5  9/10  1  11/10 +
(g) 6 − x2 − y2 − z2 − w2 − u2 dwdudzdydx.
0 0 0 0 0
(33) Find the first n term and infinite sum.
1 1 1
(a) + + ··· + + ···,
1 × 6 6 × 11 (5n − 4)(5n + 1)
     
1 1 1 1 1 1
(b) + + + 2 + ··· + + n + ···,
2 3 22 3 2n 3

1 x  1 × 4 x 2 1 × 4 × 7 x 3 1 × 4 × 7 × 10  x 4
  
(c) + + + + ···.
3 2 3×6 2 3×6×9 2 3 × 6 × 9 × 12 2
(34) Find the infinite sums.

 ∞ ∞

sin2 nα sin nx π (−1)n n3 n x4n+1
(a) , 0 < α < , (b) x , (c) .
n 2 (n + 1)! 4n + 1
n=1 n=0 n=0
(35) Find the first n terms and infinite sums.
√ √ √ √ √ √ √
(a) 3 x + ( 5 x − 3 x) + ( 7 x − 5 x) + · · · + ( 2k+1 x − 2k−1 x) + · · · ,
m m(m − 1) 2 m(m − 1) · · · (m − n + 1) n
(b) 1 + x + x + ··· + x + ···.
1! 2! n!
210 Chapter 7 · Calculus and Integral Transforms

(36) If the general term an is known, find the infinite sums.


√ √ p n − 1 1
(a) an = 1 + n − n ln , (b) an = 1+k/lnn .
n+1 n
(37) Find the sequence sums.

 ∞

xn (−1)n
(a) , (b) ,
(1+x)(1+x2 ) · · · (1+xn ) n2 + n − 2
n=1 n=2

 1
(3) .
n2 (n + 1)2 (n + 2)2
n=2
(38) Compute the following limits:
 
1 1 1 1
(a) lim + 2 + + ··· + ,
n→∞ 22 − 1 4 − 1 62 − 1 (2n)2 − 1
 
1 1 1 1
(b) lim n 2 + + + ··· + 2 .
n→∞ n + π n2 + 2π n2 + 3π n + nπ
7 (39) Find the following infinite sequence products:
∞ ∞ ∞
(2n + 1)(2n + 7) 9n2
a(−1) /n , a > 0.
n
(a) , (b) , (3)
(2n + 3)(2n + 5) (3n − 1)(3n + 1)
n=1 n=1 n=1
 π/4 ∞
 1
(40) For the general term an = tann xdx, compute S = (an + an+2 ).
0 n
n=1
(41) Test the convergency of the following infinite series:
∞ 
 n ∞
 ∞

n 1 n+1
(a) , (b) , (c) (−1)n √ ,
1 + n2 lnn ln(lnx) (n + 1) n + 1 − 1
n=2 n=10 n=1
3 3×5 3×5×7 3 × 5 × 7 × · · · × (2n + 1)
(d) − + + · · · + (−1)n−1 + ···.
2 2×5 2×5×8 2 × 5 × 8 × · · · × (3n − 1)
 √  √   √ 
1 − x 1 − 3 x ··· 1 − n x
(42) Compute the limit lim .
x→1 (1 − x)n−1
  
 +
 √
(43) Find the infinite expression S = x + x + x + x + x + · · ·.

(44) Find the Taylor series expansion about x = 0 and x = a points.


 x     
sin t 1+x
(a) dt, (b) ln , (c) ln x + 1 + x2 ,
0 t 1−x
(d) (1 + 4.2x2 )0.2 , (e) e−5x sin(3x + π/3).
(45) Find the first ten terms in Taylor series expansion for the function f (t) = et .
Find the t range where good fitting can be made.
(46) Find Fourier series expansions.
(a) f (x) = (π − |x|) sin x, −π  x < π, (b) f (x) = e|x| , −π  x < π,
#
2x/l, 0 < x < l/2
(c) f (x) = and l = π.
2(l − x)/l, l/2 < x < l,
7.5 · Exercises
211 7
(47) From the data in . Table 7.6, find various order of derivatives with the forward
difference method.
(48) Generate a set of equally spaced samples for the following statements. Compute
numerical first-order derivative from the samples with various methods, and
assess the accuracies by comparing them with theoretical values.
 
(a) y(x) = arccos2 x + ln2 arccos x − ln arccos x + 1/2 ,

1 
4 1
4
1 + x4 + 1
(b) y(x) = arctan 1 + x + ln 
4 ,
2 4 4
1 + x4 − 1
e−x arcsin e−x
2 2
1  2
(c) y(x) = + + ln 1 − e−2x .
2
1 − e−2x
2

(49) Find definite integral from the data shown in . Table 7.7. If high-precision
method is used, what is the result?
(50) Find the numerical solutions to the definite and improper integrals and assess
the accuracy.
 ∞  1  1 ,  ,
cos x 1 + x2 , ,
(a) I = √ dx, (b) I = dx, (c) ,cos ln 1 , dx.
x 1+x 4 −2πn
, x ,
0 0 e
(51) Compute multiple integrals with numerical method.
 2  √4−x2 +  3  3−x  3−x−y
(a) 4 − x − y dydx, (b)
2 2 xyz dzdydx,
0 0 0 0 0
  √  √
2 4−x2 4−x2 −y2
(c) z(x2 + y2 ) dzdydx.
0 0 0
(52) Compute the multiple integrals with numerical methods. It is noted that the
analytical solutions do not exist. How to validate the results?
 2  e−x2 /2 +
4 − x2 − y2 e−x −y dydx,
2 2
(a)
0 0
 2 2 2
z(x2 + y2 )e−x
2 −y2 −z 2 −xz
(b) dzdydx.
0 0 0

. Table 7.6 Data in Exercise (47)

xi 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2

yi 0 2.2077 3.2058 3.4435 3.241 2.8164 2.311 1.8101 1.3602 0.9817 0.6791 0.4473 0.2768

. Table 7.7 Data in Exercise (49)

xi 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2

yi 0 2.208 3.206 3.446 3.241 2.816 2.311 1.810 1.360 0.982 0.679 0.447 0.277
212 Chapter 7 · Calculus and Integral Transforms

(53) Find Laplace transform for the following functions f (t):


(a) fa (t) = sin αt/t, (b) fb (t) = t6 eαt , (c) fc (t) = t5 sin αt,
(d) fd (t) = t8 cos αt, (e) fe (t) = eβt sin(αt+θ ),
(f) ff (t) = 5e−at +t4 e−at +8e−2t , (g) fg (t) = e−12t +6e9t .

(54) Take inverse Laplace transform to the above results and see whether the original
functions can be restored.
(55) Compute inverse Laplace transform for the following functions F (s):
1 s−a 1
(a) Fa (s) = √ , (b) Fb (s) = ln , (c) Fc (s) = √ ,
s(s2 − a2 )(s + b) s−b s(s + a)
√  3a2 (s − 1)8
(d) Fd (s) = s − a − s − b, (e) Fe (s) = 3 , (f) F f (s) = ,
s + a3 s7
s 2 + a2 s2 + 3s + 8 1 s+α
(g) Fg (s) = ln 2 , (h) Fh (s) = , (i) Fi (s) = .
s +b 2 $8 2 s−α
7 (s + i)
i=1
(56) The Laplace transform expression is given by

(s0.4 + 0.4s0.2 + 0.5)


G(s) = √ ,
s (s0.2 + 0.02s0.1 + 0.6)0.4 (s0.3 + 0.5)0.6

find numerically the inverse Laplace transform, and draw the curve in the inter-
val t ∈ (0, 1).
(57) If a fractional-order system is created by the two parallel connected subsystems
G1 (s) and G2 (s) defined below, the overall model can be computed from G(s) =
G1 (s) + G2 (s). Draw the unit step response of the overall system.

(s0.4 + 2)0.8 s0.4 + 0.6s + 3


G1 (s) = √ , G2 (s) = 0.5 .
s(s + 3s + 4)
2 0.9 0.3 (s + 3s0.4 + 5)0.7

(58) Find Fourier transforms for the following functions. Take inverse Fourier trans-
form to the results and see whether the original function can be restored.
(a) f (x) = x2 (3π − 2|x|), (b) f (t) = t2 (t − 2π)2 ,
(c) f (t) = e−t , (d) f (t) = te−|t| .
2

(59) Find z transforms for the following time-domain sequences f (kT ). Validate the
results with inverse z transform.
(a) fa (kT ) = cos(kaT ), (b) fb (kT ) = (kT )2 e−akT ,
1
(c) fc (kT ) = (akT − 1 + e−akT ), (d) fd (kT ) = e−akT − e−bkT ,
a
(e) fe (kT ) = sin(αkT ), (f) ff (kT ) = 1 − e−akT (1 + akT ).
7.6 · Mini-Projects
213 7
(60) For the given z transform expressions F (z), find their inverse z transform.
10z z2
(a) Fa (z) = , (b) Fb (z) = ,
(z − 1)(z − 2) (z − 0.8)(z − 0.1)
z z−1 (1 − e−aT )
(c) Fc (z) = , (d) F d (z) = ,
(z − a)(z − 1)2 (1 − z−1 )(1 − z−1 e−aT )
Az[z cos β − cos(αT − β)]
(e) Fe (z) = .
z2 − 2z cos(αT ) + 1
(61) For the following Laplace transform expressions, find the corresponding z
transforms and validate the results.
b b 1 − e−2s
(a) G(s) = 2 , (b) G(s) = 2 .
s (s + a) s (s + a)2 s
(62) Show with MATLAB that
-  a . z(Az + B)
Z 1 − e−akT cos(bkT ) + sin(bkT ) = ,
b (z − 1)(z2 − 2e−aT cos(bT )z + e−2aT )

where
a −aT
A = 1 − e−aT cos(bT ) − e sin(bT ),
b
a −aT
B = e−2aT + e sin(bT ) − e−aT cos(bT ).
b

7.6 Mini-Projects

1. Path Integral Problem


Assume that there is a smooth 3D spatial curve l, described by a parametric equation
x = x(t), y = y(t), and z = z(t). At spatial point (x, y, z), the density of the curve is
f (x, y, z). It is known that the curve is defined in the interval tm ≤ t ≤ tM , how to
compute its mass?
The mathematical expression of the mass is

w= f (x, y, z)ds, (7.37)
l

where ds is the differentiation term of the arc at (x, y, z) point. This integral is also
known as the path integral of the first type.
There are no immediate official MATLAB solvers to compute the path integral,
while in mathematics, there are formulas to convert the path integral into a standard
integral problem. The parametric equation can be substituted into f (·), to convert it
into a function of t. Also, arc differentiation term can be computed from
+
ds = (dx/dt)2 + (dy/dt)2 + (dz/dt)2 dt (7.38)
214 Chapter 7 · Calculus and Integral Transforms

+
which is simply denoted as ds = xt2 + yt2 + zt2 dt. The path integral problem is then
converted into the following standard integral problem with respect to t.
 tM  +
I= f x(t), y(t), z(t) xt2 + yt2 + zt2 dt (7.39)
tm

If the curve is described by a 2D parametric function, x = x(t), y = y(t), while


f (x, y) is the density function, the problem can also be converted into a standard
integral problem.  tM
 +
I= f x(t), y(t) xt2 + yt2 dt (7.40)
tm

Write a universal MATLAB solver for this type of path integral problem, for 2D
and 3D curves.
 Compute the following path integrals:
(1) I1 = (x2 + y2 )ds, l is x = a(cos t + t sin t), y = a(sin t − t cos t), 0  t  2π.
l
7 (2) I2 = (x2 + y2 + z2 )ds, where l is a spiral line x(t) = a cos t, y(t) = a sin t,
l
z(t) = bt, and 0 ≤ t ≤ 2π.

2. Numerical Multivariate Integral


The multivariate integral problem solvers discussed in this book have limitations. For
certain functions, the analytical solutions do not exist, while the existing numerical
solvers cannot compute n-tuple integrals with function bounds, when n > 3.
Consider a special integral problem

 2 2  √1−z2  √4−y2 −z2


J= √ √ u2 sin u dxdydzdu
0 −2 − 1−z2 − 4−y2 −z2

According to the above discussions, the analytical and numerical solutions cannot
be found. For some special problems, the analytical solver int() can be tried, and
if you are lucky, the original problem may be converted into a solvable form, so
that numerical methods can then be used to find the final integral. Try to find the
numerical solutions to the above problem.

References
1. Demidovich BP (1970) Problems in mathematical analysis[M]. MIR Publishers, Moscow
2. Xue DY, Chen YQ (2016) Scientific computing with MATLAB[M], 2nd edn. CRC Press, Boca Raton
3. Xue DY (2020) Calculus problem solutions with MATLAB[M]. De Gruyter, Berlin
4. Varberg D, Purcell E, Rigdon S (2006) Calculus[M], 9th edn. Prentice Hall, Upper Saddle River
5. Duriš F (2009) Infinite series: convergence tests[D]. Bachelor’s thesis, Katedra Informatiky, Fakulta
Matematiky, Fyziky a Informatiky, Univerzita Komenského, Bratislava, Slovakia
6. Forsythe GE, Malcolm MA, Moler CB (1977) Computer methods for mathematical computations.
Prentice-Hall, Englewood Cliffs
7. Valsa J, Brančik L (1998) Approximate formulae for numerical inversion of Laplace transforms[J]. Int
J Numer Model Electron Netw Devices Fields 11(3):153−166
References
215 7
8. Valsa J (2011) Numerical inversion of Laplace transforms in MATLAB[R]. MATLAB Central File
ID: #32824
9. Callier FM, Winkin J (1993) Infinite dimensional system transfer functions[M]. Curtain RF, Bensoussan
A, Lions JL (eds) Analysis and optimization of systems: state and frequency domain approaches for
infinite-dimensional systems. Springer, Berlin
217 8

Linear Algebra and Matrix


Analysis
Contents

8.1 Special Matrices Input – 219


8.1.1 Zeros, Ones and Identity Matrices – 219
8.1.2 Random Matrices – 221
8.1.3 Diagonal Matrices – 222
8.1.4 Representation of Special Matrices – 223

8.2 Matrix Analysis – 224


8.2.1 Simple Analysis of Matrices – 225
8.2.2 Inverse Matrices – 229
8.2.3 Moore–Penrose Generalized Inverses – 231
8.2.4 Eigenvalues and Eigenvectors – 232

8.3 Matrix Transform and Decomposition – 233


8.3.1 Similarity Transforms – 234
8.3.2 Companion Matrix Transforms – 234
8.3.3 Transforming Matrices into Diagonal or Jordanian Ones – 235
8.3.4 Triangular Factorizations – 236
8.3.5 Cholesky Factorization of Symmetrical Matrices – 237
8.3.6 Singular Value Decomposition – 239

8.4 Matrix Functions – 240


8.4.1 Matrix Exponential Functions – 240
8.4.2 Matrix Trigonometric Functions – 241
8.4.3 Arbitrary Matrix Functions – 242

8.5 Exercises – 243

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_8
8.6 A Mini-Project – 247

References – 248
8.1 · Special Matrices Input
219 8
The study of linear algebra problems is originated from linear equations solution.
Linear equations are the most widely used mathematical models in scientific research
and engineering practice. Complicated linear algebraic equations can be established
in many applications. Matrices are the most important mathematical units in linear
algebra. Starting from the investigations on matrices, various matrix analysis meth-
ods and tasks are developed, and a complete research system on linear algebra is
established. Matrix transformations and matrix functions are also presented in this
chapter.
MATLAB language is also originated from the studies of linear algebra and matrix
analysis. The earliest MATLAB functions were targeted at solving linear algebra
problems. In this chapter, MATLAB is used extensively in the study of linear algebra
and matrix analysis problems. In 7 Sect. 8.1, the input methods of special matrices are
presented, including matrices of zeros, ones and identity matrices. Special matrices
such as random matrices and diagonal matrices are also demonstrated. In 7 Sect. 8.2,
simple matrix analysis methods are presented, followed by the computation of inverse
matrices and eigenvalue problems. In 7 Sect. 8.3, matrix transformation and factor-
ization methods are introduced. Similarity transformation, LU factorization, Jorda-
nian transformation and singular value decomposition are presented. In 7 Sect. 8.4,
the definition and computing methods of matrix functions are presented. The solvers
for matrix exponential functions, trigonometric functions and arbitrary matrix func-
tions are presented.
There is yet another important category of problems in linear algebra−linear
algebraic equation solution methods. This topic is not presented in this chapter. In
7 Chap. 9, various algebraic equation solution methods will be fully addressed.

8.1 Special Matrices Input


Before analyzing matrices, the matrices must exist in MATLAB workspace. The input
methods of ordinary matrices are introduced in 7 Chap. 2. Any complex matrices can
be entered into MATLAB workspace in this way. In real applications, special matrices
are often involved. For instance, for a 10 × 20 matrix whose elements are all 0’s, there
is no need to input the elements one by one. Some dedicated functions can be called
to input special matrices in a concise way.
A great amount of functions are provided in MATLAB to input special matrices.
The most commonly used ones are provided in . Table 8.1. The users can input
directly special matrices according to the specified syntaxes. In this section, examples
are provided to demonstrate some special matrices.

8.1.1 Zeros, Ones and Identity Matrices


Zero matrices are the matrices whose elements are all 0’s. Ones matrices are those with
all elements 1’s. These matrices can be generated with functions zeros() and ones().
Function eye() generates rectangular “identity” matrix, which is an extension to iden-
tity matrices. If matrix A is known, command size( A) extracts its size. Therefore,
command B =eye(size( A)) generates an extended identity matrix B whose size is
220 Chapter 8 · Linear Algebra and Matrix Analysis

. Table 8.1 Commonly used special matrices

Matrix names Syntaxes and descriptions

Matrix of zeros A = zeros(n, m) generates an n × m matrix A whose elements are all 0’s; The other syntax
is A =zeros([n,m]); If only n is given, an n × n square matrix is generated;
Multidimensional zero array zeros(n1 ,n2 ,· · · ,np )

Matrix of ones A = ones(n, m) generates a matrix of 1’s, other syntaxes see zeros()

Identity matrix A = eye(n, m) generates extended identity matrix, whose main diagonal elements are 1’s,
while other elements are 0’s

Random matrices A = rand(n, m) generates an n × m random A, whose elements satisfy uniform distribution
over [0, 1]; function randn() generates standard normal distribution matrix; Function
R =randi([a,b],[n,m]) generates random integer matrix over [a, b] interval

Companion matrix A = compan( p) generates a companion matrix with characteristic polynomial of p

Diagonal matrix D = diag( p, k) generates a matrix whose kth diagonal elements is p vector; if p is a
matrix, the kth diagonal elements are extracted in a column vector D; if k is omitted, the
main diagonal is involved

Vandermonde matrix V = vander( p) generates a Vandermonde matrix V from vector p, whose kth column is
8 v = p.n−k

Hilbert matrix H = hilb(n) generates an n × n Hilbert matrix where hij = 1/(i + j − 1)

Hankel matrix H = hankel(c, r) generates a Hankel matrix, where c and r are the first column and last
row elements, while back-diagonal elements are the same

Magic matrix M = magic(n) generates an n × n magic matrix, whose sums of columns, rows, diagonal
and back-diagonal elements are equal

Pascal matrix P = pascal(n) generates an n × n Pascal matrix, whose first row and column elements are
1, and other elements are pij = pi−1,j +pi,j−1

Wilkinson matrix W = wilkinson(n) generates an n × n tri-diagonal Wilkinson test matrix, whose


sub-diagonal elements are 1, and the main diagonal elements | − (n − 1)/2:(n − 1)/2|

Toeplitz matrix T = toeplitz(c, r) generates a Toeplitz matrix, where c is the first row elements and r is
the first column elements. If r is omitted, the elements are also c, such that a square matrix
is generated

Hadamard matrix H = hadamard(n) generates an n × n Hadamard matrix, whose first row and column

elements are all 1’s; the 1 and −1 alternatively appear in other places. H/ n is an
orthogonal matrix

the same as A. These functions can also be used to generate multidimensional arrays.
Examples are used to generate these matrices.

 Example 8.1
Generate a 3 × 6 A matrix of zeros. Also generates an identity matrix B whose size is the
same as A.
Solutions The expected matrices can be directly entered.

>> A=zeros(3,6), B=eye(size(A)) % generate the needed matrices


The matrices generated are
8.1 · Special Matrices Input
221 8
⎡ ⎤ ⎡ ⎤
0 0 0 0 0 0 1 0 0 0 0 0
A = ⎣0 0 0 0 0 0⎦, B = ⎣0 1 0 0 0 0⎦.
0 0 0 0 0 0 0 0 1 0 0 0

 Example 8.2
Generate a 3 × 4 × 5 × 6 × 7 × 8 multidimensional array with all elements 1.
Solutions With ones() function, such a multidimensional array can be generated. Function
size() extracts the dimensions of the variable, and function prod() is called to multiply
them together. It is found that there are 20160 elements, all set to 1. Finally with A(:)
command, all the elements in the array can be expanded into a column vector b. Function
numel(), for number of elements, also yields 20160.

>> A=ones(3,4,5,6,7,8); prod(size(A)), b=A(:), numel(A)




8.1.2 Random Matrices


Three pseudorandom matrix generating functions are shown in . Table 8.1. The
functions are rand(), randn() and randi(), and they are used in generating stan-
dard uniform distributed matrices, standard normal distributed matrices and random
integer matrices. With these functions, statistical tests can be carried out in MATLAB.

 Example 8.3
Carry out coin-tossing experiment in MATLAB. Toss a coin 100000 times with computer,
and find the probability with the coin facing-up.
Solutions This is an example to carry out statistical experiments on computers. Since
the probabilities of coin facing-up and facing-down are the same, it can be conceived
that, generate 100000 pseudorandom numbers satisfying uniform distribution in the [0,1]
interval. See how many of them are greater than 0.5, and define them as facing-up. The
probability where the random number is exactly 0.5 is almost zero, and can be ignored.
Based on the following statements, the random numbers are generated, and it is found that
the probability is p = 0.5005, close to the theoretical value of 0.5. The function nnz() is
called to find out the number of elements in R whose values are greater than 0.5.

>> N=100000; R=rand(N,1); p=nnz(R>0.5)/N % number of nonzero elements




In fact, the above-mentioned functions have limitations. For instance, they can
only be used to generate standard uniform distributed matrices. If uniform distributed
random matrices in the (a, b) interval, or normal distributed matrices satisfying
N(μ, σ 2 ) are expected, the following commands can be used:
u=a + (b−a)*rand(n,m), v=μ + σ *randn(n,m)
222 Chapter 8 · Linear Algebra and Matrix Analysis

Besides, the dedicated functions in 7 Chap. 12 can be used to generate pseu-


dorandom matrices according to certain distributions. A random integer matrix is
demonstrated next through an example.

 Example 8.4
In the function randi(), only integers within (a, b) interval appear in the generated matrix.
How to generate a 3 × 8 random integer matrix composed with integers −1,7,4,8 only?
Solutions Such a matrix cannot be generated in MATLAB function directly. Assume that
an integer random matrix with integers 1,2,3,4 can be generated first. Then substitute them
into the target integers.

>> B=randi([1,4],[3,8]); B=A; % generate a random integer matrix with 1,2,3,4 only
A(A==1)=-1; A(A==2)=7; A(A==4)=8; A(A==3)=4
Therefore the following matrix A can be generated. It can be seen that all the requests are
satisfied. Note that the substitution orders. Think about why 4 is substituted first, then
substitute 3.
⎡ ⎤ ⎡ ⎤
4 2 4 1 2 3 3 4 8 7 8 −1 7 4 4 8
8 B = ⎣3 1 2 2 2 4 4 1 ⎦ , A = ⎣ 4 −1 7 7 7 8 8 −1 ⎦ .
4 4 2 4 4 3 3 2 8 8 7 8 8 4 4 7

8.1.3 Diagonal Matrices


Function diag() is a rather powerful one. It processes diagonal matrices, and also
extracts diagonal elements from an existing matrix. Sub-diagonal elements can also
be handled. Examples are given to demonstrate the use of such a function.

 Example 8.5
Input the three matrices into MATLAB workspace.
⎡ ⎤
0 0 1 0 0 ⎡ ⎤
⎡ ⎤ 0 0 0 0
1 0 0 ⎢0 0 0 2 0⎥
⎢ ⎥ ⎢1 0 0 0⎥
A = ⎣0 2 0⎦, B = ⎢
⎢0 0 0 0 ⎥ ⎢
3⎥, C = ⎣ ⎥.
⎣0 0 2 0 0⎦
0 0 3 0 0 0 0⎦
0 0 3 0
0 0 0 0 0

Solutions Input the vector v = [1, 2, 3] to MATLAB workspace first. Therefore, matrix
A can be generated directly from the function diag(). Now consider matrix B, since the
second sub-diagonal elements are in v vector, k is set to 2. In matrix C, the sub-diagonal
below vector v, therefore k is set to −1. Therefore the following commands generate the
three matrices:

>> v=[1 2 3]; A=diag(v), B=diag(v,2), C=diag(v,-1) % construct diagonal ones


The following commands can also be used to extract diagonal elements, and they are
returned in column vectors:
8.1 · Special Matrices Input
223 8
>> v1=diag(A), v2=diag(B,2), v3=diag(C,-1) % extract diagonal elements


If A1 , A2 , · · · , An are given matrices, block diagonal matrix is defined as


⎡ ⎤
A1
⎢ A2 ⎥
A=⎢
⎣ .. ⎥.
⎦ (8.1)
.
An

Function A =blkdiag( A1 , A2 ,· · · , An ) generates a block diagonal matrix, which


allows to input arbitrary number of submatrices.

8.1.4 Representation of Special Matrices


In this section, some examples are given to demonstrate the generation of commonly
used matrices, such as Pascal, Wilkinson, Toeplitz and Hadamard matrices.

 Example 8.6
The following commands generate Pascal, Wilkinson, Toeplitz and Hadamard matrices
directly. Note that the sizes of Hadamard matrices are limited, which requires n, n/12 and
n/20 to be the power of 2. It cannot be selected arbitrarily.

>> P=pascal(5), W=wilkinson(5) % compute the generated matrix


T=toeplitz([1 2 3 4 5],[1 3 5 7]), H=hadamard(4)
The Pascal and Wilkinson matrices are as follows. Observe the elements in the upper-left
corner of the Pascal matrix.
⎡ ⎤ ⎡ ⎤
1 1 1 1 1 2 1 0 0 0
⎢1 2 3 4 5 ⎥ ⎢1 1 1 0 0⎥
⎢ ⎥ ⎢ ⎥
P =⎢
⎢1 3 6 10 15 ⎥⎥ , W = ⎢0 1 0 1 0⎥.
⎢ ⎥
⎣1 4 10 20 35 ⎦ ⎣0 0 1 1 1⎦
1 5 15 35 70 0 0 0 1 2

The generated Toeplitz and Hadamard matrices are


⎡ ⎤
1 3 5 7 ⎡ ⎤
⎢2 1 1 1 1
⎢ 1 3 5⎥⎥ ⎢ 1 −1 1 −1 ⎥
T =⎢
⎢3 2 1 3⎥ ⎢
⎥, H = ⎣1
⎥.
⎣4 1 −1 −1 ⎦
3 2 1⎦
1 −1 −1 1
5 4 3 2


224 Chapter 8 · Linear Algebra and Matrix Analysis

8.2 Matrix Analysis


The commonly used matrix analysis functions are shown in . Table 8.2. If otherwise
stated, all the functions have two different syntaxes, (1) A is a double precision matrix;
(2) A is a symbolic matrix. In the former one, numerical algorithms are used to
analyze the matrix, and the latter for analytical solutions. The results are different,
especially when the matrix approaches to a singular one, numerical methods may lead
to erroneous results. Therefore care must be taken in dealing with these matrices. The
disadvantages of the analytical solution are that the computational load is much
higher than numerical methods, for large-scale matrices. Comparative tests are made
in Reference [1], for testing determinants. Normally for determinant, a 30 × 30 matrix
takes about 1 s, while 90 × 90 matrices may need a minute.
In this section, some simple matrix analysis methods are presented, including the
direct computing of determinants, matrix ranks. Then the matrix analysis of inverse
matrices and eigenvalues are presented.

. Table 8.2 Commonly used matrix analysis functions

8 Analysis Syntaxes and descriptions

Determinant d = det( A) computes the determinant of the matrix. If A is


symbolic, analytical solution can be found, otherwise numerical
solution is found

Trace t = trace( A) computes the trace, that is the sum of diagonal


elements, which is identical to sum(diag( A))

Rank r = rank( A) computes matrix ranks. Symbolic computing is


recommended

Norm r = norm( A) computes the 2 norm of the matrix. Besides, other


norms can be evaluated with norm( A,opt), with opt for 1 norm,
opt is inf for ∞ norm, opt is 'fro' for Frobenius norm

Characteristic polynomial p = poly( A) computes the characteristic polynomial, with p the


coefficient vectors in the descending order of s. If A is a symbolic
matrix, charpoly() function should be used instead

Singular values v = svd( A) computes the singular value vector v

Condition number c = cond( A) computes the condition number, defined as the ratio
of maximum singular value to the minimum one

Inverse matrix B = inv( A) computes the inverse matrix B, such that


AB = B A = I. If A is not invertible, B =pinv( A) commands
computes the pseudoinverse of A

Eigenvalues [V , D] = eig( A) computes the eigenvalue D and eigenvector


matrix V . If only one returned argument, it returns the eigenvalue
column vector

RREF R = rref( A) computes the reduced row echelon form (RREF),


usually applied in linear algebraic equation solutions

Null space Z = null( A) computes the null space, such that AZ = 0


8.2 · Matrix Analysis
225 8
8.2.1 Simple Analysis of Matrices
The simple matrix analysis here means to find the determinants, traces, ranks, norms,
characteristic polynomials and so on. The fundamental concepts of these analysis
can be found in any linear algebra textbooks. In this section, concentrations are
made on the direct solution with MATLAB. The term solution means the numerical
and analytical solutions, depending on the data structure of matrix A. If A is a double
precision matrix, numerical methods are adopted to find the results. If A is a symbolic
one, or even containing variables, analytical methods are used to solve the problems.

1. Matrix Determinants
Matrix determinant is a very important concept in linear algebra and matrix analysis.
It was also an important tool in solving linear algebraic equations in the past, where the
term determinant means that it decides whether the equations have unique solutions
or not. The definition of matrix determinant is

D = | A| = det( A) = (−1)k a1k1 a2k2 · · · ankn , (8.2)

where k1 , k2 , · · · , kn is referred to as a permutation of 1, 2, . . . , n, and  takes the


sum of all the permutations.
It is rather complicated to compute the determinants directly from definition. In
linear algebra courses, it is recommended to use algebraic cofactor methods. For
large-scale matrix, the computational load is too heavy to execute on any computer.
Matrix factorization methods and numerical methods should be introduced. Matrix
determinants can also be evaluated directly with det() function.

 Example 8.7
Find the determinant of a 4 × 4 magic matrix.
Solutions Input a 4 × 4 magic matrix into MATLAB workspace first, then det() can be
used directly to evaluate the determinant. Convert A into symbolic form and compute the
determinant again. The former numerical result is d1 = 5.1337×10−13 while the latter is
d2 = 0, which is the accurate analytical solution.

>> A=magic(4), d1=det(A) % find the determinant numerically


B=sym(A); d2=det(B) % find determinant with analytical method


 Example 8.8
Generate a 5 × 5 integer matrix, with elements 0, 1, 2, such that the determinant of the
matrix is 1.
Solutions With random integer matrix generation function randi() in . Table 8.1, the
determinant can then be found. An outer loop can be introduced. If the determinant is 1,
the loop is completed. With the idea in mind, the following commands can be issued:

>> while (1) % construct an infinite loop, until determinant is 1


A=randi([0,2],5); if det(A)==1, break; end
end, A
226 Chapter 8 · Linear Algebra and Matrix Analysis

With the above loop, a matrix below can be found. It is worth mentioning that the matrix
found in these commands is not unique. Each time the code is executed, a different matrix
may be found. ⎡ ⎤
0 1 0 0 1
⎢1 0 1 2 2⎥
⎢ ⎥
A=⎢ ⎢1 2 0 0 2⎥.

⎣0 0 1 1 1⎦
1 0 0 2 1


 Example 8.9
Find the determinant of the following n × n matrix:
⎡ ⎤
x−a a a ··· a
⎢ a x−a a ··· a ⎥
⎢ ⎥
A=⎢
⎢ a. a x−a ··· a ⎥ .
⎣ . .. .. .. .. ⎥⎦
. . . . .
a a a ··· x − a
8
Solutions If n is not a given value, the n × n matrix cannot be handled directly with
MATLAB. A specific value of n should be used. For instance, n = 20, a 20 × 20 matrix can
be generated and the determinant is obtained d = −(18a + x)(2a − x)19 .

>> n=20; syms a x; A=a*ones(n); A=(x-2*a)*eye(n)+A; % generate the matrix


d=simplify(det(A)) % find determinant
Set n to 21, the determinant is d = (19a + x)(2a − x)20 . Summarizing the above, the
determinant of an n × n matrix is d = (−1)n+1 ((n − 2)a + x)(2a − x)n−1 , n = 1, 2, . . .. 

2. Matrix Trace
The trace of a matrix is defined as the sum of its diagonal elements. Function trace()
computes directly the trace.

 Example 8.10
For arbitrary 5 × 5 matrices A and B, validate tr( A ⊗ B) = tr( A)tr(B).
Solutions Arbitrary 5×5 matrices are generated by the method in 7 Chap. 2. The following
simple commands compute tr( A ⊗ B) and tr( A)tr(B), where ⊗ is the Kronecker product.
One more crucial problem is left: how to judge whether the two sides are equal? The simplest
way is to find the difference between the two sides and simplify the result. If the result is 0,
the two sides are equal, otherwise, the equal sign does not hold. For this specific problem,
it can be seen that the difference is 0, which validates the equal sign.

>> A=sym('a%d%d',5);
B=sym('b%d%d',5); % two arbitrary matrices
simplify(trace(kron(A,B))-trace(A)*trace(B)) % simplify the difference

8.2 · Matrix Analysis
227 8
3. Matrix Ranks
If there are rc linearly independent columns in a matrix, the column rank is defined as
rc . Similarly the row rank can also be defined. It can be shown that the row and column
ranks are equal, which is defined as the rank of the matrix, denoted as rank( A). The
rank of the matrix can be found with the MATLAB function rank().

 Example 8.11
Find the rank for the 4 × 4 magic matrix in Example 8.7.
Solutions Since the determinant of matrix A is zero, the matrix is not a full-rank matrix.
The following commands find the rank of the matrix. It is 3, which is consistent with the
conclusions in Example 8.7.

>> A=magic(4); r=rank(A) % find the rank of magic matrix




 Example 8.12
Find the rank of a 20 × 20 Hilbert matrix.
Solutions The following commands compute the ranks of the matrix, and find the deter-
minant.

>> A=hilb(20); B=sym(A); % generate matrix and convert it to symbolic one


r1=rank(A), r2=rank(B), d=det(B) % find the ranks and determinant
The ranks found are r1 = 13, r2 = 20, and the determinant is

1
d= .
23774547167685345090916442434276164401754198377534864930331853
31234419759310644585187585766816573773440565759867265558971765
63841971079330338658232414981124102355448916615471780963525779
7836800000000000000000000000000000000000

It can be seen that although the determinant is extremely small, it is not zero. Therefore the
matrix is nonsingular, such that the rank is 20 rather than the numerical solution of 13. It
is obvious that the numerical solution is misleading in this example. 

4. Matrix Norms
Matrix norms are the measures of a matrix. Generally, a nonnegative scalar describes
the magnitude of a matrix. Function norm() directly computes the norms. In this
book, norms are effective measures to describe the magnitude of error matrices.

 Example 8.13
Solve the following linear algebraic equation and assess the precision:
⎡ ⎤ ⎡ ⎤
1 4 4 2 2
⎢3 4 4 2⎥ ⎢ ⎥
⎢ ⎥x = ⎢3⎥.
⎣4 1 1 1⎦ ⎣1⎦
2 3 1 4 2
228 Chapter 8 · Linear Algebra and Matrix Analysis

Solutions Linear algebraic equation Ax = b can be solved with the command x = A \ b.


Numerical solutions always yield errors. Substituting the solution back to the original
equation, the error matrix can be found. An error matrix contains may elements, and it is
hard to describe whether the error is large or small. Therefore norms can be adopted to
indicate the magnitude of the error matrices. For this particular problem, the solution is
x = [0.5, 5.125, −3.375, −2.75]T , which yields a norm 3.1086×10−15 of the error matrix.
Therefore it can be seen that the accuracy of the solution is rather high. Also, a scalar norm
is an effective measure to describe the error matrix.

>> A=[1,4,4,2; 3,4,4,2; 4,1,1,1; 2,3,1,4]; b=[2; 3; 1; 2];


x=A\b, norm(A*x-b) % solve equation and assess the error
To pursuit analytical solutions, the solution can be obtained in a symbolic framework. The
new solution found is x = [1/2, 41/8, −27/8, −11/4]T . Substituting it back to the equation,
it can be seen that the norm of the error vector is 0, indicating that the solution is indeed
the analytical solution of the equation.

>> x=sym(A)\b, norm(A*x-b) % analytical solution and assess error




8 5. Characteristic Polynomial and Roots


Introducing an operator s, the characteristic polynomial of matrix A is defined

C(s) = det(s I − A) = sn + c1 sn−1 + c2 sn−2 + · · · + cn−1 s + cn . (8.3)

The coefficient vector c in the descending order of s can be computed with


c =poly( A). If A is a symbolic matrix, function poly() cannot be used, and function
charpoly() should be used instead.

 Example 8.14
Find the characteristic polynomial of the 4 × 4 magic matrix in Example 8.7.
Solutions Two methods compute the characteristic polynomial coefficients, and the results
are c1 ≈ c2 = [1, −34, −80, 2720, 0]. There are errors in the numerical results, where the
error norm is 2.6231×10−12 .

>> A=magic(4); c1=poly(A) % generate magic matrix and find the polynomial
B=sym(A); c2=charpoly(B), d=double(norm(c1-c2))


 Example 8.15
For the vector B = [a1 , a2 , a3 , a4 , a5 ], construct a Hankel matrix and compute its charac-
teristic polynomial.
Solutions Hankel matrix A can be generated first, then function charpoly( A,x) finds the
polynomial. Function collect() performs like term collection.

>> syms x; a=sym('a%d',[1,5]); A=hankel(a); % generate the matrix


collect(charpoly(A,x),x) % collect like terms in characteristic polynomial
8.2 · Matrix Analysis
229 8
The characteristic polynomial can be written as

det(x I − A) = x5 + (−a3 −a5 −a1 )x4 + (a5 a1 +a3 a1 +a5 a3 −2a42 −2a52 −a22 −a32 )x3 +
(2a53 −a1 a3 a5 −2a2 a4 a3 +a22 a5 +a1 a42 +a33 +a1 a52 +a3 a52 +a5 a42 +a42 a3 −2a2 a5 a4 )x2 +
(2a2 a52 a4 + a44 + a54 + a32 a52 + a52 a42 − 3a3 a5 a42 − a1 a53 − a3 a53 )x − a55 .

When the characteristic polynomial coefficient vector c is found, function roots()


finds the roots of the polynomial equation, that is, the eigenvalues. The eigenvalues
can also be computed with eig() function. The two results are identical.

 Example 8.16
Compute the eigenvalues of the matrix in Example 8.7.
Solutions The characteristic polynomial vector can be found. The eigenvalues can be found
with roots()√or eig() functions. Under symbolic framework, the eigenvalues can be found
as [0, 34, ±4 5].

>> A=sym(magic(4)); r=roots(charpoly(A)), eig(A)




8.2.2 Inverse Matrices


For a given n × n nonsingular square matrix A, if there exists a matrix C of the same
size, satisfying
AC = C A = I, (8.4)
where I is an identity matrix, then C is referred as the inverse matrix of A, denoted as
C = A−1 . Note that inverse matrices exist only for square matrices. Function inv()
finds the inverse matrix directly.

 Example 8.17
Find the inverse matrix for any 4 × 4 Hankel matrix
Solutions MATLAB inverse function applies also to matrices with variables. An arbitrary
4 × 4 Hankel matrix can be generated directly. Then function inv() can be called to find
its inverse.

>> a=sym('a',[1,4]); H=hankel(a); % generate a Hankel matrix


inv(H) % matrix inverse
from which the inverse matrix is found
⎡ ⎤
0 0 0 1/a4
⎢ 0 0 1/a4 −a3 /a42 ⎥
H −1 = ⎢
⎣ 0
⎥.

1/a4 −a3 /a42 (a32 − a2 a4 )/a43
1/a4 −a3 /a42 (a3 − a2 a4 )/a43
2 −(a1 a42 − 2a2 a3 a4 + a33 )/a44


230 Chapter 8 · Linear Algebra and Matrix Analysis

An inverse matrix can also be evaluated using the reduced row echelon form
method. The specific method is to construct a matrix C = [ A, I], then find its reduced
row echelon form. If the left side of C matrix is an identity one, the remaining part of
the matrix is the inverse matrix. Reduced row echelon form of a matrix can be found
directly with function rref().

 Example 8.18
For the matrix given in Example 8.17, compute the inverse matrix again with reduced row
echelon form.
Solutions With the above ideas, the inverse matrix can be evaluated again.

>> a=sym('a',[1,4]); H=hankel(a);


C=[H eye(4)]; D=rref(C), B=D(:,5:end) % compute inverse again
The reduced row echelon form can be obtained as follows. It can be seen that the left side
is an identity matrix. Therefore the right side is the inverse, which is the same as the one
obtained earlier.
⎡ ⎤
1 0 0 0 0 0 0 1/a4
8 ⎢0 1 0 0 0 0 1/a4 −a3 /a42 ⎥
D=⎢
⎣0
⎥.

0 1 0 0 1/a4 −a3 /a42 (a32 − a2 a4 )/a43
0 0 0 1 1/a4 −a3 /a42 (a3 − a2 a4 )/a43
2 2 3 4
−(a1 a4 − 2a2 a3 a4 + a3 )/a4

 Example 8.19
Consider the singular matrix in Example 8.7. If inv() function is used, what will happen?
Solutions With the following commands, the inverse matrix function can be tried.

>> A=magic(4); B=inv(A), C=B*A-eye(4) % find the inverse and evaluate the error
The inverse matrix and the error matrix can be found as follows. It can be seen that the
error matrix is not a zero matrix. The magnitude of the error is too large. Therefore the
inverse matrix is meaningless.
⎡ ⎤
−0.2649 −0.7948 0.7948 0.2649
⎢ −0.7948 −2.3843 2.3843 0.7948 ⎥

B=⎣ ⎥ × 1015 ,
0.7948 2.3843 −2.3843 −0.7948 ⎦
0.2649 0.7948 −0.7948 −0.2649
⎡ ⎤
0.875 −0.5 0.5 0.9688
⎢ −0.5 3 4 2.875 ⎥

C=⎣ ⎥.
1.5 0 −1 1.375 ⎦
0.125 0.5 0.5 0.03125
If the inverse is taken under symbolic framework, the elements found are all inf. Therefore
the solution process failed.

>> inv(sym(A)) % compute inverse with symbolic method



8.2 · Matrix Analysis
231 8

 Example 8.20
Find the inverse of the matrix in Example 8.7 with reduced row echelon form.
Solutions Assign an identity matrix to the right of the original matrix, then carry out
reduced row echelon form.

>> A=sym(magic(4)); A1=rref([A,eye(4)]) % get row reduced echelon form


The reduced row echelon form can be found as follows. Since the original matrix is singular,
it can be seen that the left side of the matrix is not an identity one. Therefore there is no
inverse matrix exist.
⎡ ⎤
1 0 0 1 0 −21/136 25/136 1/34
⎢0 1 0 3 0 111/136 −35/136 −15/34 ⎥
A1 = ⎢
⎣0
⎥.
0 1 −3 0 −49/68 13/68 8/17 ⎦
0 0 0 0 1 3 −3 −1

8.2.3 Moore–Penrose Generalized Inverses


It has been stated that even with symbolic methods, the inverse of a singular matrix
cannot be obtained, since it does not exist. Besides, there are no inverse matrices for
rectangular matrices. In some applications, the matrix inverse problems do exist. A
new “inverse matrix” is needed, and the inverse is generalized inverse matrix.
For a given matrix A, there exists a unique matrix M, such that all the following
three conditions are satisfied simultaneously:
(1) AM A = A;
(2) M AM = M;
(3) AM and M A are all Hermitian symmetrical matrices.
Matrix M is referred to as the Moore−Penrose generalized inverse of matrix A,
also known as pseudoinverse, denoted as M = A+ . Moore−Penrose inverse M is
the one such that the error || AM − I|| is minimized. Moore−Penrose inverse can be
evaluated directly with a function pinv().

 Example 8.21
Find the Moore−Penrose inverse of the singular matrix in Example 8.7.
Solutions Function inv() in the Symbolic Math Toolbox cannot be used to find the
analytical solution of the inverse of a matrix, since the solution does not exist. Therefore,
Moore−Penrose inverse is needed.

>> A=magic(4); B=pinv(A), A*B % find pseudoinverse


The matrices B and AB can be found, respectively,
⎡ ⎤
0.1011 −0.0739 −0.0614 0.0636
⎢ −0.0364 0.0386 0.0261 0.0011 ⎥
B=⎢
⎣ 0.0136
⎥,
−0.0114 −0.0239 0.0511 ⎦
−0.0489 0.0761 0.0886 −0.0864
232 Chapter 8 · Linear Algebra and Matrix Analysis

⎡ ⎤
0.95 −0.15 0.15 0.05
⎢ −0.15 0.55 0.45 0.15 ⎥

AB = ⎣ ⎥.
0.15 0.45 0.55 −0.15 ⎦
0.05 0.15 −0.15 0.95
It can be seen that the product AB is no longer an identity matrix, since there is not one
such that it is an identity matrix. The matrix A+ is the matrix such that the norm of the
error matrix is minimized. 

 Example 8.22
Find the pseudoinverse of the rectangular matrix A.
⎡ ⎤
6 1 4 2 1
A=⎣ 3 0 1 4 2⎦.
−3 −2 −5 8 4

Solutions The following commands analyze the matrix, and the rank of 2 is found.

>> A=[6,1,4,2,1; 3,0,1,4,2; -3,-2,-5,8,4]; rank(A) % find matrix rank


8 Since A matrix is a singular one, therefore function pinv() is used to find out the Moore−
Penrose inverse. The following commands validate all the conditions for the Moore−
Penrose inverse. It can be seen that the generalized inverse does satisfy all the conditions.

>> pinv(sym(A)), iA=pinv(A) % find pseudoinverse and validate the conditions


The pseudoinverse can be found
⎡ ⎤ ⎡ ⎤
183/2506 207/5012 −111/5012 0.073 0.0413 −0.0221
⎢ 27/2506 5/2506 −39/2506 ⎥ ⎢ 0.0108 0.002 −0.0156 ⎥
⎢ ⎥ ⎢ ⎥
A+ = ⎢
⎢ 115/2506 89/5012 −193/5012 ⎥ ⎢
⎥ ≈ ⎢ 0.0459 0.0178 −0.0385 ⎥
⎥.
⎣ 41/1253 54/1253 80/1253 ⎦ ⎣ 0.0327 0.0431 0.0638 ⎦
41/2506 27/1253 40/1253 0.0164 0.0215 0.0319

8.2.4 Eigenvalues and Eigenvectors


For matrix A, if there exists a nonzero vector x and a scalar λ, satisfying

Ax = λx, (8.5)

then λ is referred to as an eigenvalue of A, x is the corresponding eigenvector of λ.


Eigenvalues and eigenvectors can be obtained with function eig(), with
d=eig( A), % eigenvalues only
[V , D]=eig( A), % eigenvalues and eigenvectors
where d is the vector containing all the eigenvalues, D is a diagonal matrix, whose
diagonal elements are the eigenvalues of A. Each column of V is the eigenvector of
the corresponding eigenvalues. The eigenvalue matrices satisfy AV = V D, and also
8.3 · Matrix Transform and Decomposition
233 8
the eigenvectors are normalized, that is the squared sum of the elements is normalized
to 1. If the function returns only one argument, it is the column vector composed of
all the eigenvalues of A. Even though A is a complex matrix, function eig() can also
be used to find the eigenvalue and eigenvector matrices.

 Example 8.23
Compute the eigenvalues and eigenvectors of the matrix in Example 8.7.
Solutions Function eig() finds the eigenvalues 34, ±8.9443, −2.2348×10−15 .

>> A=[16 2 3 13; 5 11 10 8; 9 7 6 12; 4 14 15 1];


[v,d]=eig(A), norm(A*v-v*d) % use numerical methods in computation
The eigenvalues and eigenvectors are obtained as below, with error of 1.2284×10−14 .
⎡ ⎤
−0.5 −0.8236 0.3764 −0.2236
⎢ −0.5 0.4236 0.0236 −0.6708 ⎥
v=⎢
⎣ −0.5
⎥,
0.0236 0.4236 0.6708 ⎦
−0.5 0.3764 −0.8236 0.2236
⎡ ⎤
34 0 0 0
⎢ 0 8.9443 0 0 ⎥
d=⎢
⎣ 0
⎥.

0 −8.9443 0
0 0 0 −2.2348×10 −15

Function eig() is also supported in symbolic framework. Theoretically it applies to


any matrices.
√ For a given matrix A, the following command finds the exact eigenvalues
0, 34, ±4 5:

>> [v,d]=eig(sym(A)) % analytical solutions of eigenvalues and eigenvectors


The matrices found are as follows. Note that the eigenvector matrix is not normalized in
symbolic computation.
⎡ √ √ ⎤ ⎡ ⎤
−1 1 12 5/31 −√41/31 −12
√ 5/31 − 41/31
0 0 0 0
⎢ −3 1 8 √5/31 + 17/31 ⎥ ⎢0 0 ⎥
√ − 8 5/31
17/31 34 0√
v=⎢
⎣ 3 1
⎥, d = ⎢ ⎥.
−4 5/31 − 7/31 4 5/31 − 7/31 ⎦ ⎣0 0 −4 5 0 ⎦

1 1 1 1 0 0 0 4 5

8.3 Matrix Transform and Decomposition


Matrix transformations and decomposition are very important in matrix analysis.
Normally a transformation method can be introduced such that an ordinary matrix
can be made into a simpler form, or factorized into the product of two or several special
matrices. The commonly used transformations and factorization methods provided
in MATLAB are shown in . Table 8.3.
In this section, similarity transformation is introduced first. Then the transforma-
tion to companion and Jordanian matrices are presented. Finally the triangular fac-
torization, Cholesky factorization and singular value decomposition are illustrated.
234 Chapter 8 · Linear Algebra and Matrix Analysis

. Table 8.3 Commonly used factorizations and transformations

Factorizations Syntaxes and descriptions

Jordanian transform [T , J] = jordan( A) transforms a matrix A into a Jordanian matrix


J, the returned T is the transformation matrix, such that
T −1 AT = J

LU factorization [L, U] = lu( A) factorizes A into the product of a lower-triangular


matrix L and an upper one U, that is A = LU

Cholesky factorization [ D, p] = cholesky( A) carries out Cholesky factorization for


symmetrical matrices, where D satisfy DT D = A, an upper-triangular
matrix. If A is not positive-definite, then p is nonzero

QR factorization [ Q, R] = qr( A) performs QR factorization of A, with a orthogonal


matrix Q and an upper-triangular matrix Q, such that A = Q R

SVD [U, Σ, V ] = svd( A) performs singular value decomposition, where


Σ is a diagonal matrix of singular values, U and V are orthogonal
matrices

8 8.3.1 Similarity Transforms


For a given square matrix A, if there exists a nonsingular matrix T , such that the
original matrix A can be transformed into

X = T −1 AT , (8.6)

the transformation is referred to as similarity transformation, and T is the transfor-


mation matrix. After similarity transforms, the important properties such as rank,
trace, determinant, characteristic polynomial and eigenvalues of X are not affected,
they are the same as the ones in A.
If the transformation matrix is T , commands X=inv(T ) * A * T or X =T \ A * T
computes the transformation result immediately.
The crucial step in matrix transformation is how to select a matrix T , such that the
arbitrary matrix A can be deliberately transformed into the special form. For instance,
to companion matrix or diagonal matrix and so on. Transformation methods will be
explored later.

8.3.2 Companion Matrix Transforms


For matrix A, if there exists a column vector x, such that T = x, Ax, · · · , An−1 x
matrix is nonsingular, then matrix A can be converted into a companion form through
similarity transformation.
There are infinite numbers of transformation matrices T like this. The transformed
result X is unique. To select such a transformation matrix in MATLAB, loop structure
can be used to find such an x vector, with elements 0’s, 1’s or other simple values,
such that the generated T is a full-rank matrix. In the example next, the selection of
transformation matrices is demonstrated.
8.3 · Matrix Transform and Decomposition
235 8

 Example 8.24
For the magic matrix in Example 8.7, find a transformation matrix such that it can be
transformed into a companion matrix.
Solutions The following commands find a transformation matrix, from which the original
matrix can be transformed into a companion form.

>> A=magic(4); % input the matrix


while(1) % find a transformation matrix in a loop
x=randi([0,1],[4,1]); T=sym([x A*x A^2*x A^3*x]);
if rank(T)==4, break; % construct the full rank integer matrix
end, end, T, X=inv(T)*A*T % perform similarity transform
The transformation matrix and transform result are as follows:
⎡ ⎤ ⎡ ⎤
0 13 273 10186 0 0 0 0
⎢0 8 281 9786 ⎥⎥ ⎢1 0 0 −2720 ⎥
T =⎢
⎣ 0 12 , X =⎢ ⎥.
257 10106 ⎦ ⎣0 1 0 80 ⎦
1 1 345 9226 0 0 1 34

It can be seen that the expected transformation target is completed. It should be noted that
there are other T matrices generated using the same code, but X matrix is the same. 

8.3.3 Transforming Matrices into Diagonal or Jordanian Ones


To transform a given matrix into a diagonal one through similarity transform, the
eigenvalues and eigenvectors must be computed with [V , D]=eig( A). If matrix V
obtained is of full rank, the matrix V can be selected as the similarity transformation
matrix. Therefore matrix D is the expected diagonal matrix.
Of course, there are conditions such that V is a full-rank matrix, since all the
eigenvalues of matrix A must be distinct, such that V is a full-rank one. Therefore the
matrix A can be transformed into a diagonal matrix if and only if all the eigenvalues
of A are distinct.
If there are repeated eigenvalues in matrix A, it is not possible to transform it
into a diagonal one. Therefore, Jordanian matrix is the next choice, with the
syntax [T , J]=jordan( A). The returned T is the transformation matrix, and J is
the transformed Jordanian form.

 Example 8.25
Transform the following matrix into a diagonal one through similarity transformation:
⎡ ⎤
−9 −1 −6 −1
⎢ −4 −7 −5 −2 ⎥
A=⎢
⎣ 5
⎥.
2 1 2⎦
8 3 11 −2

Solutions The following commands can be tried for diagonalization to matrix A:


236 Chapter 8 · Linear Algebra and Matrix Analysis

>> A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


[V,D]=eig(A) % direct diagonalization
while the diagonalized matrix is
⎡ ⎤
−2 0 0 0
⎢ 0 −4.999998 + 3.43×10−6 j 0 0 ⎥
D=⎢
⎣ 0
⎥.

0 −4.999998 − 3.43×10−6 j 0
0 0 0 −5.000004

Unfortunately the above result is not correct. As in other double precision solvers, there may
exist large errors in computing eigenvalues, when there are repeated ones. This phenomenon
is inevitable under double precision framework. To solve the problem, the computation
should be carried out in the symbolic framework, such that reliable solutions can be found.

>> [V,D]=eig(sym(A)) % find the eigenvalues and eigenvectors symbolically


therefore the transformation matrix V and eigenvalues D can be found.
⎡ ⎤ ⎡ ⎤
−1/2 0 −2 0 0 0
⎢ −1/2 −1 ⎥ ⎢ 0⎥
⎥ , D = ⎢ 0 −5 0
8 ⎢
V =⎣
1/2 0⎦ ⎣ 0 0 −5 0⎦
⎥.

1 1 0 0 0 −5

It can be seen that the eigenvalue −5 is a triple one, such that V matrix has only two
columns. Therefore diagonalization is not possible with such a matrix. In other words,
there is not any transformation matrix such that A can be transformed into a diagonal one.


 Example 8.26
Find the Jordanian transform for the matrix A in Example 8.25.
Solutions Carry out Jordanian transform with the following commands:

>> A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


[T,J]=jordan(sym(A)), J1=inv(T)*A*T % transform matrix into Jordanian form
the transformation and Jordanian matrices are as follows. The transformed result J 1 is the
same as J. The 3 × 3 submatrix at the lower-right corner is a Jordanian block.
⎡ ⎤ ⎡ ⎤
−2 0 2 3 −2 0 0 0
⎢ −2 1 2 2⎥ ⎢ 0 −5 1 0⎥
T =⎢
⎣ 2
⎥ , J1 = J = ⎢ ⎥.
0 −1 −2 ⎦ ⎣ 0 0 −5 1⎦
4 −1 −4 −4 0 0 0 −5

8.3.4 Triangular Factorizations


The triangular factorization, also known as LU factorization, is to factorize an ordi-
nary matrix into the product of two matrices, one is the lower-triangular matrix L,
8.3 · Matrix Transform and Decomposition
237 8
and the other is an upper-triangular matrix U, such that A = LU, where L and U
matrices can be, respectively, written as
⎡ ⎤ ⎡ ⎤
1 u11 u12 ··· u1n
⎢ l21 1 ⎥ ⎢ u22 ··· u2n ⎥
L=⎢
⎣ ... .. .. ⎥, U = ⎢
⎦ ⎣ .. .. ⎥ . (8.7)
. . . . ⎦
ln1 ln2 ··· 1 unn

Function [L,U]=lu( A) carries out LU factorization. In the double precision


lu() function, pivot-based algorithm is used, such that [L,U]=lu( A) command
may not yield a genuine lower-triangular matrix L. The correct form is [L,U, P]=
lu( A), where P is a permutation matrix, such that A = P −1 LU.

 Example 8.27
Consider again the LU factorization problem for the matrix in Example 8.7. Call the lu()
function in numerical and symbolical format and compare the results.
Solutions Input A matrix, and find the LU factorization matrices.

>> A=magic(4); [L1,U1]=lu(sym(A)) % use symbolic method for LU factorization


The factorized matrices are
⎡ ⎤ ⎡ ⎤
1 0 0 0 16 2 3 13
⎢ 5/16 1 0 0⎥ ⎢ 0 83/8 145/16 63/16 ⎥
L=⎢
⎣ 9/16
⎥, U = ⎢ ⎥.
47/83 1 0⎦ ⎣ 0 0 −68/83 204/83 ⎦
1/4 108/83 −3 1 0 0 0 0

With numerical methods, the following commands can be issued:

>> [L,U,P]=lu(A), A1=inv(P)*L*U % triangular decomposition


The factorized matrix is as follows. The matrix A1 restores the original A matrix.
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
1 0 0 0 16 2 3 13 1 0 0 0
⎢ 0.25 1 0 0⎥⎥ ⎢ 0 13.5 14.25 −2.25 ⎥ ⎢0 0 0 1⎥
L=⎢
⎣ 0.5625 0.4352 1 , U =⎢ ⎥, P = ⎢ ⎥.
0⎦ ⎣ 0 0 −1.9 5.67 ⎦ ⎣0 0 1 0⎦
0.3125 0.7685 1 1 0 0 0 1.3×10−15 0 1 0 0

8.3.5 Cholesky Factorization of Symmetrical Matrices


If A is a symmetrical matrix. With the characteristic of symmetrical matrices, a similar
factorization method to LU method can be used, such that the original matrix A is
decomposed as
238 Chapter 8 · Linear Algebra and Matrix Analysis

⎡ ⎤⎡ ⎤
l11 l11 l21 ··· ln1
⎢ l21 l22 ⎥⎢ l22 ··· ln2 ⎥
A = LL = ⎢
T
⎣ ... .. .. ⎥⎢
⎦⎣ .. .. ⎥ . (8.8)
. . . . ⎦
ln1 ln2 ··· lnn lnn
Function chol() finds Cholesky factorization matrix D, which yields an upper-
triangular matrix, with the syntax [ D,p]=chol( A), where D = L T . If A is not a
positive-definite one, p does not equal to matrix size n. Therefore, the method judges
whether A is a positive-definite matrix or not. If p is not returned, then when D is not
full-rank matrix, the matrix is not positive-definite.

 Example 8.28
Find the Cholesky factorization to the symmetrical matrix A.
⎡ ⎤
9 3 4 2
⎢3 6 0 7⎥
A=⎢
⎣4
⎥.
0 6 0⎦
8 2 7 0 9

Solutions Executing the following commands in symbolic framework, the Cholesky fac-
torization of A can be found, to yield matrix D.

>> A=[9,3,4,2; 3,6,0,7; 4,0,6,0; 2,7,0,9];


D=chol(A), D1=chol(sym(A))
The numerical and analytical solutions can be found as
⎡ ⎤ ⎡ ⎤
3 1 1.3333 0.6667 3 √1 √4/3 2/3

⎢ 0 2.2361 −0.5963 2.8324 ⎥ ⎢ 5 √−4 √5/15 ⎥

D=⎣ ⎥ , D1 = ⎢ 0 √19 √5/15 ⎥ .
0 0 1.9664 0.4068 ⎦ ⎣0 0 15 58/15 2 √15√58/145 ⎦
0 0 0 0.6065 0 0 0 4 2 87/87

 Example 8.29
Judge whether the symmetrical matrix A is positive-definite or not. Carry out Cholesky
factorization to the matrix. ⎡ ⎤
7 5 5 8
⎢5 6 9 7⎥
A=⎢ ⎣5 9 9 0⎦.

8 7 0 1

Solutions The following commands carry out Cholesky factorization to matrix A, which
yields D matrix, with order of 2, which indicates that the matrix is not positive-definite,
since p  = 0.

>> A=[7,5,5,8; 5,6,9,7; 5,9,9,0; 8,7,0,1];


[D,p]=chol(A) % check whether the matrix is positive-definite
8.3 · Matrix Transform and Decomposition
239 8
The positive-definite submatrix D obtained is as follows, where p = 3  = 0, indicating the
positive-definite submatrix is a 2 × 2 one, which is the same as the conclusion obtained
earlier.
2.6458 1.8898
D= .
0 1.5584
If matrix A is not positive-definite, symbolic manipulation using chol() function may not
solve Cholesky factorization problem well. Function cholsym() provided in Reference [1]
solves well the Cholesky factorization problem.

>> D=cholsym(sym(A)) % Cholesky factorization


where the obtained Cholesky matrix is shown below. Note that, since matrix A is not a
positive-definite one, matrix D contains complex terms.
⎡√ √ √ √ ⎤
7 √5 √7/7 √5 √7/7 √ 8√ 7/7
⎢ 0 7 17/7 38 9√ 7√17/119 ⎥
D=⎢ √ 7√ 17/119 ⎥.
⎣ 0 0 17 114 j/17 73 √17 √114 j/969 ⎦
0 0 0 2 31 57/57

8.3.6 Singular Value Decomposition


The concept of singular values is introduced in numerical linear algebra. They can be
regarded as a measure of a matrix. Assume that A matrix is an n × m matrix, then A
can be decomposed as
A = L A1 M T , (8.9)
where A1 = diag(σ1 , · · · , σp ) is an n × m diagonal matrix, whose diagonal elements
satisfying the inequalities σ1 ≥ · · · ≥ σp ≥ 0, p = min(n, m). L and M are, respectively,
n×n and m×m orthogonal matrices. If σp = 0, then matrix A is a singular matrix. The
rank of matrix A equals the number of nonzero elements in matrix A1 . Orthogonal
matrix Q satisfies the condition Q H Q = Q Q H = I, where I is an identity matrix.
Function svd() performs singular value decomposition, with the syntaxes
S=svd( A) % compute singular values only
[L, A1 ,M]=svd( A) % compute singular value and transformation matrices
where A is the original matrix. The returned A1 is a diagonal matrix, while L and M
are, respectively, orthogonal matrices.
The size of the singular values determines the characteristics of the matrices. If the
singular values change significantly, a slight variation in an element in the matrix may
affect the properties of the matrix. Such a matrix is referred to as a bad-conditioned
matrix. If there exist zero singular values, the matrix is a singular one.
The ratio of the maximum singular value σmax to the minimum singular value
σmin is referred to as the condition number, denoted as cond( A), that is cond( A) =
σmax /σmin . The condition number of matrix A can be evaluated directly with cond( A)
command. If the condition number is too large, symbolic computing is recommended,
otherwise misleading results can be found.
240 Chapter 8 · Linear Algebra and Matrix Analysis

 Example 8.30
Perform singular value decomposition to the singular matrix A in Example 8.7.
Solutions Call the function svd(), the matrices L, A1 and M can be found. The condition
number can also be found as 4.7133×1017 .

>> A=magic(4); [L,A1,M]=svd(A), cond(A) % SVD and condition number


The decomposed matrices are
⎡ ⎤ ⎡ ⎤
−0.5 0.6708 0.5 −0.2236 34 0 0 0
⎢ −0.5 −0.2236 −0.5 −0.6708 ⎥ ⎢ 0 17.8885 0 0 ⎥
L=⎢
⎣ −0.5
⎥ , A1 = ⎢ ⎥,
0.2236 −0.5 0.6708 ⎦ ⎣ 0 0 4.4721 0 ⎦
−0.5 −0.6708 0.5 0.2236 0 0 0 7.2×10−17

⎡ ⎤
−0.5 0.5 0.6708 −0.2236
⎢ −0.5 −0.5 −0.2236 −0.6708 ⎥

M=⎣ ⎥.
−0.5 −0.5 0.2236 0.6708 ⎦
−0.5 0.5 −0.6708 0.2236
Since one of the singular value is 0, the original matrix is singular. The condition number
can be found with cond( A) command, which yields ∞. Under double precision operations
8 there are some erroneous. If A matrix is converted into a symbolic one, function svd() can
be called to find singular decomposition matrices with higher precision. 

8.4 Matrix Functions


Matrix functions are important in linear algebra. They are used in many fields in
science and engineering. Unfortunately matrix functions are completely ignored in
classical linear algebra courses.
The topic of matrix function has many different meanings [2]. The following defi-
nition is adopted here. If there is a scalar function f (x) and a complex square matrix
A, if the independent variable x is substituted by matrix A, f ( A) is the matrix of the
same size, then f ( A) is referred to as a matrix function. In normal cases, variable x is
substituted by matrix A, while the scalar is substituted by an identity matrix I. Scalar
function f (x) is rewritten as a matrix function f ( A).
In this section, matrix exponential function is presented first. Matrix trigonomet-
ric functions are then discussed, followed by the computation of arbitrary matrix
functions.

8.4.1 Matrix Exponential Functions


Before introducing matrix exponential function, the Taylor series expression of the
exponential function ex is given first.

 1 i 1 1 1 m
ex = x = 1 + x + x2 + x3 + · · · + x + ··· . (8.10)
i! 2! 3! m!
i=0
8.4 · Matrix Functions
241 8
If variable x is substituted by matrix A, and the constant is replaced by an identity
matrix, the exponential matrix function is defined.

 1 i 1 1 1 m
e =
A
A = I + A + A2 + A3 + · · · + A + ··· . (8.11)
i! 2! 3! m!
i=0

Function expm() evaluates directly exponential matrix function. The use of the
function is demonstrated in the example.

 Example 8.31
For A matrix in Example 8.25, compute the exponential matrices e A and e At .
Solutions Input matrix A, numerical and analytical methods can be used to compute matrix
exponentials.

>> syms t; A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


F1=expm(A), F2=expm(A*t) % compute exponential matrix function
The numerical solution of e A is
⎡ ⎤
−0.2370 −0.1151 −0.2572 −0.1151
⎢ −0.2403 −0.1118 −0.2505 −0.1185 ⎥

F1 = ⎣ ⎥,
0.2505 0.1219 0.2639 0.1219 ⎦
0.4841 0.2336 0.5077 0.2403

and the analytical solution of e At is



e−5t (2t + 3) − 2e−2t e−5t (2t + 1) − e−2t
⎢ e−5t (4t + t2 + 4)/2 − 2e−2t e−5t (2t + t2 + 4)/2 − e−2t
F2 = ⎢
⎣ ,
−e−5t (t + 2) + 2e−2t −e−5t (t + 1) + e−2t
−e−5t (8t + t2 + 8))/2 + 4e−2t −e−5t (6t + t2 + 4)/2 + 2e−2t


−2 exp−5t +e−2t e−5t (2t + 1) − e−2t
e−5t (t + 2) − 2e−2t ⎥
e−5t (2t + t2 + 2)/2 − e−2t
⎥.
2e−2t − e−5t −e−5t (t + 1) + e−2t⎦
−5t
−e (t + 4) + 4e −2t −5t 2
−e (6t + t + 2))/2 + 2e −2t

8.4.2 Matrix Trigonometric Functions


The sinusoidal matrix function sin A and cosine function cos A are defined as

 A2k+1 1 1
sin A = (−1)k = A − A3 + A5 + · · · , (8.12)
(2k + 1)! 3! 5!
k=0

1 2 1 1 (−1)n 2n
cos A = I − A + A4 − A6 + · · · + A + ··· . (8.13)
2! 4! 6! (2n)!
242 Chapter 8 · Linear Algebra and Matrix Analysis

There are no existing trigonometric matrix function evaluation tools in the cur-
rent version of MATLAB. The function funm() can be used directly to compute
trigonometric matrix functions or other matrix functions, with the syntax
A1 =funm( A,func_name), % for instance, B=funm( A,@sin)
where func_name is a function handle, or a string. In recent versions of MAT-
LAB, even more complicated matrix functions such as sin At can be evaluated with
funm( A*t,'sin') or funm( A*t,@sin).
In fact, the well-known Euler’s formulas ej A = cos A + j sin A and e−j A = cos A −
j sin A can also be used to find

1 jA  1 jA 
sin A = e − e−j A , cos A = e + e−j A . (8.14)
j2 2

Therefore with the well-established expm() function, trigonometric matrix func-


tions can also be found.

8 8.4.3 Arbitrary Matrix Functions


Apart from the transcendental functions in . Table 2.4, the functions abs(), sqrt()
and sign() can also be used. In the function call in funm(), these functions can be
called directly.

 Example 8.32
Consider the A matrix in Example 8.25, compute ψ( A) = e A cos At .
Solutions This is a complicated composite function. Consider the nested relationship in the
ψ(·) function, the following commands evaluate the needed matrix function:

>> A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


syms t; F=expm(A*funm(A*t,@cos)), F(1,1) % direct computing
The result obtained is rather lengthy, which is not displayed here. Only the element in the
upper-left corner can be found

ψ1,1 = 3e−5 cos 5t − 2e−2 cos 2t + 2 cos 5te−5 cos 5t − 10t sin 5te−5 cos 5t .

A Jordanian transform-based solver funmsym() is written in Reference [3], with


the syntax A1 =funmsym( A,funx,x), where x is the symbolic independent variable,
funx is the prototype function of x. More complicated matrix function can be com-
puted with such a function.
8.5 · Exercises
243 8

 Example 8.33
Call funmsym() function to compute the matrix function in Example 8.32.
Solutions It can be seen from the matrix function e A cos At that, the prototype function of
the matrix function can be written as exp(x*cos(x*t)), and use x to express the matrix
A. Therefore the following commands can be used to compute again the matrix function.
It can be seen that the format of the two matrices is different, but they are equivalent. In
fact, the matrix obtained here is simpler.

>> A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


syms t x; F=funmsym(A,exp(x*cos(x*t)),x), F(1,1)


 Example 8.34
Consider the matrix A in Example 8.25, compute k A , k > 0.
Solutions Input the matrix A, the following two methods can be used to compute k A . The
two solutions are equivalent.

>> A=[-9,-1,-6,-1; -4,-7,-5,-2; 5,2,1,2; 8,3,11,-2];


syms k positive; % declare k as a positive symbolic variable
F1=simplify(k^A), F2=funmsym(A,k^x,x), simplify(F1-F2)
The matrix F 1 is complicated, and matrix F 2 is
⎡ ⎤
2 lnk − 2k 3 + 3 2 lnk − k 3 + 1 2 − 2 ∗ k3 2 lnk − k 3 + 1
⎢ 2 2 2 ⎥
⎢ 2 lnk+ ln k −2k 3 + 2 lnk+ ln k −k 3 +2 lnk − 2k 3 + 2 lnk + ln k − k 3 + 1 ⎥
1 ⎢ ⎥
F2 = 5 ⎢ 2 2 2 ⎥.
k ⎢⎢ 2k 3 − lnk − 2 k 3 − lnk − 1 2k 3 − 1 k 3 − lnk − 1 ⎥

⎣ ln2 k ln2 k ln2 k ⎦
4k 3 − −4 lnk−4 2k 3 − −3 lnk−2 4k 3 −lnk−4 2k 3 − −3 lnk−1
2 2 2

8.5 Exercises
(1) Test what is the data type of A, after the execution of the following commands:
>> syms A, A=5
(2) Generate a diagonal matrix whose diagonal elements are a1 , a2 , · · · , a12 .
(3) Test from the display format, and find which one is in double precision format,
and which one is in symbolic format. If A is a numeric matrix while B is a
symbolic one, what is the data type of their product C = A*B? Validate the
judgement through a simple example.
(4) Generate standard uniform distributed pseudorandom vector with 30000 val-
ues. Find the mean and variance. Also draw its histogram.
(5) Given c =[−4,−3,−2,−1,0,1,2,3,4], generate, respectively, the diagonal,
Hankel, Vandermonde and companion matrices.
(6) Write an M-function to generate n × n Wilkinson matrix.
244 Chapter 8 · Linear Algebra and Matrix Analysis

(7) Generate a 9 × 9 magic matrix, and observe the trend of 1 → 2 → · · · → 80 →


81.
(8) Generate a 15 × 15 random matrix, with elements 0 and 1 only, and the deter-
minant is 1.
(9) Input the following 20 × 20 matrix, without loops:
⎡ ⎤
x a a ··· a
⎢a x a ··· a⎥
⎢ ⎥
A=⎢
⎢ a. a x ··· a⎥⎥.
⎣ .. .. .. ..
. . . a⎦
a a a ··· x

(10) Compute the determinants of the following matrices:


⎡ ⎤ ⎡ x ⎤
sin α cos α sin(α + δ) (a + a−x )2 (ax − a−x )2 1
A = ⎣ sin β cos β sin(β + δ) ⎦ , B = ⎣ (by + b−y )2 (by − b−y )2 1⎦.
sin γ cos γ sin(γ + δ) (cz + c−z )2 (cz − c−z )2 1

8 (11) Compute the determinant of the Vandermonde matrix, and display it in the
simplest form. ⎡ 4 ⎤
a a3 a2 a 1
⎢ b4 b3 b2 b 1⎥
⎢ ⎥
A=⎢ ⎢c
4 c3 c2 c 1⎥⎥.
⎣ d4 d3 d2 d 1⎦
e4 e3 e2 e 1
(12) For the n × n matrices described as follows, find their determinants.
 
 n −1 0 0 ··· 0 0 

n − 1 x −1 0 ··· 0 0 

n − 2 0 x −1 ··· 0 0 
 . .. .. .. .. . ..  .
 .. . . . . .. .

 2 0 0 0 ··· x −1 

 1 0 0 0 ··· 0 x

(13) Verify that the even sized magic matrices (the size is less than 100) are singular
ones.
(14) Select some sizes n. Generate random matrices in symbolic form, and find its
inverse matrix. Record the time, and find out the time elapse.
(15) Find the characteristic polynomial for the n × n matrix in Exercise (5).
(16) Wilkinson matrices are interesting test matrices. Observe the 15 × 15 Wilkinson
matrix and find the difference between its two largest eigenvalues. Observe the
largest eigenvalues of a 30 × 30 Wilkinson matrix.
(17) Select a finite n, for instance n = 50, validate that the following matrix has
characteristic polynomial sn − a1 a2 · · · an .
8.5 · Exercises
245 8
⎡ ⎤
0 a1 0 ··· 0
⎢0 0 a2 ··· 0 ⎥
⎢ . .. .. .. .. ⎥
A=⎢
⎢ .
. . . . . ⎥
⎥.
⎣0 0 0 ··· a ⎦
n−1
an 0 0 ··· 0

(18) Judge whether the following matrices are positive-definite ones or not. If they
are, find out their Cholesky factorized form.
⎡ ⎤ ⎡ ⎤
9 2 1 2 2 16 17 9 12 12
⎢2 4 3 3 3⎥ ⎢ 17 12 12 2 18 ⎥
⎢ ⎥ ⎢ ⎥
A=⎢
⎢1 3 7 3 4⎥ ⎢
⎥, B = ⎢ 9 12 18 7 13 ⎥
⎥.
⎣2 3 3 5 4 ⎦ ⎣ 12 2 7 18 12 ⎦
2 3 4 4 5 12 18 13 12 10

(19) For the following matrices, perform Jordanian transform, and find the trans-
formation matrices.
⎡ ⎤ ⎡ ⎤
−2 0.5 −0.5 0.5 −2 −1 −2 −2
⎢ 0 −1.5 0.5 −0.5 ⎥ ⎢ 2⎥
A=⎢ ⎥ , B = ⎢ −1 −2 2 ⎥.
⎣ 2 0.5 −4.5 0.5 ⎦ ⎣ 0 2 0 3⎦
2 1 −2 −2 1 −1 −3 −6

(20) Select a suitable transformation matrix, such that A matrix can be transformed
into its companion form.
⎡ ⎤
2 −2 2 −1 0
⎢ −2 1 −1 2 1⎥
⎢ ⎥
A=⎢
⎢ 1 −1 −1 −2 2⎥⎥.
⎣ 1 1 −1 2 2⎦
1 0 2 2 −2

(21) See whether the matrix A can be transformed into a diagonal one. If yes, what
is the transformation matrix?
⎡ ⎤
2 2 −2 7 −2
⎢ 38 15 −28 56 −10 ⎥
⎢ ⎥
A=⎢ ⎢ 17 8 −15 24 −5 ⎥
⎥.
⎣ −4 −2 2 −9 2⎦
20 10 −16 31 −8

(22) Find the singular values of the following complex matrix:


⎡ ⎤ ⎡ ⎤
−2 −2 1 −1 2 0 −2 0
⎢ 0 −1 −2 2⎥ ⎢2 1 −2 1⎥
A=⎢
⎣ 0 −2
⎥ + j⎢ ⎥.
2 −1 ⎦ ⎣0 0 −1 2⎦
1 0 −2 −1 0 0 −1 −1
246 Chapter 8 · Linear Algebra and Matrix Analysis

(23) For the autonomous differential equation x (t) = Ax(t), the analytical solution
can be written as x(t) = e At x(0), find the analytical solution of the autonomous
differential equation.
⎡ ⎤ ⎡ ⎤
−3 0 0 1 −1
⎢ −1 −1 1 −1 ⎥ ⎢ ⎥
x (t) = ⎢ ⎥ x(t), x(0) = ⎢ 0 ⎥ .
⎣ 1 0 −2 1 ⎦ ⎣ 3⎦
0 0 0 −4 1

(24) For the given matrix A find, the logarithmic matrix functions ln A and ln At,
and validate the solutions, with the reliable expm() function.
⎡ ⎤
−1 −1/2 1/2 −1
⎢ −2 −5/2 −1/2 1⎥
A=⎢
⎣ 1
⎥.
−3/2 −5/2 −1 ⎦
3 −1/2 −1/2 −4

(25) Find the analytical and numerical solutions of the square roots of the matrix A
8 and validate the results.
⎡ ⎤
−30 0 0 0
⎢ 28 −2 1 1⎥
A=⎢ ⎣ −27 −28 −31 −1 ⎦ .

27 28 29 −1

(26) Find the trigonometric functions sin At, cos At, tan At and cot At of the fol-
lowing matrices.
⎡ ⎤ ⎡ ⎤
−15/4 3/4 −1/4 0 −1 0 0 0
⎢ 3/4 −15/4 0⎥ ⎢ 0⎥
A1 = ⎢
1/4 ⎥ , A2 = ⎢ 0 −1 1 ⎥.
⎣ −1/2 1/2 −9/2 0⎦ ⎣ 2 0 −2 1⎦
7/2 −7/2 1/2 −1 −1 0 0 −2

(27) Assume that a Jordanian block matrix A, whose components are


⎡ ⎤
A1
A=⎣ A2 ⎦,
A3

where
⎡ ⎤
⎡ ⎤ −1 1 0 0
−3 1 0 ⎢ 0
−5 1 −1 1 0⎥
A1 = ⎣ 0 −3 1 ⎦ , A2 = , A3 = ⎢
⎣ 0
⎥.
0 −5 0 −1 1⎦
0 0 −3
0 0 0 −1

Use analytical solution method to find e At and sin 2 At + π/3 .
8.6 · A Mini-Project
247 8
2
(28) For the given matrix A, compute e A t A2 + sin( A3 t) At + esin At .
⎡ ⎤
−3 −1 1 0
⎢ −28 −57 27 −1 ⎥
A=⎢
⎣ −29 −56
⎥.
26 −1 ⎦
1 29 −29 −30
 
(29) For the matrix A, compute e At , sin At and e At sin A2 e At t .
⎡ ⎤
−4.5 0 0.5 −1.5
⎢ −0.5 −4 0.5 −0.5 ⎥
A=⎢
⎣ 1.5
⎥.
1 −2.5 1.5 ⎦
0 −1 −1 −3

(30) For the matrix A in Exercise (5), compute the matrix power Ak .
(31) For the matrix A in Exercise (5), compute the matrices k A and 5 A , and validate
the results.

8.6 A Mini-Project
Edge detection to a digital image is a very important task in digital signal processing
and computer vision. Edge detecting method with Sobel operator is presented here
as an example such that a Sobel operator-based edge detecting function is expected.
A grayscale digital image can be represented by a matrix. Mesh grids can be made
to the whole image, such that each mesh grid, known as a pixel, is represented by a
value. A color image in RGB color space can be represented by a 3D array, which is
piled up by three image layers, and these layers represent, respectively, the red, green
and blue components in the image.
Functions imread() loads an image file into MATLAB workspace, and func-
tion imtool() can be used to display and manipulate the images. Since many edge
detection methods can only be used to deal with grayscale images, a conversion func-
tion rgb2gray() can be used to carry out the conversion. The default data type in
MATLAB is uint8, and it should be converted into double first.
Two Sobel matrices are introduced [4]
⎡ ⎤ ⎡ ⎤
−1 0 1 1 2 1
Sx = ⎣ −2 0 2 ⎦ , Sy = ⎣ 0 0 0⎦ (8.15)
−1 0 1 −1 −2 −1

and carry out convolution operation with the whole n × m image matrix W . That is,
to compute

gx = −wi−1,j−1 + wi−1,j+1 − 2wi,j−1 + 2wi,j+1 − wi+1,j−1 + wi+1,j+1


(8.16)
gy = wi−1,j−1 + 2wi−1,j + wi−1,j+1 − wi+1,j−1 − 2wi+1,j − wi+1,j+1
248 Chapter 8 · Linear Algebra and Matrix Analysis


for i = 2, 3, . . . , n−1, j = 2, 3, . . . , m−1. Then the values g = gx2 + gy2 are examined
for each pair of i’s and j’s. If the value g is greater than the predefined threshold h, for
instance, h = 150, the corresponding ti,j is set to 0 (for black, on the edge), otherwise
it is set to 255 (for white, not on the edge). Matrix T thus created is composed of 0’s
and 255’s. It is then the edge image from the original grayscale one.
Write a Sobel operator-based edge detection function. In the toolbox for this book,
a well-known testing image file, lena512color.tif, is provided. Load the image into
MATLAB workspace. Convert it into a grayscale image, then call the edge detection
function to detect the edges of the image. What is the impact of the threshold on the
detecting quality? Superimpose the result on top of the color image and observe the
result.

References
1. Xue DY (2020) Linear algebra and matrix computations with MATLAB[M]. De Gruyter, Berlin
2. Higham NJ (2008) Functions of matrices: Theory and application[M]. SIAM Press, Philadelphia
3. Xue DY, Chen YQ (2016) Scientific computing with MATLAB[M], 2nd edn. CRC Press, Boca Raton
8 4. Gongzalez RC, Woods RE (2002) Digital image processing[M], 2nd edn. Prentice Hall, Englewood
Cliffs
249 9

Algebraic Equation
Solutions
Contents

9.1 Linear Algebraic Equation Solutions – 251


9.1.1 General Form of Linear Equations – 251
9.1.2 Numerical and Analytical Solutions of Linear Equations – 252
9.1.3 Infinite Solution Constructions – 253
9.1.4 Least Squares Solutions of Conflict Equations – 255
9.1.5 X A = B Equation Solutions – 256

9.2 Solutions of Special Linear Equations – 256


9.2.1 Kronecker Transform of Linear Equations – 257
9.2.2 AX B = C Equation Solutions – 258
9.2.3 Lyapunov Equations – 258
9.2.4 Sylvester Equations – 260

9.3 Solutions of Nonlinear Equations – 262


9.3.1 Graphical Solutions of Nonlinear Equations – 262
9.3.2 Quasi-Analytical Solutions of Polynomial-Type
Equations – 266
9.3.3 Quasi-Analytical Solutions of Quadratic Equations – 268
9.3.4 Numerical Solutions of Nonlinear Equations – 269
9.3.5 Control Parameters in Equation Solutions – 271

9.4 Nonlinear Matrix Equations with Multiple


Solutions – 272
9.4.1 Ideas and Implementation of Equation Solutions – 272
9.4.2 Matrix Equation Solutions – 274
9.4.3 Solutions of Pseudo-Polynomial Equations – 275

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_9
9.5 Exercises – 276

9.6 Mini-Projects – 280


References – 281
9.1 · Linear Algebraic Equation Solutions
251 9
Equations are equalities containing one or more variables. These variables are referred
to as unknowns. The unknown variables satisfying these equalities are also known
as the solutions of the equations. If there are several equations containing many
variables, and these equations hold at the same time, the equations are referred to
as simultaneous equations. Equations are the ubiquitous mathematical models in
science, engineering, and even in daily life. Equations are usually classified into alge-
braic equations and differential equations. The solutions of algebraic equations are
explored in this chapter, while in 7 Chap. 10, the solutions of differential equations
are explored. In this chapter, the solutions of linear and nonlinear equations are both
considered. In particular, the nonlinear matrix equations with multiple solutions are
studied, and a general universal solver is designed.
In 7 Sect. 9.1, numerical and analytical solutions of linear algebraic equations are
introduced. Linear equations are classified, and the cases where the equations have
unique solutions, infinite number of solutions and least squares solutions are studied,
respectively. The solutions of other forms of linear equations are also discussed. In
7 Sect. 9.2, various equations which can be converted into linear algebraic equations
are discussed. These types of equations include Lyapunov equations and generalized
Lyapunov equations, where both numerical and analytical solutions are presented.
In 7 Sect. 9.3, solutions of ordinary nonlinear algebraic equations are explored, the
methods such as graphical methods and quasi-analytical solution methods are pro-
posed. Also, searching-based numerical solutions for ordinary nonlinear equations
are discussed. In 7 Sect. 9.4, explorations on nonlinear matrix equations are pre-
sented, and attempts are made on finding possibly all the solutions in the interested
regions.

9.1 Linear Algebraic Equation Solutions


Linear algebraic equations are the simplest equations. This section is dedicated to the
solution patterns of linear algebraic equations. The general mathematical forms of
linear algebraic equations are presented first, and three cases are considered for the
solutions of the equations. Numerical and analytical solutions are both explored, and
the solutions of simple variation of linear equations are also studied.

9.1.1 General Form of Linear Equations


The general mathematical form of linear equation is

⎪ a11 x1 + a12 x2 + · · · +a1n xn = b1

⎨ a x + a x + · · · +a x = b
21 1 22 2 2n n 2
.. (9.1)

⎪ .

am1 x1 + am2 x2 + · · · +amn xn = bm .

If bi is a 1 × p row vector, the solution x is an n × p matrix.


252 Chapter 9 · Algebraic Equation Solutions

The matrix form of the linear equations in (9.1) is

Ax = B, (9.2)

where A and B are given matrices.


⎡ ⎤ ⎡ ⎤
a11 a12 ··· a1n b11 b12 ··· b1p
⎢ a21 a22 ··· a2n ⎥ ⎢ b21 b22 ··· b2p ⎥
A=⎢
⎣ ... .. .. .. ⎥ , B=⎢
⎣ ... .. .. .. ⎥ . (9.3)
. . . ⎦ . . . ⎦
am1 am2 ··· amn bm1 bm2 ··· bmp

From the given matrices A and B, a test matrix C can be established.


⎡ ⎤
a11 a12 ··· a1n b11 b12 ··· b1p
⎢ a21 a22 ··· a2n b21 b22 ··· b2p ⎥
C=⎢
⎣ ... .. .. .. .. .. .. .. ⎥ . (9.4)
. . . . . . . ⎦
am1 am2 ··· amn bm1 bm2 ··· bmp

Therefore the judgement theorem of the linear algebraic equation is given below,
without proofs [1]. The solutions of linear equation Ax = B can be studied in the
9 following three cases:
(1) When m = n and rank( A) = n, (9.2) has a unique solution:

x = A−1 B. (9.5)

(2) When rank( A) = rank(C) = r < n, (9.2) has infinite number of solutions.
(3) When rank( A) < rank(C), (9.2) is a conflict equation, with no solutions.
Moore−Penrose generalized inverse finds its least squares solutions.

9.1.2 Numerical and Analytical Solutions of Linear Equations


If A matrix is an n × n squared one, and rank( A) = n, the equation has a unique
solution. How can we find the unique solution? The following three methods are all
feasible:
(1) With left division method, the solution is found directly from X = A \ B.
(2) From (9.5), if the inverse matrix is found, the solution is X = inv( A)*B .
(3) Reduced row echelon form can be used to solve the equation directly:
C=[ A,B]; D=rref(C); X= D(:,n + 1:end)
The three methods are mathematically equivalent. If one of A and B is symbolic,
analytical solution can be found. If both are double precision ones, numerical solution
can be found.
9.1 · Linear Algebraic Equation Solutions
253 9

 Example 9.1
Assume that A is an n × n random matrix, and b is an n × 1 random column vector,
compare the three methods in terms of speeds and accuracy, for relatively large n. Assess
the advantages and disadvantages of the three methods.
Solutions With the following statements, it can be seen from the observed results in . Table
9.1 that Method (1) has advantages over (2) on speed and accuracy. Therefore Method (1)
is recommended. The efficiency of Method (3) is relatively low and not recommended.
>> n0=[500,1000,3000,6000,10000]; % different matrix sizes
for n=n0 % compare in a loop
A=rand(n); b=rand(n,1); % generate random matrices and vectors
disp([n,1]), tic, X=A\b; norm(A*X-b), toc % Method (1)
disp([n,2]), tic, X=inv(A)*b; norm(A*X-b), toc % Method (2)
disp([n,3]), if n>3000, continue, end % Mathod (3) is skipped directly
C=[A,b]; tic, D=rref(C); X=D(:,n+1:end); norm(A*X-b), toc
end
If A is converted into a symbolic one, the error obtained is zero. The time elapse is relatively
long. For instance, when n = 50, the time elapses are 4.182 and 26.393 s, respectively. If
n = 80, time elapses are, respectively, 24.53 s and 219.36 s. The tendency of time elapse is
the same as the ones in . Table 9.1. 

9.1.3 Infinite Solution Constructions


If rank( A) = rank(C) = r < n, (9.2) has infinite number of solutions. The infinite
solutions can be composed according to the following three steps:
(1) Infinite solutions for the homogeneous equation. The concept of null space is
presented first. All the nonzero vectors in matrix z such that the homogeneous equa-
tion Az = 0 holds are referred to as null vectors, and a set of linearly independent
null vectors spans the null space Z, where the number of columns in Z is n − r. The
columns in Z are also known as the basic set of solutions in matrix A. Matrix Z can
be obtained with Z = null( A).

. Table 9.1 Efficiency comparisons of the three methods

Size n 500 1000 3000 6000 10000

Method (1), time elapse 0.012 0.074 0.607 3.322 15.516

Method (1), errors 1.18×10−12 4.60×10−12 4.64×10−10 2.27×10−10 6.07×10−10

Method (2), time elapse 0.075 0.128 1.364 9.969 55.163

Method (2), error 5.02×10−12 3.72×10−11 7.18×10−10 4.033×10−10 1.08×10−9

Method (3), time elapse 1.457 5.834 443.47 − −

Method (3), error 1.47×10−11 2.48×10−11 1.04×10−10 − −


254 Chapter 9 · Algebraic Equation Solutions

With matrix Z, the infinite solution can be composed from

ẑ = α1 z 1 + α2 z 2 + · · · + αn−r z n−r , (9.6)

where αi are arbitrary constants, i = 1, 2, . . . , n − r. Infinite solutions can also be


composed through matrix multiplication.
(2) Find a particular solution. A particular solution can be found from x 0 = A+ B,
and with command x 0 = pinv( A)*B.
(3) Configure solutions. Add up the above solutions, the infinite number of solu-
tions to the original equations can be composed.

x = α1 z 1 + α2 z 2 + · · · + αn−r z n−r + x 0 . (9.7)

 Example 9.2
Solve the linear algebraic equation [2].
⎡ ⎤ ⎡ ⎤
1 4 0 −1 0 7 −9 3
⎢ 2 8 −1 3 9 −13 7⎥ ⎢9⎥
⎢ ⎥ X = ⎢ ⎥.
⎣ 0 0 2 −3 −4 12 −8 ⎦ ⎣1⎦
−1 −4 2 4 8 −31 37 4
9
Solutions Input matrices A and B to compose matrix C. The test matrix can be constructed,
and their ranks can be found.
>> A=[1,4,0,-1,0,7,-9;2,8,-1,3,9,-13,7;
0,0,2,-3,-4,12,-8;-1,-4,2,4,8,-31,37];
B=[3; 9; 1; 4]; C=[A B]; rank(A), rank(C) % find the ranks
It can be seen that the ranks of matrices A and C are the same, both equal to 3, less than
7, the number of columns in matrix A. It can be concluded that the equation has infinite
number of solutions. The null space Z should be found first, and a particular solution x 0
can be found.
>> Z=null(sym(A)), x0=sym(pinv(A)*B) % find null space and particular solution
a=sym('a%d',[4,1]); x=Z*a+x0, E=A*x-B % compose general solutions
For arbitrary constants a1 , a2 , a3 and a4 , all the analytical solutions of the original equation
can be composed, such that the error matrix is a zero one.
⎡ ⎤ ⎡ ⎤
−4 −2 −1 3 92/395
⎢ 1 0 0 0⎥ ⎢ 368/395 ⎥
⎢ ⎥ ⎢ ⎥
⎢ 0 −1 3 −5 ⎥ ⎢ 459/790 ⎥
⎢ ⎥ ⎢ ⎥
Z=⎢
⎢ 0 −2 6 −6 ⎥ ⎢ ⎥
⎥ , x 0 = ⎢ −24/79 ⎥ ,
⎢ 0 1 0 0⎥ ⎢ 347/790 ⎥
⎢ ⎥ ⎢ ⎥
⎣ 0 0 1 0⎦ ⎣ 247/790 ⎦
0 0 0 1 303/790
9.1 · Linear Algebraic Equation Solutions
255 9
⎡ ⎤
−4a1 − 2a2 − a3 + 3a4 + 92/395
⎢ a1 + 368/395 ⎥
⎢ ⎥
⎢ −a2 + 3a3 − 5a4 + 459/790 ⎥
⎢ ⎥
x=⎢
⎢ −2a2 + 6a3 − 6a4 − 24/79 ⎥.

⎢ a + 347/790 ⎥
⎢ 2 ⎥
⎣ a3 + 247/790 ⎦
a4 + 303/790


 Example 9.3
Solve the matrix equation in Example 9.2 with reduced row echelon form.
Solutions Reduced row echelon form can also be used to solve the equation.
>> C=[A B]; D=rref(C) % augment the matrix and find the reduced row echelon form
The reduced row echelon form obtained is
⎡ ⎤
1 4 0 0 2 1 −3 4
⎢0 0 1 0 1 −3 5 2⎥
D=⎢
⎣0
⎥.
0 0 1 2 −6 6 1⎦
0 0 0 0 0 0 0 0

It is seen that the free variables can be selected as x2 , x5 , x6 and x7 , and they can be of any
values. Let x2 = b1 , x5 = b2 , x6 = b3 , x7 = b4 , the solutions to the equation can easily be
composed from D. ⎡ ⎤
−4b1 − 2b2 − b3 + 3b4 + 4
⎢ b1 ⎥
⎢ ⎥
⎢ −b2 + 3b3 − 5b4 + 2 ⎥
⎢ ⎥
x=⎢ ⎢ −2b 2 + 6b 3 − 6b 4 + 1 ⎥.

⎢ b ⎥
⎢ 2 ⎥
⎣ b3 ⎦
b4


9.1.4 Least Squares Solutions of Conflict Equations


If rank( A) < rank(C), then (9.2) is a conflict equation. Moore−Penrose generalized
inverse finds its least squares solution x = A+ B.
Since pseudoinverse is involved, the command x = pinv( A)*B finds directly
the least squares solution. The solution does not satisfy the original equation, but it
minimizes the norm measure || Ax − B|| of the error matrix.
256 Chapter 9 · Algebraic Equation Solutions

 Example 9.4
Solve the linear algebraic equation.
⎡ ⎤ ⎡ ⎤
1 2 3 4 1
⎢2 2 1 1⎥ ⎢2⎥
⎢ ⎥ X = ⎢ ⎥.
⎣2 4 6 8⎦ ⎣3⎦
4 4 2 2 4

Solutions Input the two matrices first and compose the test matrix C. Then find the ranks
of them with the following commands:
>> A=[1 2 3 4; 2 2 1 1; 2 4 6 8; 4 4 2 2]; B=[1:4]';
C=[A B]; rank(A), rank(C) % find the ranks of A and C
It can be seen that rank( A) = 2  = rank(C) = 3, therefore the original equation is a conflict
one. There is no solution. Function pinv() finds the Moore−Penrose generalized inverse,
so as to find the least squares solution.
>> X=pinv(A)*B, norm(A*X-B) % solve conflict equation, assess least squares solution
The least squares solution found is X = [0.5466, 0.4550, 0.0443, −0.0473]T , which does
not satisfy the original equation, but it minimizes the squared error, such that the norm of
the error matrix is 0.4472. 

9
9.1.5 X A = B Equation Solutions
If the linear solution is given by
X A = B, (9.8)
transpose can be applied to both sides such that

AT Z = B T , (9.9)

where Z = X T . The original equation can be mapped into the form in (9.2), such that
the above methods can be used to solve directly the equations.
Note that the transpose here is direct transpose, rather than Hermitian transpose,
otherwise the solutions obtained may not satisfy the original equation (9.8).

9.2 Solutions of Special Linear Equations


Special linear equations here refer to those which can be converted through cer-
tain transformation into linear algebraic equations. After conversion, the methods
in 7 Sect. 9.1 can be used to find the numerical and analytical solutions of the orig-
inal equations. In this section, several special equation forms are studied, including
AX B = C equations, Lyapunov equations and Sylvester equations. Analytical solu-
tions based on Kronecker products are introduced. Also, the solvers in MATLAB
Control System Toolbox can be used to find the numerical solutions.
9.2 · Solutions of Special Linear Equations
257 9
9.2.1 Kronecker Transform of Linear Equations
The definition of Kronecker product of two matrices was given in (6.5). Besides,
the solution methods for equations AX = B are discussed earlier. In this section,
Kronecker product-based method is proposed to convert the equation into Ax = b
form, where x and b are column vectors. Of course the transformation demonstrated
next is not intended for the solution of simple linear algebraic equations, but to explore
more complicated equations. An example is given next for the conversion.

 Example 9.5
Derive 2 × 2 equations under Kronecker product representation.
  
a11 a12 x1 x3 b1 b3
= .
a21 a22 x2 x4 b2 b4

Solutions Defining the symbolic variables, the original equation can be converted into the
standard Ax = b form, where b is a column vector.
>> A=sym('a%d%d',2); % arbitrary symbolic matrix
syms x1 x2 x3 x4; X=[x1 x3; x2 x4];
syms b1 b2 b3 b4; B=[b1 b3; b2 b4]; M=A*X; M(:)==B(:)
It can be converted into the following equivalent form:
⎡ ⎤⎡ ⎤ ⎡ ⎤
a11 a12 0 0 x1 b1
⎢ a21 a22 0 ⎥ ⎢ ⎥ ⎢ ⎥
⎢ 0 ⎥ ⎢ x2 ⎥ = ⎢ b2 ⎥ .
⎣ 0 0 a11 a12 ⎦ ⎣ x3 ⎦ ⎣ b3 ⎦
0 0 a21 a22 x4 b4

It can be seen that the coefficient matrix on the left side is in fact I ⊗ A. Vectors x and b
are the expanded vectors from the original matrices in a column-wise format. 

More generally, the AX = B can be equivalently converted to


 
I m ⊗ A x = b, (9.10)

where A ∈ Cn×n , B ∈ Cn×m , and vectors x and b are the column-wise expanded
vectors from matrices X and B, denoted, respectively, as x = vec(X) and b = vec(B).
Similarly, equation X A = B can also be converted with Kronecker product as
 
AT ⊗ I n x = b, (9.11)

where X ∈ Cm×n , A ∈ Cn×n , and vectors x and b are, respectively, column-wise


expanded ones from matrices X and B, denoted as x = vec(X) and b = vec(B).
258 Chapter 9 · Algebraic Equation Solutions

9.2.2 AX B = C Equation Solutions


If matrices A and B are nonsingular, simple conversion can be made such that the
equation AX B = C can be solved.

X = A−1 C B −1 . (9.12)

Alternatively, if Kronecker product is adopted, AX B = C equation can be con-


verted into the following form:
 
B T ⊗ A x = c, (9.13)
   
where c = vec C , x = vec X are the column-wise expanded vectors of matrices C
and X.

 Example 9.6
Solve the following equation again with Kronecker product method:
⎡ ⎤
⎡ ⎤ 0 1 0 0 1 ⎡ ⎤
8 1 6 ⎢1 0 1 2 2⎥ 0 2 0 0 2
⎢ ⎥
⎣3 5 7⎦ X ⎢1 2 0 0 2⎥ = ⎣1 2 1 0 0⎦.
⎢ ⎥
⎣0 0 1 1 1⎦
9 4 9 2
1 0 0 2 1
2 1 1 1 0

Solutions The following commands find directly the analytical solution of the equation.
In fact, the column-wise expansion vec(C) can be obtained with C(:). When the solution
vector is found, it can be restored into matrix form with reshape() function.

>> B=[0,1,0,0,1; 1,0,1,2,2; 1,2,0,0,2; 0,0,1,1,1; 1,0,0,2,1];


C=[0,2,0,0,2; 1,2,1,0,0; 2,1,1,1,0];
A=[8,1,6; 3,5,7; 4,9,2]; A=sym(A); c=C(:);
x=inv(kron(B.',A))*c; X=reshape(x,3,5), A*X*B-C % solve and validate
X1=A\C/sym(B), A*X1*B-C % if (9.12) is used
The analytical solutions with the two methods are given below and they are identical. When
they are substituted back to the original equation, the errors are zero matrices.
⎡ ⎤
257/360 7/15 −29/90 −197/360 −29/180
X = X 1 = ⎣ −179/180 −8/15 23/45 119/180 23/90 ⎦ .
−163/360 −8/15 31/90 223/360 31/180

9.2.3 Lyapunov Equations


Continuous Lyapunov equation is expressed as

AX + X AH = −C, (9.14)

where matrices A, C, X ∈ Cn×n .


9.2 · Solutions of Special Linear Equations
259 9
If there is no a priori knowledge on Lyapunov equations, it may be rather hard
to solve the equations like this. Function lyap() provided in the Control System
Toolbox can be adopted with the syntax X = lyap( A,C), to find the numerical
solution of Lyapunov equation. In fact, with the conversion methods in (9.10) and
(9.11), it is not difficult to convert (9.14) into
 
I ⊗ A + A ⊗ I x = −c, (9.15)
   
where c = vec C and x = vec X are, respectively, the column-wise expanded
vectors of matrices C and X. Therefore with the previously presented methods, the
analytical solution of the equation can be found.

 Example 9.7
Assume that the matrices A and C in the Lyapunov equation are given below, solve numer-
ically the Lyapunov equation and validate the solution.
⎡ ⎤ ⎡ ⎤
1 2 3 10 5 4
A = ⎣4 5 6⎦, C = −⎣ 5 6 7⎦.
7 8 0 4 7 9

Solutions Input the matrices, the following commands can be used to solve the equation:
>> A=[1 2 3;4 5 6; 7 8 0]; C=-[10,5,4; 5,6,7; 4,7,9]; % input the matrices
X=lyap(A,C), norm(A*X+X*A'+C) % solve Lyapunov equation and validate it
The numerical solution obtained is given below. It can be seen from the last line that the
error of the solution is || AX + X AT + C|| = 2.3211×10−14 , it can be seen that the solution
X satisfies the equation, with rather high accuracy.
⎡ ⎤
−3.9444444444442 3.8888888888887 0.38888888888891
X = ⎣ 3.8888888888887 −2.7777777777775 0.22222222222221 ⎦ .
0.38888888888891 0.22222222222221 −0.11111111111111

 Example 9.8
Find the analytical solution of the Lyapunov equation in Example 9.7.
Solutions With the analytical method in (9.15), the following commands can be used:
>> A=[1 2 3;4 5 6; 7 8 0]; C=-[10,5,4; 5,6,7; 4,7,9]; % input the matrices
A=sym(A); I=eye(3); % convert the matrix into symbolic form
x=-(kron(A,I)+kron(I,A))\C(:); % solve Lyapunov equation
X=reshape(x,3,3), A*X+X*A'+C % validate the solution
The analytical solution obtained is given below. Substituting it back into the equation,
the zero error matrix can be found. It is validated that the solution thus obtained is the
analytical solution.
260 Chapter 9 · Algebraic Equation Solutions

⎡ ⎤
−71/18 35/9 7/18
X = ⎣ 35/9 −25/9 2/9 ⎦ .
7/18 2/9 −1/9


9.2.4 Sylvester Equations


The general form of Sylvester equation is

AX + X B = −C, (9.16)

where A ∈ Cn×n , B ∈ Cm×m , C, X ∈ Cn×m . The equation is also known as generalized


Lyapunov equation.
Function lyap() provided in Control System Toolbox can be used directly to
solve the equation, with X = lyap( A,B,C). Schur decomposition is used to find the
numerical solutions. Besides, function sylvester() in MATLAB solves numerically
the Sylvester equations, with the syntax X = sylvester( A,B, − C). Note that −C
is used here, since the equation for such a function is AX + X B = C.
Similar to the above Lyapunov equations, Kronecker product converts directly
9 the original equations into linear algebraic equation.
 
I m ⊗ A + B T ⊗ I n x = −c, (9.17)

where c = vec(C), x = vec(X) are the column-wise


 expanded vectors.
If the coefficient matrix I m ⊗ A + B T ⊗ I n is nonsingular, the Sylvester equation
has a unique solution.
Note that, direct transpose is used in (9.17), rather than Hermitian transpose.
Summarizing the above algorithms, the following MATLAB function lyapsym()
can be written to solve Sylvester equation:
function X=lyapsym(A,B,C)
if nargin==2, C=B; B=A'; end % solve Lyapunov equation
[nr,nc]=size(C); A0=kron(eye(nc),A)+kron(B.',eye(nr));
if rank(A0)==nr*nc, x0=-A0\C(:); X=reshape(x0,nr,nc);
else, error('singular matrix found.'), end
end

 Example 9.9
Solve numerically the following Sylvester equation:
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
8 1 6 16 4 1 1 2 3
⎣3 5 7⎦ X + X ⎣ 9 3 1⎦ = ⎣4 5 6⎦.
4 9 2 4 2 1 7 8 0

Solutions With function lyap(), numerical solution of the equation can be found.
9.2 · Solutions of Special Linear Equations
261 9
>> A=[8,1,6; 3,5,7; 4,9,2]; B=[16,4,1; 9,3,1; 4,2,1]; % input the matrices
C=-[1,2,3; 4,5,6; 7,8,0]; X=lyap(A,B,C) % solve the equation
norm(A*X+X*B+C) % validate the results
The numerical solution can be obtained below. It can be seen that the norm of the error is
1.5445×10−14 . ⎡ ⎤
0.0749 0.0899 −0.4329
X = ⎣ 0.0081 0.4814 −0.2160 ⎦ .
0.0196 0.1826 1.1579

Function sylvester() yields an error of 7.9143×10−15 .


>> X=sylvester(A,B,-C), norm(A*X+X*B+C)


 Example 9.10
Find the analytical solution of the Sylvester equation in Example 9.9.
Solutions With lyapsym() function, the analytical solution can be obtained
>> A=[8,1,6; 3,5,7; 4,9,2]; B=[16,4,1; 9,3,1; 4,2,1]; % input matrices
C=-[1,2,3; 4,5,6; 7,8,0]; x=lyapsym(sym(A),B,C) % analytical solution
norm(A*x+x*B+C) % validate the solution
and the solutions found as follows. It can be seen that the error is zero, which is indeed the
analytical solution of the equation.
⎡ ⎤
1349214/18020305 648107/7208122 −15602701/36040610
x = ⎣ 290907/36040610 3470291/7208122 −3892997/18020305 ⎦ .
70557/3604061 1316519/7208122 8346439/7208122

Of course, lyapsym() function can still be used to find the numerical solution of the
Sylvester equation. 

 Example 9.11
Solve the following Sylvester equation:
⎡ ⎤ ⎡ ⎤
8 1 6  1 2
2 3
A = ⎣3 5 7⎦, B = , C = −⎣3 4⎦.
4 5
4 9 2 5 6

Solutions It is not necessary that matrix C is square. With the following commands the
analytical solution can be obtained. With the above function lyapsym(), the analytical
solution to the Sylvester equation can be found.
>> A=[8,1,6; 3,5,7; 4,9,2]; B=[2,3; 4,5]; C=-[1,2; 3,4; 5,6]
X=lyapsym(sym(A),B,C), norm(A*X+X*B+C) % solution and validation
The solution obtained is as follows. It is seen that the solution is the analytical solution of
the equation.
262 Chapter 9 · Algebraic Equation Solutions

⎡ ⎤
−2853/14186 −11441/56744
X = ⎣ −557/14186 −8817/56744 ⎦ .
9119/14186 50879/56744


 Example 9.12
If in B matrix, b21 = a in Example 9.11, where a is real, solve the Sylvester equation.
⎡ ⎤ ⎡ ⎤
8 1 6  1 2
2 3
A = ⎣3 5 7⎦, B = , C = −⎣3 4⎦.
a 5
4 9 2 5 6

Solutions Even though there is a constant a, the analytical solution method presented
earlier can still be used to solve Sylvester equation
>> syms a real; A=[8,1,6; 3,5,7; 4,9,2];
B=[2,3; a,5]; C=-[1,2; 3,4; 5,6]; % matrix with variable a
X=simplify(lyapsym(A,B,C)), norm(A*X+X*B+C) % solve and validate
and the analytical solution found is

  ⎤
9 1 ⎢
6 3a3 + 155a2 − 2620a + 200
 
−(513a2 − 10716a + 80420)
 ⎥
⎢ ⎥
X= ⎢ 4 9a3 − 315a2 + 314a + 980 −3 201a2 − 7060a + 36780 ⎥ ,
Δ ⎣   ⎦
2 27a3 − 1869a2 + 25472a − 760 −477a2 + 4212a + 194300

where Δ = 27a3 − 3672a2 + 69300a + 6800. Besides, when the denominator Δ = 0, there
is no solution. 

9.3 Solutions of Nonlinear Equations


The solutions of nonlinear algebraic equations are more complicated than their linear
counterparts. In many applications, it is even impossible to know how many solu-
tions are there. In this section, graphical method is introduced first, then numerical
solutions with high precision to polynomial-type equations are discussed. Finally
searching-based numerical solutions are introduced. In 7 Sect. 9.4, matrix equations
with multiple solutions are further explored.

9.3.1 Graphical Solutions of Nonlinear Equations


It has been presented in 7 Chap. 5 that with functions fplot() and fimplicit(),
the solutions can be drawn graphically for the equations with one or two variables.
These methods are known as graphical methods. It is obvious that the graphical
methods have certain limitations, since graphical methods can be used to solve at most
equations with two variables. In this section, graphical methods are demonstrated.
9.3 · Solutions of Nonlinear Equations
263 9
1. Graphical Solutions of Univariate Equations
The mathematical form of equations with one unknown is given by

f (x) = 0. (9.18)

For any equations with one unknown, f (x) = 0, anonymous function or symbolic
expression can be used to describe the equation, then function fplot() draws the
curve of the equation. Therefore, the intersections of the curve with horizontal axis
are found graphically, which are the solutions of the equations.

 Example 9.13
It is usually difficult to handle analytically equations with square roots. If the conditions
are not satisfied, the analytical solutions cannot be found. Use graphical methods to solve
the following equation:
   
2x2 + 3 + x2 + 3x + 2 − 2x2 − 3x + 5 − x2 − 5x + 2 = 0.

Solutions Symbolic expression can be used to describe the left side of the equation, then
fplot() can be called to draw the curve, superimposed by the horizontal axis, as shown in
. Fig. 9.1. It can be seen from the results that there is only one intersection with horizontal
axis, which is the solution of the equation.
>> syms x % declare symbolic variable
f=sqrt(2*x^2+3)+sqrt(x^2+3*x+2)-... % use symbolic expression
sqrt(2*x^2-3*x+5)-sqrt(x^2-5*x+2);
fplot(f), line([-5 5],[0,0]) % draw curve with horizontal axis
To find the solutions of the equation, the zooming facilities in the toolbar of the axis can
be used to zoom the interested solution. This facility can be used repeatedly such that the
labels on x-axis are virtually the same. Such a solution can be regarded as a solution of the
equation. With this specific equation, it can be seen that the solution is x = 0.13809878.
Substituting the solution back to the equation, the error of 6.0180×10−9 is found. 

2. Solutions of Equations with Two Unknowns


The mathematical form of the simultaneous equations with two unknowns is given
below. Graphical method can be used to solve the equation. Also the limitations of
the method are illustrated.
The general form of the simultaneous equation is

f (x, y) = 0
(9.19)
g(x, y) = 0.

It can be seen that f (x, y) = 0 can be regarded as the implicit function with two
independent variables, x and y. Therefore function fimplicit() draws the curves of
264 Chapter 9 · Algebraic Equation Solutions

6
5
4
3
2
1
0
-1
-2
-3
-4

-5 -4 -3 -2 -1 0 1 2 3 4 5

. Fig. 9.1 Graphical solution of the equation

the function. All the points on the curves satisfy the equation. Similarly, g(x, y) = 0
is also an implicit function. With function fimplicit(), the equations can be solved.
If the two sets of curves are drawn together, the intersections are the solutions of the
simultaneous equations.

9
 Example 9.14
Find all the solutions in the interested range −2π ≤ x, y ≤ 2π, of the simultaneous
equations with two unknowns.

x2 e−xy /2 + e−x/2 sin(xy) = 0
2

y2 cos(y + x2 ) + x2 ex+y = 0.

Solutions The graphical method has been illustrated in Example 5.28. With the following
commands, the curves of the two equations are drawn together, as shown in Fig. 9.2. The
intersections are the solutions of the simultaneous equations.
>> syms x y; f1=x^2*exp(-x*y^2/2)+exp(-x/2)*sin(x*y);
f2=y^2*cos(y+x^2)+x^2*exp(x+y); % symbolic expressions of the equations
fimplicit([f1 f2],[-2*pi,2*pi]) % the curves of the equations
In order to find the solution at a specific point, zooming facilities can be used repeatedly to
locate roughly the solutions x and y, around the intersection. The accuracy thus obtained
may not be very high. Besides, there are too many such intersections, and it is hard to find
them one by one, in this way. Better methods are needed to find all the intersections in one
run.
If point (0, 0) is substituted into the equation, it is seen that this point is the solution of the
equation. Unfortunately such a point is deliberately avoided in the plot. Such a solution is
referred to as an isolated solution, which is usually difficult to find with searching methods.

9.3 · Solutions of Nonlinear Equations
265 9

-2

-4

-6
-6 -4 -2 0 2 4 6

. Fig. 9.2 Curves of the equations

 Example 9.15
Solve the simultaneous equations with graphical method.

x 2 + y2 = 1
0.75x3 − y = 0.9.

Solutions The two equations can be described as symbolic expressions. Then the two implicit
functions can be drawn together, as shown in . Fig. 9.3. It can be seen that there are two
intersections.
>> syms x y; f1=x^2+y^2==1; f2=0.75*x^3-y==0.9; % describe two equations
fimplicit([f1,f2],[-pi,pi]) % draw two implicit functions

-1

-2

-3
-3 -2 -1 0 1 2 3

. Fig. 9.3 Illustration of simultaneous equations


266 Chapter 9 · Algebraic Equation Solutions

Change the second equation slightly, it is found that y = 0.75x3 − 0.9. Substituting it into
the first one, a polynomial equation of x of degree 6 can be found: 0.5625x6 − 1.35x3 +
x2 − 0.19 = 0. The following commands can be used to find its roots:
>> x=roots([0.5625,0,0,-1.35,1,0,-0.19]), y=0.75*x.^3-0.9
It can be seen that there are six roots, not the two in . Fig. 9.3. Why there are only two
solutions in the plot? The equation has two real solutions, and the remaining four are two
pairs of complex conjugates. With graphical methods, only real solutions can be drawn.
The complex roots cannot be found and displayed. 

9.3.2 Quasi-Analytical Solutions of Polynomial-Type Equations


For specific equations, if the unknown terms are given in the form of polynomials,
it can be converted, for instance, with Gröbner base algorithm, into a polynomial
equation of a certain variable. Therefore the solution of the equation can be found. If
the analytical solutions cannot be found, symbolic computing engine can be employed
automatically to find the numerical solutions with very high precision. The solutions
thus found are referred to as quasi-analytical solutions in this book.
Two functions, solve() and vpasolve(), are provided in MATLAB for solving
directly algebraic equations. If there are analytical solutions, the former function finds
9 the analytical solutions. If there are no analytical solutions, the latter one is used in
finding quasi-analytical solutions.
The syntaxes of solve() function are
S=solve(eqn1 ,eqn2 ,· · · ,eqnn ), % solve equations
S=solve(eqn1 ,eqn2 ,· · · ,eqnn ,x1 ,x2 ,· · · ,xn ), % specify unknowns
where the equations to be solved can be described by the symbolic expressions eqni .
The independent variables can be described by xi . If only one output argument is
returned, the solutions can be extracted directly with S.xi . In the syntaxes, eqni can
be one equation, or a set of equations defined by a vector or a matrix. All the equations
can be expressed in a matrix or a vector eqn1 , such that the equations can be solved
directly.
Of course, the following syntax solves directly the equations:
[x1 ,x2 ,· · · ,xn ]=solve(∼), % the input arguments are the same as above
It can be seen that the directly returned arguments are simpler and more straight-
forward. Therefore this format is adopted in this book.
The syntaxes of function vpasolve() are the same as the ones in solve().

 Example 9.16
Solve the chick−rabbit cage problem with MATLAB.

x + y = 35
2x + 4y = 94 .
9.3 · Solutions of Nonlinear Equations
267 9
Solutions Low-level commands can of course be used to solve directly the problem. Here
the above functions are demonstrated. Symbolic expressions are needed to describe the two
equations, then call function solve(), the solutions can be found.
>> syms x y; [x0,y0]=solve(x+y==35,2*x+4*y==94) % solve the equations
Note that the equal signs in the equations should be described by ==. If the right side of the
equation is zero, the equal signs can be omitted. With the above commands, the analytical
solution x0 = 23 and y0 = 12 can be found. 

 Example 9.17
Solve the simultaneous equations in Example 9.15.
Solutions Graphical method cannot be used to solve the simultaneous equations in the
example, since there exist both real and complex solutions. The equations can be described
as symbolic expressions and then function vpasolve() can be used to solve the equations.
It is apparent that for the users, the solutions of these equations are as simple as solving
the chick−rabbit cage problems.
>> syms x y;
[x0,y0]=vpasolve(x^2+y^2==1,0.75*x^3-y==0.9) % quasi-analytical solutions
The solutions are returned in vectors x 0 and y0 . For this particular example, the validation
process is not quite simple. The equations should be entered again to assess the errors. An
alternative way is to define the two equations with symbolic expressions, and then solve the
equations again. The results are the same, and the error can be found as 3.6718×10−38 .
>> f1=x^2+y^2-1; f2=0.75*x^3-y-0.9; [x0,y0]=vpasolve(f1,f2)
norm([subs(f1,{x,y},{x0,y0}),subs(f2,{x,y},{x0,y0})])


 Example 9.18
Solve the complicated algebraic equation (Exercise (5)) in Chap 1.

⎪ 1 2 3 2 5 3

⎨ 2 x +x+ 2 + y + 2 + 3 =0
2y x

⎪ y 3 1
⎩ + + 4 + 5y4 = 0 .
2 2x x

Solutions The equation here is not the same as the one in Example 9.15, since at least in
Example 9.15, one equation can be substituted into the other one such that the equation
can be converted into a polynomial equation with one unknown. It is rather complicated,
or even not possible to do so, without the help from computers and leading edge software
tools. Not alone talking about the solutions, it is impossible to know how many solutions
are there.
With the help of MATLAB, it is no longer necessary to worry about these trivial things.
The original equations can be described as symbolic expressions in a natural way, so that
the quasi-analytical solutions of the original equations can be found.
>> syms x y;
f1(x,y)=x^2/2+x+3/2+2/y+5/(2*y^2)+3/x^3;
f2(x,y)=y/2+3/(2*x)+1/x^4+5*y^4; % describe equations in symbolic forms
268 Chapter 9 · Algebraic Equation Solutions

[x0,y0]=vpasolve(f1,f2), size(x0) % solve the equations and count them


e1=norm(f1(x0,y0)), e2=norm(f1(x0,y0)) % assess the errors
Substituting all the 26 solutions back into the original equations, very small errors are
found, which are as small as 10−33 , indicating the solutions are very accurate. It seems that
the extremely complicated equations can also be solved directly, and the solution process
is again as simple as the chick−rabbit cage problem. 

9.3.3 Quasi-Analytical Solutions of Quadratic Equations


The mathematical form of Riccati equation is

AT X + X A − X B X + C = 0, (9.20)

where all the matrices involved are n × n ones. Since the quadratic term X B X appears
in the equation, the equation is also referred to as a quadratic equation. Function
are() provided in the Control System Toolbox can be used to find a solution in the
Riccati equation. Only one solution can be found, not all of them. If the original form
of the equation is converted into the following form:

DX + X A − X B X + C = 0,
9 (9.21)

the equation is known as generalized Riccati equation. This kind of equation cannot be
solved with functions such as are(). In this section, function vpasolve() is illustrated
to find all the quasi-analytical solutions.

 Example 9.19
If the matrices are given below, solve the generalized Riccati equation.
⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎡ ⎤
−1 1 1 2 1 1 0 −2 −3 2 −1 −1
A = ⎣ 1 0 2 ⎦ , B = ⎣ −1 1 −1 ⎦ , C = ⎣ 1 3 3 ⎦ , D = ⎣ 1 1 −1 ⎦ .
−1 −1 −3 −1 −1 0 −2 −2 −1 1 −1 0

Solutions The crucial step in solving such an equation is how to describe the unknowns. For
this specific problem, the unknowns are x11 , x12 , · · · , x33 . It is quite natural to use sym()
function to define a variable matrix. The given matrices can be entered into MATLAB, such
that the generalized Riccati equation can be described as a symbolic expression. Function
vpasolve() can then be called in solving directly such an equation.
>> A=[-1,1,1; 1,0,2; -1,-1,-3]; B=[2,1,1; -1,1,-1; -1,-1,0];
C=[0,-2,-3; 1,3,3; -2,-2,-1]; D=[2,-1,-1; 1,1,-1; 1,-1,0];
X=sym('x%d%d',3); F=D*X+X*A-X*B*X+C; % define the unknowns & the equation
tic, X0=vpasolve(F), toc, X0.x11 % solve directly the equations
After 19.89 s of waiting, 20 solutions can be found from the above equation, among them,
the 1st, 2nd, 5th, 8th, 9th, 12th, 15th and 20th solutions are real matrices. The remaining
ones are complex conjugates. If the 15th solution is expected, it can be extracted with the
following methods, and the norm of the error matrix is 2.2902×10−31 .
9.3 · Solutions of Nonlinear Equations
269 9
>> k=15; % extracting the 15th solution
X1=[X0.x11(k),X0.x12(k),X0.x13(k); X0.x21(k),X0.x22(k),X0.x23(k);
X0.x31(k),X0.x32(k),X0.x33(k)],
norm(subs(F,X,X1)) % substituting back to the equation


It can be seen that it is rather complicated to extract one solution from the solution
set. The following MATLAB function is written to extract all the solutions in a single
call. The kth solution is returned in Y (:,:,k) in the three-dimensional array. It is
no longer necessary to extract the solutions one by one.
function Y=extract_sols(X,n,m,x)
arguments, X, n(1,1){mustBeInteger, mustBePositive}
m(1,1){mustBeInteger, mustBePositive}, x='x';
end
eval(['N=length(X.' x '11);'])
for k=1:N, for i=1:n, for j=1:m % extract the solution
eval(['Y(i,j,k)=X.' x int2str(i) int2str(j),...
'(' int2str(k) ');'])
end, end, end, end

 Example 9.20
Find the maximum error among the 20 solutions in Example 9.19.
Solutions Solve again the equations, and then the above function extracts all the solutions.
They can be substituted into the equation, such that the maximum error of 1.0861×10−26
can be found. It can be seen that the accuracy is much higher than the ones obtained under
double precision framework. The disadvantages are that it is rather time-consuming.
>> A=[-1,1,1; 1,0,2; -1,-1,-3]; B=[2,1,1; -1,1,-1; -1,-1,0];
C=[0,-2,-3; 1,3,3; -2,-2,-1]; D=[2,-1,-1; 1,1,-1; 1,-1,0];
X=sym('x%d%d',3); F=D*X+X*A-X*B*X+C; % define unknowns and the equation
tic, X0=vpasolve(F), toc % solve directly the equation
Y=extract_sols(X0,3,3); % extract all the solutions
for k=1:20, v(k)=norm(subs(F,X,Y(:,:,k))); end % error for each solution
err=double(max(v)) % find the maximum error


9.3.4 Numerical Solutions of Nonlinear Equations


Now consider numerical methods for an ordinary nonlinear equation f (x) = 0.
The above-mentioned solution tools seem to be rather powerful, however they
have their own inevitable limitations. The tools above are more suitable for solving
polynomial-type equations, although vpasolve() function can be used in solving
other types of equations with limited capabilities. On the other hand, since the solu-
tions are obtained under symbolic framework, the solution process is usually rather
slow. Better and more general solution methods are needed. In MATLAB, a practical
270 Chapter 9 · Algebraic Equation Solutions

numerical solver fsolve() is provided. The user needs to provide the description of
the equations and initial search values, so that the nonlinear solutions of any com-
plexity can be found. From the initial search point, one solution to the equation can
be found, under the syntaxes
x=fsolve(f ,x 0 ), % simplest form
[x,F,flag,out]=fsolve(f ,x 0 ,opts), % complete command
where f is a function handle for the equations, x 0 is the initial vector or matrix, whose
size is the same as f function. Normally the returned x is the numerical solutions of
the equation. Matrix F is the function value matrix at x. If the returned argument
flag is positive, it indicates that the solution process is successful. The argument out
returns some intermediate information. The user may indicate control options in the
argument opts, for algorithm selection and error tolerance specifications. These will
be demonstrated next through examples.

 Example 9.21
Solve the equations in Example 9.15 with the numerical solver.
Solutions In the original equation, the unknown variables are x and y, not the expected
vector x, therefore, it should be converted into standard form first before the solution
process. Assume that x1 = x, x2 = y, the variables in the original equations can be
9 substituted, such that the original equations can be converted into the standard form.
  
x12 + x22 − 1 = 0 x12 + x22 − 1
3 ⇒ f (x) = = 0.
0.75x1 − x2 − 0.9 = 0, 0.75x13 − x2 − 0.9

With the standard form, an anonymous function or a MATLAB function can be written
to describe f (x). The anonymous function is
>> f=@(x)[x(1)^2+x(2)^2-1; 0.75*x(1)-x(2)-0.9];
With the following MATLAB function, the equation can also be described, and saved into
the file c9mfun.m.
function y=c9mfun(x)
y=[x(1)^2+x(2)^2-1; 0.75*x(1)-x(2)-0.9];
end
Selecting an initial vector x 0 = [1; 2], the numerical solution of the equation can be found,
x = [0.9872, −0.1596], and the norm of the error vector is 1.7609×10−9 .
>> x0=[1;2]; x=fsolve(f,x0) % or x=fsolve(@c9mfun,x0)
norm(f(x)) % or norm(c9mfun(x))
If other initial search point is chosen, for instance, x 0 = [−1, 0], the equations can be
solved again, where another real solution x = [−0.1232, −0.9924] can be found, with error
norm of 3.0342×10−8 . The returned value of flag is 1, indicating the solution process is
successful. Besides, out structured variable displays other information, such as number of
iterations of 5, and number of anonymous function call of 18.
>> x0=[-1; 0]; [x,f0,flag,out]=fsolve(f,x0), norm(f0)

9.3 · Solutions of Nonlinear Equations
271 9
9.3.5 Control Parameters in Equation Solutions
It can be seen from the above process is that there still exist two questions: (1) how
to find complex solutions? (2) how to increase the accuracy?
For the first question, if the initial values are selected as complex numbers, some-
times it may yield complex solutions. Besides, for equations with real coefficients, the
complex conjugates of the solutions are likely the solutions of the original equation,
and they can be validated.
For the second question, control parameters can be assigned with optimset()
function. The commonly used options are shown in . Table 9.2.
MATLAB fsolve() solver searches for equation solution in an iterative way,
from the user-specified initial search point x 0 , where the solution in the kth iteration
is denoted as x k . Several terminate conditions are posed:
(1) If the maximum numbers of iterations or anonymous function calls are
exceeded.
(2) The difference of x between two consecutive iterations is smaller than the
predefined error tolerance, i.e., ||x k − x k−1 || ≤ ε1 .
(3) The absolute value of the function is smaller than the predefined error tolerance,
i.e., || f (x k )|| ≤ ε2 .
When Condition (1) is satisfied, a warning message is given, indicating that the
solution process is unsuccessful. The values of MaxIter or MaxFunEvals in the option
can be increased. In the latter two cases, the solution process is regarded successful.
Of course, to increase the accuracy of the solution process, tough error tolerances
TolX (i.e., ε1 ) or TolFun (i.e., ε2 ) must be specified.
Control parameters can be modified with the statements
ff=optimset; ff.TolX=1e-13; ff.TolFun=eps;

. Table 9.2 Commonly used control parameters in equation solutions

Parameters Descriptions

Display Display format of intermediate results, with option off for no display, iter
for step-by-step display, and notify for notification when diverge. Option
final for only display final values

MaxIter Maximum allowed number of iterations. If no solution is found, this value


can be increased

MaxFunEvals Maximum number of equation function calls

TolFun Error tolerance of the function. When the value of the function is smaller, the
solution process is completed

TolX Error tolerance of the solutions, if the difference at two consecutive solutions
is smaller, terminate the solution process
272 Chapter 9 · Algebraic Equation Solutions

 Example 9.22
In the demonstration in Example 9.21, under certain initial values, the solution error may
be as high as 10−8 . Find more accurate solutions.
Solutions In Example 9.21, if the initial value is chosen as x 0 = [−1, 0], the error obtained
is rather large. Under the same initial value, the following commands can be used to solve
again the equations, with the error norm of 1.1102×10−16 . It can be seen that the accuracy
of the solutions is significantly increased.
>> f=@(x)[x(1)^2+x(2)^2-1; 0.75*x(1)-x(2)-0.9];
ff=optimset; ff.TolX=eps; ff.TolFun=eps;
x0=[-1; 0]; [x,f0,flag,out]=fsolve(f,x0,ff), norm(f0)


9.4 Nonlinear Matrix Equations with Multiple Solutions


In real applications, some equations may have multiple solutions. For instance, in
the generalized Riccati equation demonstrated earlier, there are 20 solutions, while
in . Fig. 9.2, there are tens of intersections. It is hard to find the solutions one by
one, using the solver fsolve(), since different initial values can be chosen so as to
find more solutions. In this section, an idea for finding all the solutions is conceived,
9 based on the ideas, a MATLAB implementation is made, such that a universal solver
for multiple solutions in nonlinear matrix equations is written. With such a function,
the matrix equations even not possible to solve with vpasolve() can easily be solved.
The solutions of pseudo-polynomial equations are also explored.

9.4.1 Ideas and Implementation of Equation Solutions


In the fsolve() function, it can be seen that a random initial search point can be
generated, and from it a solution of the equation can be found. This part can be used
as the kernel of the solver, outside it, a loop structure can be used. Inside the loop,
a random point is generated inside the interested region, from that a solution can
be found with fsolve(). If the newly found solution is already recorded, the new
solution can be compared with the recorded one to see which is more accurate. If
the new one is more accurate, replace the recorded one with the new one, otherwise,
discard the solution. If the solution is an unrecorded one, record the solution.
The loop can be designed as an infinite loop. In this way, it is expected that all the
solutions in the interested region can be found. Based on such an idea, a universal
solver can be written for solving matrix equations. Several releases of the earlier
versions of the solver are made public [3]. In this version, some special processing
tasks are embedded. For instance, zero matrix is explored first to check whether it
is an isolated solution; if the solution obtained is more accurate than the recorded
one, replace the recorded one with the new solution; if a complex solution is found,
check whether its complex conjugate is also a solution; a predefined gap ε is used to
check whether two solutions are the same. Based on the considerations, the following
MATLAB solver is written. One of the benefits of the solver is that the longer the
solver is executed, the more accurate the solution can be found.
9.4 · Nonlinear Matrix Equations with Multiple Solutions
273 9
function more_sols(f,X0,A,tol,tlim,ff,gap0)
arguments
f, X0, A=1000, tol(1,1) double {mustBePositive}=eps
tlim(1,1) {mustBePositive}=10; ff=optimset; gap0(1,1)=5e-4
end
X=X0; ff.Display='off'; ff.TolX=tol; ff.TolFun=eps;
if isscalar(A), a=-0.5*A; b=0.5*A;
else, a=A(1); b=A(2); end
ar=real(a); br=real(b); ai=imag(a); bi=imag(b);
[n,m,i]=size(X0); tic % the solutions found so far
if i==0, X0=zeros(n,m); % judge whether zero an isolated one
if norm(f(X0))<tol, i=1; X(:,:,i)=X0; end
end
while (1) % infinite loop, which can be terminated by Ctrl+C keys
x0=ar+(br-ar)*rand(n,m); % generate random initial matrix
if ~isreal(A), x0=x0+(ai+(bi-ai)*rand(n,m))*1i; end
try [x,~,key]=fsolve(f,x0,ff); catch, continue; end
t=toc; if t>tlim, break; end % if no new solution found
if key>0, N=size(X,3); % if recorded, compare accuracy
for j=1:N % compare all the solutions
if norm(X(:,:,j)-x)<gap0; key=0; break; end, end
if key==0 % updates to more accurate one
if norm(f(x))<norm(f(X(:,:,j))), X(:,:,j)=x; end
elseif key>0, X(:,:,i+1)=x; % record the new solution
if norm(imag(x))>1e-8, i=i+1; X(:,:,i+1)=conj(x);
end, assignin('base','X',X); i=i+1, tic
end, assignin('base','X',X); % to MATLAB workspace
end, end, end
The syntax of the universal solver more_sols() is as follows:
more_sols(f ,X 0 ,a,,tlim ,opts,ε)
where f is the function handle, which can be an anonymous function or an
M-function describing the original algebraic equations. X 0 is a 3D array, used to
describe the size of the solutions. If used for the first time, it is recommended to set
X 0 as zeros(n,m,0), i.e., a blank 3D array, where n and m specify the size of the
solution matrix. The recorded solutions are automatically saved into the 3D array X
in MATLAB workspace. To continue the search process, X can be assigned to X 0 in
the syntax. The default value a is 1000, indicating the searching area of [−500, 500].
The default value of  is eps and the default value tlim is 30, indicating that if within
30 s, there is no new solution found, the solver is completed, ε is the gap to distinguish
whether two solutions are the same, with a predefined value of 10−5 . The user may
also assign control options opts, with a default value of optimset. The argument a
can also be selected as a complex number, indicating that complex solutions are also
needed. Besides, a can be assigned to the interval of [a, b].
The recorded solutions are written into 3D array X in MATLAB, where X(:,:,k)
stores the kth solution recorded.
274 Chapter 9 · Algebraic Equation Solutions

 Example 9.23
Find all the solutions of the equation in Example 9.14, in the interested range of −2π ≤
x, y ≤ 2π. How many solutions are there and what is the largest norm of the errors.
Solutions Let x1 = x and x2 = y, the standard form of the equation is
 
x12 e−x1 x2 /2 + e−x1 /2 sin(x1 x2 )
2
f (x) = = 0.
x22 cos(x2 + x12 ) + x12 ex1 +x2

Therefore the following statements are used to describe the equations, and find all the
solutions in the interested area.
>> f=@(x)[x(1)^2*exp(-x(1)*x(2)^2/2)+exp(-x(1)/2)*sin(x(1)*x(2));
x(2)^2*cos(x(2)+x(1)^2)+x(1)^2*exp(x(1)+x(2))];
more_sols(f,zeros(2,1,0),4*pi)
The implicit curve is drawn in . Fig. 9.2. If all the solutions are found, they can be super-
imposed on the implicit curve, as shown in . Fig. 9.4. It can be seen that there are 41
solutions in all, with maximum norm of error 1.3706×10−13 .
>> syms x y; f1=x^2*exp(-x*y^2/2)+exp(-x/2)*sin(x*y);
f2=y^2*cos(y+x^2)+x^2*exp(x+y); % describe the equations
fimplicit([f1 f2],[-2*pi,2*pi]) % draw the two implicit functions
9 x0=X(1,1,:); y0=X(2,1,:); ii=(abs(x0)<=2*pi & abs(y0)<=2*pi);
x0=x0(ii); y0=y0(ii); size(x0) % find the solutions in the region
hold on, plot(x0(:),y0(:),'og'); hold off % superimpose the solutions
er=[]; for i=1:size(X,3), er=[er f(X(:,:,i))]; end, norm(er,1)


9.4.2 Matrix Equation Solutions


Some of the matrix equations may not be solved with the vpasolve() function, since
before vpasolve() is used, manipulation is needed to describe the equation matrix
F(X) fully with symbolic expression. Therefore many mathematical functions cannot

-2

-4

-6
-6 -4 -2 0 2 4 6

. Fig. 9.4 Curve of the equation


9.4 · Nonlinear Matrix Equations with Multiple Solutions
275 9
be described in this way. In the solver here, anonymous function is needed to describe
the matrix equation, thus there is no such restriction with the new solver.

 Example 9.24
Find the 20 solutions in Example 9.19 with numerical method.
Solutions Anonymous function can be used to describe directly the matrix equation, such
that all the 20 numerical solutions can be found, returned in the 3D array X. It should be
noted that the precision is the best under double precision framework, while it is much less
accurate than the ones in quasi-analytical solutions.
>> A=[-1,1,1; 1,0,2; -1,-1,-3]; B=[2,1,1; -1,1,-1; -1,-1,0];
C=[0,-2,-3; 1,3,3; -2,-2,-1]; D=[2,-1,-1; 1,1,-1; 1,-1,0];
f=@(X)D*X+X*A-X*B*X+C; % describe equations in anonymous function
more_sols(f,zeros(3,3,0),1000+1000i) % find complex solutions


 Example 9.25
Consider the following nonlinear matrix equation:

e AX sin B X − C X + D = 0,

where A, B, C and D matrices are given in Example 9.19. Find as many real solutions as
possible.
Solutions If the solver in 7 Sect. 9.3.3 is used, command F = expm( A*X)*funm
(B*X,@sin) -C*X+ D fails to generate the symbolic expression F . Therefore, the quasi-
analytical solutions cannot be found. With the following commands, the complicated non-
linear matrix equation can be described. With the new solver, 120 real solutions are found
so far. The user may continue trying by themselves and see whether more real solutions can
be found. The currently found solutions are stored in the data file data9_25.mat.
>> A=[2 1 9; 9 7 9; 6 5 3]; B=[0 3 6; 8 2 0; 8 2 8];
C=[7 0 3; 5 6 4; 1 4 4]; D=[3 9 5; 1 2 9; 3 3 0];
f=@(X)expm(A*X)*funm(B*X,@sin)-C*X+D; % matrix equation description
more_sols(f,zeros(3,3,0),10); X % solve nonlinear matrix equation


9.4.3 Solutions of Pseudo-Polynomial Equations


The mathematical form of pseudo-polynomial p(s) is given in (6.1), where p(s) = 0 is
referred to as a pseudo-polynomial equation. So far there is no other methods capable
of solving such pseudo-polynomial equations. The solver more_sols() presented in
this section can be called to possibly find all the solutions in pseudo-polynomial
equations.
276 Chapter 9 · Algebraic Equation Solutions

 Example 9.26
Solve the irrational pseudo-polynomial equation
√ √ √
s 5 + 25s 3 + 16s 2 − 3s0.4 + 7 = 0.

Solutions The solver more_sols() may be the only method capable of solving the given
equation. The following commands can be issued directly to solve the pseudo-polynomial
equation. It can be seen that there are only two solutions in the irrational pseudo-polynomial
equation, located at s = −0.0812±0.2880j. Substituting them back to the original equation,
the error obtained is 9.1551×10−16 , which is the most accurate one possible under double
precision framework.
>> f=@(s)s^sqrt(5)+25*s^sqrt(3)+16*s^sqrt(2)-3*s^0.4+7;
more_sols(f,zeros(1,1,0),100+100i); x0=X(:) % solve equation
err=norm(f(x0(1))) % validate the solutions


9.5 Exercises
(1) Judge whether the following linear equation has solutions:
9
⎡ ⎤ ⎡ ⎤
16 2 3 13 1
⎢ 5 11 10 8⎥ ⎢3⎥
⎢ ⎥ X = ⎢ ⎥.
⎣ 9 7 6 12 ⎦ ⎣4⎦
4 14 15 1 7

(2) Find the analytical solutions for the following equation and validate them:
⎡ ⎤ ⎡ ⎤
2 9 4 12 5 8 6 1 9
⎢ 12 2 8 7 3 3 7⎥ ⎢ 5 12 ⎥
⎢ ⎥ ⎢ ⎥
⎢ 3 0 3 5 7 5 10 ⎥ ⎢ 4 12 ⎥
⎢ ⎥ ⎢ ⎥
⎢ 3 11 6 6 9 9 1⎥ X = ⎢ 10 9 ⎥.
⎢ ⎥ ⎢ ⎥
⎢ 11 2 1 4 6 8 7⎥ ⎢ 0 5 ⎥
⎢ ⎥ ⎢ ⎥
⎣ 5 −18 1 −9 11 −1 18 ⎦ ⎣ 10 18 ⎦
26 −27 −1 0 −15 −13 18 −20 2

(3) Solve the following linear algebraic equation:




⎪ x1 + 2x2 + x3 + 2x5 + x6 + x8 =1

2x1 + x2 + 4x3 + 4x4 + 4x5 + x6 + 3x7 + 3x8 =1

⎪ 2x1 + x3 + x4 + 3x5 + 2x6 + 2x7 + 2x8 =0

2x1 + 4x2 + 2x3 + 4x5 + 2x6 + 2x8 =2.

(4) Find the null space matrix Z, such that the homogeneous equation AZ = 0 is
satisfied.
9.5 · Exercises
277 9
⎡ ⎤
3 1 2 1 1
⎢1 2 3 3 2⎥
⎢ ⎥
A=⎢
⎢4 1 4 2 1⎥⎥.
⎣4 4 4 4 4⎦
3 2 1 1 2
(5) Solve the following matrix equation:
⎡ ⎤
⎡ ⎤ 0 1 0 0 1 ⎡ ⎤
1 2 3 ⎢1 0 1 2 2⎥ 1 1 2 2 2
⎢ ⎥
⎣3 5 7⎦ X ⎢
⎢1 2 0 0 2⎥⎥ = ⎣1 1 2 2 2⎦.
4 9 2 ⎣0 0 1 1 1⎦ 1 1 2 2 2
1 0 0 2 1

(6) Check whether the following equation has solutions, If there are, find all the
solutions.
⎡ ⎤
⎡ ⎤ 0 0 0 ⎡ ⎤
−1 −1 0 0 −1 0 ⎢ 1 1 −1 ⎥ 4 4 0
⎢ ⎥
⎣ 1 1 −1 0 −1 −1 ⎦ X ⎢ −1 −1 0 ⎥ = ⎣ −2 −2 −2 ⎦ .
⎢ ⎥
1 1 0 0 1 0 ⎣ −1 −1 0 ⎦ −4 −4 0
0 0 1

(7) Solve equation A1 X B 1 + A2 X B 2 = C and validate results, where


 
4 + 4j 1+j 3+j 2 + 2j
A1 = , A2 = ,
1 + 4j 4 + 2j 1 + 2j 4 + 2j
⎡ ⎤ ⎡ ⎤
3 4 1 1 2 1 44
⎢2 4 1 1⎥ ⎢3 4 23⎥
B1 = ⎢
⎣1
⎥ , B2 = ⎢ ⎥,
2 1 2⎦ ⎣4 1 43⎦
4 3 1 2 2 3 23

141 + 47j 77 + 3j 98 + 27j 122 + 37j
C= .
115 + 58j 72 + 4j 93 + 34j 106 + 46j
(8) If the matrices A1 and B 1 in Exercise (7) are changed into the following singular
ones, is the original equation still solvable? Find the solutions and validate the
results. ⎡ ⎤
 16 2 3 13
1 3 ⎢ 5 11 10 8⎥
A1 = , B1 = ⎢ ⎣
⎥.
4 2 9 7 6 12 ⎦
4 14 15 1
(9) Find numerical and analytical solutions of the following Sylvester equation and
validate the results:
278 Chapter 9 · Algebraic Equation Solutions

⎡ ⎤ ⎡ ⎤
3 −6 −4 0 5 ⎡ ⎤ −2 1 −1
⎢ 1 4 2 −2 4⎥ 3 −2 1 ⎢ 4 1 2⎥
⎢ ⎥ ⎢ ⎥
⎢ −6 3 −6 3⎥ + ⎣ −2 −9 2⎦ = ⎢ −6 1⎥
⎢ 7 ⎥ X X ⎢ 5 ⎥.
⎣ −13 10 0 −11 0⎦ −2 −1 9 ⎣ 6 −4 −4 ⎦
0 4 0 3 4 −6 6 −3

(10) Find the analytical solution to the following matrix equation and validate the
results. Find out for what value of a, when there is no solution in the equations.
⎡ ⎤ ⎡ ⎤ ⎡ ⎤
−2 2 c −2 −1 2 0 −1 0
⎣ −1 0 −1 ⎦ X + X ⎣ a 3 0 ⎦ + ⎣ −1 1 0 ⎦ = 0.
1 −1 2 b −2 2 1 −1 −1

(11) Solve the discrete Lyapunov equation AX AT − X + Q = 0. Find out the


numerical and analytical solutions, where
⎡ ⎤ ⎡ ⎤
−2 −1 0 −3 −12 −16 14 −8
⎢ −2 −2 −1 −3 ⎥ ⎢ −20 −25 11 −20 ⎥
A=⎢
⎣ 2
⎥, Q = ⎢ ⎥.
2 −3 0⎦ ⎣ 3 1 −16 1⎦
−3 1 1 −3 −4 −10 21 10

9 (12) Solve the multi-term Sylvester equation and validate the results. The matrices
are given in Exercise (7). If A1 and B 1 are changed into the singular matrices
in Exercise (8), solve the multi-term Sylvester equation again, and validate the
solutions.
(13) Solve the following simultaneous equations, and formulate the conditions that
only real solutions exist:

ax + cy = 2
bx2 + cx + ay2 − 4xy = −3.

(14) The mathematical form of a Riccati equation is P A+ AT P− P B R−1 B T P+ Q =


0, where ⎡ ⎤ ⎡ ⎤
−27 6 −3 9 0 3
⎢ 2 −6 −2 −6 ⎥ ⎢ ⎥
A=⎢ ⎥ , B = ⎢ 16 4 ⎥ ,
⎣ −5 0 −5 −2 ⎦ ⎣ −7 4 ⎦
10 3 4 −11 9 6
⎡ ⎤
6 5 3 4 
⎢5 6 3 4⎥
Q=⎢ ⎥, R = 4 1 .
⎣3 3 6 2⎦ 1 5
4 4 2 6
Solve the equations and find matrix P. Validate the solutions.
(15) Find all the solutions to the generalized Riccati equation AX + X D − X B X +
C = 0, and validate the results, where
9.5 · Exercises
279 9
⎡ ⎤ ⎡ ⎤ ⎡ ⎤ ⎡ ⎤
2 1 9 0 3 6 7 0 3 3 9 5
A = ⎣9 7 9⎦, B = ⎣8 2 0⎦, C = ⎣5 6 4⎦, D = ⎣1 2 9⎦.
6 5 3 8 2 8 1 4 4 3 3 0

(16) Find all the quasi-analytical solutions for the equations in Exercise (15), and
validate the results.
(17) Find all the equations of the following matrix equation:

AX 3 + X 4 D − X 2 B X + C X − I = 0,

where the constant matrices are given in Exercise (15).


(18) If the equation in Exercise (15) is changed to AX + X D − X B X T + C = 0,
solve the equation again and find all the quasi-analytical solutions.
(19) Solve the following simultaneous equations [4]:

0.5 sin x1 x2 − 0.25x
 2 /π − 0.5x1 = 0
(1 − 0.25/π) e2x1 − e + ex2 /π − 2ex1 = 0 ,

where 0.25 ≤ x1 ≤ 1 and 1.5 ≤ x2 ≤ 2π.


(a) In Reference [4], two solutions are provided. If the interested is changed
to x1 ∈ (−5, 5), x2 ∈ (−10, 10), find all the solutions, and show the solutions
graphically, and see whether there are unfound real solutions.
(b) Are there any further real solutions.
(20) Solve the following simultaneous nonlinear equations in the region −π ≤ x, y ≤
π: 
x2 e−xy /2 + e−x/2 sin(xy) = 0
2

y cos(x + y2 ) + x2 ex+y = 0.
2

(21) Find the solutions [4]

b b(1 + aT0 ) c/T T


T ec/T − e + − 1 = 0,
T0 aT0 T0

where 100 ≤ T ≤ 1000. The constants are a = −1000/(3H), b = 1.344×109 ,


c = −7548.1193, T0 = 298. The constant H has three options: −50000,
−35958 and −35510.3.
(22) Solve the following simultaneous linear equations with solve() function and
validate the solutions:


⎪ x1 + x2 + x3 + x4 + x5 = 7


⎨ 3x 1 + 2x2 + x3 + x4 − 3x5 = −28
x2 + 2x3 + 2x4 + 6x5 = 49



⎪ 5x 1 + 4x2 + 3x3 + 3x4 − x5 = −14

4x2 + 3x3 − 5x4 = 64.

(23) Solve the pseudo-polynomial equation x2.3 + 5x1.6 + 6x1.3 − 5x0.4 + 7 = 0.


√ √ √
(24) Solve the pseudo-polynomial equation x 11 + 2x 7 + 3x 2 + 4 = 0.
280 Chapter 9 · Algebraic Equation Solutions

(25) For the given polynomial equation

p(s) = s8 + 12s7 + 62s6 + 180s5 + 321s4 + 360s3 + 248s2 + 96s + 16 = 0.

Find the solutions with different methods. Note the quasi-analytical solutions
can be found with the solver provided in the Symbolic Math Toolbox. The
numerical solutions can be found in many ways. For instance, with the pseudo-
polynomial equation solver, with roots() function described earlier in this
section, and find the eigenvalues of the constructed companion matrix.
(26) Find possibly all the complex solutions to the following complex equation [5].

(18s + 9)e−s + 3 + 29s + 46s2 + 20s3 = 0.

(27) The more_sols() solver is not restricted to solving real coefficient algebraic
equations. Solve pseudo-polynomial equations with complex coefficients and
orders, and validate the solutions.
√ √
p(x) = (1 + 2j)x1+ 3j
+ (1 − 3j)x 2j
+ 4x + 6 + 7j = 0.

9 9.6 Mini-Projects

1. Balancing Chemical Reaction Equations


Chemical reaction equation balancing is a very important issue in chemistry. The
so-called balancing means to find appropriate coefficients in the equations, such that
the chemical equation holds. An example is given next to show how to balance the
equation with linear algebraic equation solving method [6].
Consider a chemical reaction: Mg+HCl → MgCl2 +H2 . To balance the equation,
it is necessary to rewrite it into an equation form x1 Mg + x2 HCl = x3 MgCl2 + x4 H2 .
How to choose x1 , x2 , x3 and x4 such that the equation holds?
Considering element Mg on both sides of the equation, it is found that x1 = x3 , or
x1 − x3 = 0. Considering the other elements, the following linear algebraic equation
and its matrix form can be established:
⎧ ⎡ ⎤
⎨ x1 − x3 = 0 1 0 −1 0
x2 − 2x4 = 0 ⎣0 1 0 −2 ⎦ = 0.

x2 − 2x3 = 0, 0 1 −2 0

It can be seen that this algebraic equation has four unknown but has three equa-
tions. With rref() function, the reduced row echelon form of the matrix can be
found. ⎡ ⎤
1 0 0 −1
R = ⎣ 0 1 0 −2 ⎦ .
0 0 1 −1
Let x4 = 1, it is easily found from R matrix that x1 = 1, x2 = 2, x3 = 1, such that
the balanced chemical reaction equation is Mg + 2HCl = MgCl2 + H2 .
References
281 9
Balance the following chemical reaction equations with the same method:
(1) KClO3 + HCl → KCl + Cl2 + H2 O
(2) Pb(N2 )3 + Cr(MnO4 )2 → Cr2 O3 + MnO2 + Pb3 O4 + NO
(3) K4 Fe(CN)6 +KMnO4 +H2 SO4 → KHSO4 +Fe2 (SO4 )3 +MnSO4 +HNO3 +
CO2 + H2 .

2. Solve Simultaneous Nonlinear Equations


A powerful algebraic equation solver, more_sols(), is provided in the book, aiming
at solving nonlinear matrix equations with multiple solutions. Explore the solutions
of the following equations.
(1) Solve the following kinetic equation for a robot, and see how many real solu-
tions can be found [4]:

⎪ 4.731×10−3 x1 x3 − 0.3578x2 x3 − 0.1238x1 + x7 − 1.637×10−3 x2 − 0.9338x4 = 0.3571



⎪ 0.2238x1 x3 + 0.7623x2 x3 + 0.2638x1 − x7 − 0.07745x2 − 0.6734x4 − 0.6022 = 0



⎪ x6 x8 + 0.3578x1 + 4.731×10−3 x2 = 0

⎨ −0.7623x + 0.2238x + 0.3461 =
1 2 0

⎪ x12 + x22 − 1 = 0



⎪ x32 + x42 − 1 = 0



⎪ x52 + x62 − 1 = 0

x72 + x82 − 1 = 0,

where −1 ≤ xi ≤ 1, i = 1, 2, . . . , 8. Validate the solutions. If the searching area is


increased, can you find more solutions? Are there any complex solutions?
(2) Solve the following simultaneous algebraic equations [4]:


⎪ x1 x2 + x1 − 3x5 = 0

⎪ 2x1 x2 + x1 + 3R10 x22 + x2 x32 + R7 x2 x3 + R9 x2 x4 + R8 x2 − Rx5 =
⎨ 0
2x2 x32 + R7 x2 x3 + 2R5 x32 + R6 x3 − 8x5 = 0



⎪ R9 x2 x4 + 2x42 − 4Rx5 = 0

x1 x2 + x1 + R10 x22 + x2 x32 + R7 x2 x3 + R9 x2 x4 + R8 x2 + R5 x32 + R6 x3 + x42 = 1,

where 0.0001 ≤ xi ≤ 100, i = 1, 2, 3, 4, 5. The constants are R = 10, R5 = 0.193,


R6 = 4.10622×10−4 , R7 = 5.45177×10−4 , R8 = 4.4975×10−7 , R9 = 3.40735×10−5 ,
R10 = 9.615×10−7 .

References
1. Mathematics Handbook Editorial Group (1979) Mathematics handbook (in Chinese)[M]. Peoples’
Education Publishers, Beijing
2. Beezer RA (2012) A first course in linear algebra, version 2.99[R/OL]. Department of Mathematics
and Computer Science University of Puget Sound, 1500 North Warner, Tacoma, Washington, pp
98416−1043, 7 http://linear.ups.edu/
3. Xue DY, Chen YQ (2016) Scientific computing with MATLAB[M], 2nd edn. CRC Press, Boca Raton
4. Floudas CA, Pardalos PM, Adjiman CS et al (1999) Handbook of test problems in local and global
optimization[M]. Kluwer Scientific Publishers, Dordrecht
5. Xue DY (2022) Computer-aided control system design: MATLAB language and its applications (in
Chinese)[M], 4th edn. Tsinghua University Press, Beijing
6. Xue DY (2020) Linear algebra and matrix computations with MATLAB[M]. De Gruyter, Berlin
283 10

Ordinary Differential
Equation Solutions
Contents

10.1 Analytical Solutions of ODEs – 284


10.1.1 Linear ODEs with Constant Coefficients – 284
10.1.2 High-Order Linear ODE Sets – 287
10.1.3 Time-Varying Linear ODEs – 288
10.1.4 Nonlinear ODEs – 289

10.2 Initial Value ODE Problems – 290


10.2.1 Standard Form of First-Order Explicit ODEs – 291
10.2.2 Direct Solutions of ODEs – 291
10.2.3 Validation of ODE Solutions – 293
10.2.4 ODE Conversions – 294
10.2.5 Stiff ODEs – 300

10.3 Special ODEs – 302


10.3.1 Differential–Algebraic Equations – 302
10.3.2 Implicit Differential Equations – 303
10.3.3 Delay Differential Equations – 305

10.4 Boundary Value Problems – 309


10.4.1 Mathematical Forms of Boundary Value Problems – 309
10.4.2 Solutions of BVPs – 310
10.4.3 BVPs with Undetermined Coefficients – 312

10.5 Exercises – 313

10.6 Mini-Projects – 319

References – 320

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_10
284 Chapter 10 · Ordinary Differential Equation Solutions

In scientific research or even in everyday life and social science, some phenomena can
be described by differential equations. Therefore, differential equations are regarded
as the mathematical foundation in dynamic system modeling. Differential equations
are classified as ordinary differential equations (ODEs) and partial differential equa-
tions (PDEs). In this chapter, solutions of various ODEs are presented. For linear
ODEs, analytical solutions are explored. Numerical solutions are presented to var-
ious ODEs such as stiff ODEs, implicit ODEs, differential–algebraic equations and
delay differential equations. Boundary value problems are also explored.
In 7 Sect. 10.1, analytical solutions of ODEs are introduced, with concentrations
on linear ODEs with constant coefficients. The solutions of some extremely simple
nonlinear ODEs are also discussed. The remaining parts of the chapter introduce
numerical solutions of ODEs. In 7 Sect. 10.2, initial value problems of ODEs are
presented. The standard form of the ODEs is presented first, MATLAB-based ODE
solvers are discussed to solve the equations. Besides, other ODE types are studied, and
methods are introduced to convert them into the standard forms so that numerical
solutions can be found. In 7 Sect. 10.3, solutions of special ODEs, such as implicit
ODEs, differential–algebraic equations and delay differential equations are all illus-
trated. In 7 Sect. 10.4, solutions of boundary value problems are presented.

10.1 Analytical Solutions of ODEs


In college mathematics courses, the analytical solution methods for linear ODEs with
10 constant coefficients are introduced. The corresponding polynomial equations are
solved first, and based on the solutions, the analytical solutions can be constructed.
In fact, with the powerful tools such as MATLAB, the solution process of ODEs is
significantly simplified. Function dsolve() provided in the Symbolic Math Toolbox
can be used to solve directly the ODEs.
The syntaxes of the function dsolve() is quite similar to function solve() in
7 Chap. 9. The user needs to describe the differential equations in the allowed format,
and then call the solver to find the solutions directly. The syntaxes of the function are
>> syms t x(t);
x=dsolve(diff(x)==x*(1-x^2)+1) % analytical solution does not exist
In earlier versions of MATLAB, symbolic and string descriptions are allowed to
describe the equations fi . In the later versions, string descriptions may no longer be
supported. Therefore, it is recommended to use symbolic expressions to describe the
differential equations. The string description is not discussed here.

10.1.1 Linear ODEs with Constant Coefficients


If the ODEs can be expressed by a symbolic expression, function dsolve() can be
called directly to find the general solutions of the ODEs. Examples are given next to
demonstrate the solution process.
10.1 · Analytical Solutions of ODEs
285 10

 Example 10.1
Assume that the input signal is u(t) = e−5t cos(2t + 1) + 5, find the general solution of the
ODE
y(4) (t) + 10y (t) + 35y (t) + 50y (t) + 24y(t) = u (t) + 2u(t).

Solutions Since function y(t) is used, it is better to set y as a symbolic function y(t),
then some intermediate variables can be defined to describe the derivatives of y(t). For
instance, the intermediate variable y3 can be used to describe the derivative term y (t). For
convenience, such notation makes the description of ODEs simpler. With these prepared,
symbolic expression describes directly the ODE. Then call function dsolve() to get the
analytical solution. Note that when using symbolic expressions, the equal sign should be
rewritten as ==.

>> syms t y(t); u=exp(-5*t)*cos(2*t+1)+5;


y1=diff(y); y2=diff(y,2); y3=diff(y,3); y4=diff(y,4);
y0=dsolve(y4+10*y3+35*y2+50*y1+24*y==diff(u)+2*u); % solve the ODE
y0(t)=simplify(y0) % simplify the result
where the analytical solution is found, where Ci is arbitrary constant, also known as unde-
termined coefficients.

1 −5t   5
y(t) = C1 e−4t + C2 e−3t + C3 e−2t + C4 e−t + e cos(2t + 1) + sin (2t + 1) + .
40 24

If the solution is substituted back to the ODE, the error is 0. Therefore, no matter what are
the values of Ci , the solution obtained satisfies the original equation.
>> simplify(diff(y0,4)+10*diff(y0,3)+35*diff(y0,2)+50*diff(y0)+...
24*y0-diff(u)-2*u)


 Example 10.2
Consider again the ODE in Example 10.1, if the initial values are y(0) = 3, y (0) = 2,
y (0) = y (0) = 0, find the analytical solution of the ODE.
Solutions It is seen in Example 10.1 that, the general solution has four undetermined coeffi-
cients. Therefore, there are four independent conditions. The coefficients can be determined
uniquely from the conditions, such that a solution can be found. Since the solution is rather
lengthy, it is omitted here. The curve of the solution can be drawn as shown in . Fig. 10.1.

>> syms t y(t); u=exp(-5*t)*cos(2*t+1)+5;


y1=diff(y); y2=diff(y,2); y3=diff(y,3); y4=diff(y,4);
y0=dsolve(y4+10*y3+35*y2+50*y1+24*y==diff(u)+2*u,...
y(0)==3,y1(0)==2,y2(0)==0,y3(0)==0);
y0=simplify(y0), fplot(y0,[0,2*pi]) % solve equation and draw plot

286 Chapter 10 · Ordinary Differential Equation Solutions

3.5

2.5

1.5

0.5
0 1 2 3 4 5 6

. Fig. 10.1 Solution of the ODE

 Example 10.3
Consider still the ODE in Example 10.1. Assume that there are given points in the solution,
y(0) = 1, y (π) = 0, y (2π) = y (2π) = 0. Solve the equation and validate the result. Draw
the curve of the solution.
Solutions Compared with the problem in Example 10.2, the points t = π and t = 2π are
also known. Therefore, similar commands can be issued to solve directly the ODE. It can
be validated that the differences at the given function values and the given point, the error
10 is at 10−69 level, such that the original conditions are satisfied. The curve of the function
is obtained as shown in . Fig. 10.2.

>> syms t y(t); u(t)=exp(-5*t)*cos(2*t+1)+5;


y1=diff(y); y2=diff(y,2); y3=diff(y,3); y4=diff(y,4);
y0(t)=dsolve(y4+10*y3+35*y2+50*y1+24*y==diff(u)+2*u,...
y(0)==1,y1(pi)==0,y1(2*pi)==0,y2(2*pi)==0);

0.9

0.8

0.7

0.6

0.5

0 1 2 3 4 5 6

. Fig. 10.2 Another solution of the ODE


10.1 · Analytical Solutions of ODEs
287 10
err=[y0(0),subs(diff(y0),t,[pi,2*pi]),subs(diff(y0,2),t,2*pi)];
double(err-[1 0 0 0]), fplot(y0,[0,2*pi]) % solve ODE and draw plot
Although the manual solution to the problem is extremely complicated, or even not possible
to get the solutions, the solution process of the ODE is as easy as the one in Example 10.2,
with the help of computers. Describe the given points in a usual way such that the solution
can be found. 

10.1.2 High-Order Linear ODE Sets


If ODE sets are known, they can still be expressed directly with symbolic expressions.
Then call function dsolve() to solve the ODE set. If certain points are given, the
conditions can be entered into the solver, such that the solution of the equations can
be found.

 Example 10.4
Solve the following linear ODE set.
 
x (t) + 2x (t) = x(t) + 2y(t) − e−t
y (t) = 4x(t) + 3y(t) + 4e−t .

Solutions Linear ODE set can be solved directly with function dsolve(). The following
MATLAB commands can be used to solve the equation:

>> syms t x(t) y(t) % declare symbolic variable and function


[x,y]=dsolve(diff(x,2)+2*diff(x)==x+2*y-exp(-t),...
diff(y)==4*x+3*y+4*exp(-t)) % ODE solution
The general solution of the ODE set can be found.
⎧ √ √

⎨ −t −t 1+ 6 t 1− 6 t
x(t) = −6te + C1 e + C2 e + C3 e
 √  √
⎩ y(t) = 6te−t − C e−t + 22 + √6C e 1+ 6 t + 22 − √6C e 1− 6 t + e−t /2.

1 2 3

 Example 10.5
Find the analytical solutions of the linear ODE set.
⎧ 2


d y(x)
+ 2y(x) + 4z(x) = ex

dx2

⎪ 2
⎩ d z(x) − y(x) − 3z(x) = −x.
dx2
Solutions Declare first y and z as functions of x. Then with the following commands, solve
the linear ODE set in the example:

>> syms x y(x) z(x)


[y1,z1]=dsolve(diff(y,2)+2*y+4*z==exp(x),diff(z,2)-y-3*z==-x)
288 Chapter 10 · Ordinary Differential Equation Solutions

y1=simplify(y1), z1=simplify(z1) % ODE solution and simplification


simplify(diff(y1,x,2)+2*y1+4*z1-exp(x))
simplify(diff(z1,x,2)-y1-3*z1+x) % ODE solution and validation
The solutions are shown below, and through validation, it is seen that the original ODE
set is satisfied.
⎧ √ √ √ √

⎪ 2 2
x
⎨ y1 (x) = e − 2x − 4C1 cos x − 4C2 sin x − C3 e 2x + C4 e− 2x
2 2
√ √ √ √

⎪ e x 2 2
⎩ z (x) = x − + C1 cos x + C2 sin x + C3 e 2x − C4 e− 2x .
1
2 2 2


10.1.3 Time-Varying Linear ODEs


If the ODE contains coefficients of independent variables or other parameters, the
differential equations are referred to as time-varying ODEs. Some time-varying ODEs
can be solved analytically with dsolve() function. The solutions obtained may con-
tain special functions. Most of the time-varying ODEs do not have analytical solu-
tions. Of course, dsolve() function is incapable of solving the problems either.

10  Example 10.6
Consider the second-order time-varying linear ODE.

y (x) + ay (x) + (bx + c)y(x) = 0.

Solutions Describe the ODE with symbolic expression, the following commands can be
used.

>> syms x a b c y(x)


y=dsolve(diff(y,2)+a*diff(y)+(b*x+c)*y==0) % solve the ODE
The following analytical solution to the ODE can be found:

C −a2 + 4c + 4bx C −a2 + 4c + 4bx


y(x) = √ 1 Ai − √3
+ √ 2 Bi − √3
,
eax 4 b2 eax 4 b2

where the mathematical forms of the special Airy functions Ai(·) and Bi(·) are [1]
⎧ ∞

⎪ 1 t3

⎪ Ai(z) = cos + zt dt
⎨ π 0 3
 

⎪ 1 ∞ t3 t3

⎪ = exp − + zt + sin + zt
⎩ Bi(z) dt.
π 0 3 3


10.1 · Analytical Solutions of ODEs
289 10

 Example 10.7
Find the analytical solution of the third-order time-varying ODE in t ∈ (0.2, π) [2], and
draw the solution.

x5 y (x) = 2(xy (x) − 2y(x)), y(1) = 1, y (1) = 0.5, y (1) = −1.

Solutions No matter which types of ODEs are there, the solver can be tried, to see whether
there are analytical solutions or not. For the differential equation and the initial conditions
here, the intermediate variables can be defined so as to describe the ODE. If the solution is
found, the solution curve can also be drawn, as shown in . Fig. 10.3.

>> syms x y(x); y1=diff(y); y2=diff(y1); y3=diff(y2);


y0=dsolve(x^5*y3==2*(x*y1-2*y),y(1)==1, y1(1)==0.5, y2(1)==-1)
y=simplify(y0); fplot(y,[0.2,pi]) % solve ODE and draw plot
The analytical solution found is
√ √
3 2 √2 2 −√2/x 3 2 −√2 2 √2/x
y(x) = x2 − e x e + e x e .
8 8


10.1.4 Nonlinear ODEs


There are extremely few nonlinear ODEs where analytical solutions exist. Almost all
the nonlinear ODEs do not have analytical solutions. Therefore, numerical solutions
are usually considered. Of course, dsolve() function can be tried first.

-1

0.5 1 1.5 2 2.5 3

. Fig. 10.3 The solution of the equation


290 Chapter 10 · Ordinary Differential Equation Solutions

 Example 10.8
Solve the following first-order nonlinear ODE:

dy(t)
+ 8y(t) + y2 (t) = −15, y(0) = 0.
dt

Solutions The following commands can be used and the analytical solution can be found
y = −(15e2t − 15)/(5e2t − 3). It can be seen that there are no special skills needed in finding
the analytical solutions. Just specify the ODE in symbolic form and call the solver.

>> syms t y(t); y=dsolve(diff(y)+8*y+y^2==-15, y(0)==0);


simplify(y) % simplify the solution


 Example 10.9
Find the analytical solution of the first-order ODE x (t) = x(t)(1 − x2 (t)).
Solutions The nonlinear ODE can be solved directly with the command dsolve().

>> syms t x(t); x=dsolve(diff(x)==x*(1-x^2)) % direct solution



The solution x(t) = −1/ eC−2t − 1 can be found. Besides, constants ±1 and 0 are also
the analytical solutions. 
10
 Example 10.10
Try to find the analytical solution of x (t) = x(t)(1 − x2 (t)) + 1.
Solutions Slight change is made to the ODE in Example 10.9, where 1 is added to the
right side of the ODE. The following commands can be tried, but the solution process is
not successful, and a warning message “Unable to find symbolic solution” is obtained,
indicating that there is no analytical solution.

>> syms t x(t);


x=dsolve(diff(x)==x*(1-x^2)+1) % analytical solution does not exist


It is seen that the solver dsolve() cannot be used in solving nonlinear ODEs
since the solutions usually do not exist. Therefore, numerical solutions must be found
instead. In the subsequent sections, numerical solutions to various ODEs are studied.

10.2 Initial Value ODE Problems


Many numerical solvers for ODEs are provided in MATLAB, while most of them can
only be used in solving first-order explicit ODEs. In this chapter, first-order explicit
ODEs are referred to as the standard ODEs. Mathematical form of the standard
ODEs is presented first in this section, followed by the presentations on the solvers
10.2 · Initial Value ODE Problems
291 10
and solution procedures. Conversion methods from various ODEs to standard ODEs
are discussed. Validation methods of ODE solutions are presented.

10.2.1 Standard Form of First-Order Explicit ODEs


The mathematical form of a first-order explicit ODE is
 
x  (t) = f t, x(t) , (10.1)
 T
where the unknown vector x(t) = x1 (t), x2 (t), . . . , xn (t) is known as the state vec-
 T
tor, function vector f (·) = f1 (·), f2 (·), . . . , fn (·) can be of any nonlinear functions.
 T
If the initial state vector x 0 (t0 ) = x1 (t0 ), x2 (t0 ), . . ., xn (t0 ) is known, in the
first-order explicit ODE in (10.1), the problem is referred to as initial value problem
of ODEs.

10.2.2 Direct Solutions of ODEs


If the first-order explicit ODE is described by an anonymous function or an
M-function, the solvers provided in MATLAB can be used to find the numerical
solutions directly. The often used solvers in MATLAB are listed in . Table 10.1.
Comparisons on these solvers will be studied through dedicated examples.
Normally, for non-stiff ODEs, the solver ode45() is recommended, while for stiff
ODEs, the solver ode15s() is recommended. If the two functions both fail, other
solvers can be tried. The syntaxes of these functions are the same:

. Table 10.1 Solvers for first-order explicit ODEs

Solvers Descriptions

ode45() 4/5th-order Runge–Kutta–Felberg algorithm, the first one to be tried

ode23() 2/3rd-order Runge–Kutta algorithm, efficiency is low, not recommended

ode15s() Stiff ODE solver, the order is changed adaptively between first and fifth
according to the actual situations. Sometimes, the precision is not very high

ode113() Variable-step, variable order Adams–Bashforth–Moulton predict–correct


algorithm

ode23s() Applies to stiff ODEs

ode23tb() Another stiff ODE solver

ode78() Newly implemented solver, also ode89()

ode87() 7/8th-order solver, a third-party solver [3]. The efficiency is rather high in
certain ODEs
292 Chapter 10 · Ordinary Differential Equation Solutions

[t,x]=solver(f ,tspan,x 0 ,control parameters)


sol=solver(f ,tspan,x 0 ,control parameters)
where, the solvers are listed in . Table 10.1; f is the function handle for the ODE
description, which can be an anonymous function or an M-function; x 0 is the initial
state vector x(t0 ); tspan is a time vector, usually selected as [t0 ,ttn ], indicating the
solution interval, and t0 > tn is allowed; control parameters contain specifications for
the solver, such as precision control. They will be further discussed later. The returned
t is a time vector, x is a matrix whose columns are the solutions of each state variable.
In the second syntax, a structured variable sol is returned, whose component x is
the same as the t vector, while y is the transpose of the matrix x. Besides, other
information may be returned in the structured variable. For instance, in the function
call, if Events option is specified and events are measured, then the component xe
returns the time the events happen, ye is the state value at the events, and ie records
the subscript of the event in the time vector.
If the outputs at equal-spaced time instances are expected, the tspan can be
expressed as an equal-spaced vector t. The algorithms adopted in the function are
still variable-step ones, rather than fixed-step ones.
The procedures for solving ODEs are summarized below:
(1) Build the standard ODE: x  (t) = f (t, x(t)), with the given x(t0 ).
(2) Describe the ODE with MATLAB. It can either be an anonymous function
or an M-function. Note that, there is a t argument in the function. Even though t
is not explicitly contained in the equation, the t should still be used in the function
description.
10 (3) ODE solutions. The solvers such as ode45() can be called to find the solutions.
(4) Solution validation. It is a very important step in the solution process. The topic
will be discussed later.
With the standard solution methods and procedures, examples are given next to
demonstrate the solution processes and skills.

 Example 10.11
Consider the Lotka–Volterra model.
 
x (t) = 4x(t) − αx(t)y(t)
y (t) = βx(t)y(t) − 3y(t),

where, α = 2, β = 1, and the initial values are x(0) = 2 and y(0) = 3. Solve the ODE and
draw the solution curves.
Solutions The functions x(t) and y(t) are expected, while in the standard form, only vector
x(t) is involved. Therefore, state variables should be introduced. For instance, let x1 (t) =
x(t) and x2 (t) = y(t), the standard ODE can be found.
   
4x1 (t) − αx1 (t)x2 (t) 2
x  (t) = f (t, x(t)), where f (t, x(t)) = , x(0) = .
βx1 (t)x2 (t) − 3x2 (t) 3

With the standard form, anonymous function can used to describe directly the ODE, and
can then be solved. The relationship between x(t) and y(t), also known as the phase plane
10.2 · Initial Value ODE Problems
293 10
trajectory, can be obtained, as shown in . Fig. 10.4. Besides, the time elapse measured is
about 0.0105 s, with 153 points computed.
>> x0=[2; 3]; tn=10; a=2; b=1;
f=@(t,x)[4*x(1)-a*x(1)*x(2); b*x(1)*x(2)-3*x(2)];
tic, [t,x]=ode45(f,[0,tn],x0); toc % solution and measure time elapse
length(t), plot(x(:,1),x(:,2)) % draw phase plane trajectory


10.2.3 Validation of ODE Solutions


Adaptive variable-step algorithms are implemented in MATLAB ODE solvers. For
instance, fourth/fifth-order algorithm is implemented in ode45() function, where
fifth-order algorithm is used to solve the equation, while fourth-order algorithm is
used to validate the solutions, such that the step size are adjusted. If the difference in
the two solutions is larger than the pre-selected error tolerance, the step size is reduced
automatically, until the solutions satisfying the error tolerance are found. If the error
is too small, the step size can be increased to speed up the solution process.
Similar to the fsolve() function discussed earlier, command options=odeset
loads the control parameters, where options is a structured variable, whose members
are shown in . Table 10.2. Among the many control options, RelTol is the most
effective one in controlling the accuracy, whose smallest allowed value is 2.2205 ×
10−14 . In real applications, the analytical solutions are usually unknown. How can
we validate the numerical solutions? The following suggestions are made for the
validation process.
(1) Modify the control parameters, for instance, adjust the error tolerances. If a
solution is found, the error tolerance can be set to a smaller value. If the two results
are not the same, that is, there are noticeable differences between the two solutions,
the error tolerance should be reduced again. In real computing, it is advised to set

3.5

2.5

1.5

1
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5

. Fig. 10.4 The phase plane trajectory (the result is suspicious)


294 Chapter 10 · Ordinary Differential Equation Solutions

. Table 10.2 Commonly used control parameters in ODE solvers

Parameters Descriptions

RelTol Relative error tolerance, with default value of 0.001. To ensure high precision, it
must be reduced. It is recommended to reduce it to 2.2205 × 10−14 , or 3 × 10−14
in the book

AbsTol Absolute error tolerance of the states, with default one of 10−6 . It can be set to a
scalar of eps

MaxStep Maximum allowed step size

Mass Mass matrix used in describing differential–algebraic equations

Jacobian Function handle to describe Jacobian matrix function ∂ f /∂ x. If the Jacobian


matrix is known, the simulation process may be sped up

Events Event response, can be set to the event function handle

OutputFcn In each step the simulation is completed, a user-defined function can be called
automatically to show the intermediate result. It is recommended to set to
@odeplot

the option to the smallest allowed one 100×eps, such that the most accurate solution
10 under double precision framework is found.
(2) Select different algorithms to cross-validate the solutions.

 Example 10.12
The curves found in Example 10.11 are rather rough. Validate the solutions.
Solutions Set the relative error tolerance to 10−10 , the solution is found in 0.0757 s, with
669 points computed. The curves obtained are smooth (curves omitted). Even smaller
relative error tolerance is set, for instance, 3 × 10−14 , the number of points is still 669. It is
seen that even though the error tolerance is very small, it is not necessary to worry about
computational load.

>> x0=[2; 3]; tn=10; ff=odeset; ff.RelTol=1e-10; % set control parameters


a=2; b=1; f=@(t,x)[4*x(1)-a*x(1)*x(2); b*x(1)*x(2)-3*x(2)];
tic, [t,x]=ode45(f,[0,tn],x0,ff); toc % find solution and time elapse
length(t), plot(x(:,1),x(:,2)) % draw the phase plane trajectory


10.2.4 ODE Conversions


In 7 Sect. 10.2, the numerical solution methods for the initial value problems were
discussed. To solve the problems, the ODEs
 must
 be expressed as first-order explicit
ODEs, in the standard form x  (t) = f t, x(t) , with known initial state vector x(t0 ).
10.2 · Initial Value ODE Problems
295 10
This kind of ODE is not sufficient for the study of differential equations. Numeri-
cal solutions of ODEs in other forms, or ODE sets should also be explored. In fact, the
simple idea to solve various ODEs is to convert them, in someway, into the standard
form. Then the solvers such as ode45() can be called to solve directly the problems.
In this section, the conversion from different types of ODEs to the standard form is
considered.

1. A Single High-Order ODE


Assume that a high-order ODE is written as
 
y(n) (t) = f t, y(t), y (t), . . . , y(n−1) (t) , (10.2)

and the initial values of the output y(t) and its derivatives are known as y(t0 ), y (t0 ),
· · · , y(n−1) (t0 ). Select a set of state variables, such as x1 (t) = y(t), x2 (t) = y (t),
· · · , xn (t) = y(n−1) (t), the high-order ODE is converted into the following first-order
explicit ODE in the form:
⎧ 

⎪ x1 (t) = x2 (t)

⎨ x (t) = x3 (t)
2
.. (10.3)

⎪ . 

⎩  
xn (t) = f t, x1 (t), x2 (t), . . . , xn (t) ,

with the initial values x1 (t0 ) = y(t0 ), x2 (t0 ) = y (t0 ), · · · , xn (t0 ) = y(n−1) (t0 ). There-
fore, the new ODEs can be solved directly with ode45() function, to find their numer-
ical solutions.

 Example 10.13
Consider again the time-varying ODE in Example 10.7. For simplicity, the original ODE
is rewritten in the following form, where the independent variable is replaced by t.

t5 y (t) = 2(ty (t) − 2y(t)), y(1) = 1, y (1) = 0.5, y (1) = −1,

with the known analytical solution


√ √2 √ √ √
3 2e − 3 2e− 2 2 √2/t
y(t) = t2 − 2
t e 2/t + t e .
8 8

Solutions Since t  = 0 in the expected t ∈ [0.2, π] interval, divide both sides of the equation
by t5 , the explicit form of the equation is found.

y (t) = 2(ty (t) − 2y(t))/t5 , y(1) = 1, y (1) = 0.5, y (1) = −1.

Since the highest order is 3, the state variables x1 (t) = y(t), x2 (t) = y (t) and x3 (t) = y (t)
are selected. Therefore, the third-order ODE is converted into the following standard form:
296 Chapter 10 · Ordinary Differential Equation Solutions

⎡  ⎤ ⎡ ⎤ ⎡ ⎤ ⎡ ⎤
x1 (t) x2 (t) x1 (1) 1
⎣ x (t) ⎦ = ⎣ x3 (t) ⎦ , ⎣ x2 (1) ⎦ = ⎣ 0.5 ⎦ .
2

x3 (t) 2(tx2 (t) − 2x1 (t))/t 5 x3 (1) −1

The solution interval is [0.2, π], and the given one t = 1 is an inner point in the interval.
Therefore, the solution interval can be divided into two subintervals, [1, 0.2] and [1, π].
Note that, the first one is in reversed order, since the values at t = 1 point are known, the
information at t = 1 is used, to compute backward to t = 0.2. Therefore, the obtained
solutions should also be processed in the reverse order. It means that when the solutions
in the first subinterval are obtained, it should be arranged backward, to join the solutions
in the second subinterval, to form the solutions of the original ODE. Since the analytical
solutions are known, it can be compared with the numerical one, and the maximum error
is found. To ensure the highest precision under double precision framework, the relative
error tolerance is set to 3 × 10−14 .

>> f=@(t,x)[x(2); x(3); 2*(t*x(2)-2*x(1))/t^5]; s2=sqrt(2);


x0=[1;0.5;-1]; ff=odeset; ff.RelTol=3e-14; ff.AbsTol=eps;
tic, [t1 x1]=ode45(f,[1,0.2],x0,ff); % solution in [1, 0.2]
[t2 x2]=ode45(f,[1,pi],x0,ff); toc % solution in [1, π]
t=[t1(end:-1:2); t2]; y=[x1(end:-1:2,1); x2(:,1)]; % unified solution
y0=t.^2-3*s2*exp(s2)/8*t.^2.*exp(-s2./t)+...
3*s2*exp(-s2)/8*t.^2.*exp(s2./t); % exact solutions on interested points
err=max(abs((y-y0))), length(t) % max. error and number of points
If the solver ode45() in the statements is substituted by other solvers, the maximum error
10 and time elapse can be measured, as shown in . Table 10.3. It is seen that, in low-order
algorithms, the step size must be selected extremely small to satisfy the tough error tolerance.
Therefore, the computational load is very high. For this particular problem, the third-party
solver ode87() is the most effective one, then comes the ode45() solver. The ode45() solver
is recommended in the book. For certain time-consuming problems, the solver ode87()
can be tried. 

2. High-Order ODE Sets


The ODE set with two ODEs is demonstrated here to show how to convert it into the
standard ODE. If the two ODEs are both expressed in explicit form

x(m) (t) = f (t, x(t), x (t), · · · , x(m−1) (t), y(t), y (t), . . . , y(n−1) (t))
(10.4)
y(n) (t) = g(t, x(t), x (t), · · · , x(m−1) (t), y(t), y (t), . . . , y(n−1) (t)),

. Table 10.3 Comparisons on speed and accuracy

Algorithm ode87() ode45() ode15s() ode23() ode113() ode23t() ode23tb()

Time elapse 0.05364 0.13189 0.53278 3.13421 0.18895 6.60289 16.52489

Maximum error 5 × 10−15 5 × 10−14 8 × 10−11 2 × 10−13 1 × 10−12 7 × 10−9 4 × 10−9

Number of points 37 7397 2230 182260 398 322964 293512


10.2 · Initial Value ODE Problems
297 10
where each equation is in the explicit form of the highest order derivative of an
unknown function. Select the states x1 (t) = x(t), x2 (t) = x (t), · · · , xm (t) = x(m−1) (t),
also let xm+1 = y(t), xm+2 = y (t), · · · and xm+n (t) = y(n−1) (t), the original ODE set
can be converted into the following form:


⎪ x1 (t) = x2 (t)

⎪ ..



⎪ .

⎨  (t) = f (t, x (t), x (t), . . . , x
xm 1 2 m+n (t))

(10.5)

⎪ xm+1 (t) = xm+2 (t)



⎪ ..

⎪ .

⎩ 
xm+n (t) = g(t, x1 (t), x2 (t), . . . , xm+n (t)).

Convert also the initial values, the expected first-order explicit ODE can be
obtained. An example is given next to demonstrate the conversion and solution of
ODE sets.

 Example 10.14
The trajectory (x, y) of the Apollo satellite satisfies the following ODEs:
 
x (t) = 2y (t) + x(t) − μ∗ (x(t) + μ)/r13 (t) − μ(x(t) − μ∗ )/r23 (t)
y (t) = −2x (t) + y(t) − μ∗ y(t)/r13 (t) − μy/r23 (t),

where μ = 1/82.45, μ∗ = 1 − μ, and


 
r1 (t) = (x(t) + μ)2 + y2 (t), r2 (t) = (x(t) − μ∗ )2 + y2 (t),

and the initial values are known, x(0) = 1.2, x (0) = 0, y(0) = 0, y (0) = −1.04935751.
Solve the ODEs and draw the (x, y) trajectory of the Apollo satellite.
Solutions Select a set of state variables x1 (t) = x(t), x2 (t) = x (t), x3 (t) = y(t) and
x4 (t)x = y (t), the first-order explicit ODE can be found
⎡ ⎤
x2 (t)
⎢ 2x4 (t) + x1 (t) − μ∗ (x1 (t) + μ)/r (t) − μ(x1 (t) − μ∗ )/r (t) ⎥
3 3
x  (t) = ⎢

1 2 ⎥,

x4 (t)
−2x2 (t) + x3 (t) − μ∗ x3 (t)/r13 (t) − μx3 (t)/r23 (t)
 
where, r1 (t) = (x1 (t) + μ)2 + x32 (t), r2 (t) = (x1 (t) − μ∗ )2 + x32 (t), μ = 1/82.45 and

μ∗ = 1 − μ. The initial state vector can be written as x 0 = [1.2, 0, 0, −1.04935751]T .


Since in the model, the intermediate variables r1 (t) and r2 (t) should be computed first, then
compute x  (t); therefore, it is not very simple to use anonymous function to describe the
ODEs, the M-function should be used instead.

function dx=apolloeq(t,x)
mu=1/82.45; mu1=1-mu;
r1=sqrt((x(1)+mu)^2+x(3)^2); r2=sqrt((x(1)-mu1)^2+x(3)^2);
298 Chapter 10 · Ordinary Differential Equation Solutions

dx=[x(2); 2*x(4)+x(1)-mu1*(x(1)+mu)/r1^3-mu*(x(1)-mu1)/r2^3;
x(4); -2*x(2)+x(3)-mu1*x(3)/r1^3-mu*x(3)/r2^3]; % describe the ODEs
end
Of course, if M-function is not expected, the following anonymous functions can also be
used, but the structure is a bit more complicated.

>> mu=1/82.45; mu1=1-mu; r1=@(x)sqrt((x(1)+mu)^2+x(3)^2);


r2=@(x)sqrt((x(1)-mu1)^2+x(3)^2); % set intermediate parameters
f=@(t,x)[x(2); % describe the ODEs
2*x(4)+x(1)-mu1*(x(1)+mu)/r1(x)^3-mu*(x(1)-mu1)/r2(x)^3;
x(4); -2*x(2)+x(3)-mu1*x(3)/r1(x)^3-mu*x(3)/r2(x)^3];
If function ode45() is called, the numerical solution can be found. The trajectory is shown
in . Fig. 10.5. 689 points are found in total, and the time elapse is 0.14 s.

>> x0=[1.2;0;0;-1.04935751];
tic, [t,y]=ode45(@apolloeq,[0,20],x0); toc % find the solution
length(t), plot(y(:,1),y(:,3)) % draw phase plane trajectory
Unfortunately, the directly obtained Apollo trajectory is incorrect, since the default relative
error tolerance RelTol selected in the ode45() solver is too large, such that misleading
results are finally obtained. Such a tolerance must be reduced, for instance to 10−6 , such that
consistent results can be obtained. To ensure the highest precision under double precision
framework, the following commands are executed, and the correct trajectory in . Fig. 10.7
is found. The total of 64753 points are found, and time elapse is 0.23 s.
10
>> ff=odeset; ff.AbsTol=eps; ff.RelTol=3e-14;
tic, [t1,y1]=ode45(@apolloeq,[0,20],x0,ff); toc % solve the ODE again
length(t1), plot(y1(:,1),y1(:,3)) % vector length, draw phase plane trajectory
The following commands also yield the smallest step size of h = 1.5879 × 10−6 , the step
sizes at different t are drawn in . Fig. 10.7. The function diff() is different from the one
in 7 Chap. 7. The latter diff() function operates on a symbolic expression. therefore,
the derivative expression is obtained, while here, it acts on the time vector, therefore the

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8
-1.5 -1 -0.5 0 0.5 1 1.5

. Fig. 10.5 Apollo satellite trajectories (erroneous one)


10.2 · Initial Value ODE Problems
299 10

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8
-1.5 -1 -0.5 0 0.5 1 1.5

. Fig. 10.6 The correct Apollo satellite trajectory

-3
10
1.4

1.2

0.8

0.6

0.4

0.2

0
0 2 4 6 8 10 12 14 16 18 20

. Fig. 10.7 Step sizes in the simulation process

difference of t vector is found, which is the step size vector. Also, the length of the vector
is one less than the vector t.

>> h=min(diff(t1)) % find the smallest step size


plot(t1(1:end-1),diff(t1)) % draw the actual step size
It can be seen that there are advantages in the variable-step algorithms, that is, small step
size can be adopted, if necessary. When the changes in the solution are very slow, large step
size can be adopted automatically so as to ensure high efficiencies in solving ODEs.
It is seen from the curve that, at most times, a large step size over 0.001 is used. To ensure
the accuracy, around some particular points, small step sizes about 2 × 10−6 are used. In
other words, if fixed-step algorithms are used, a small step size of 10−6 should be used
throughout the simulation process, otherwise the relative error of 10−14 cannot be guar-
anteed. The number of points may reach 1.26×107 , which is about 195 times more than the
variable-step
algorithms. 
300 Chapter 10 · Ordinary Differential Equation Solutions

3. More Complicated ODE Sets


In the previously discussed ODE sets, each ODE contains only the highest-order
derivative of one unknown variable only; therefore, it can be converted into first-order
explicit ODEs easily. Another category of ODE sets is discussed in this section, where
both of the highest order derivative terms appear in the two equations simultaneously.
The first-order explicit ODEs can be obtained by solving algebraic equations. An
example is given next to demonstrate the conversion process.

 Example 10.15
Assume that the ODE set with two unknowns is given blow. Convert it to the first-order
explicit ODEs.  
x (t) + 2y (t)x(t) = 2y (t)
x (t)y (t) + 3x (t)y (t) + x(t)y (t) − y(t) = 5.

Solutions The x (t) and y (t) terms appear in both of the equations simultaneously. Select
a set of state variables x1 (t) = x(t), x2 (t) = x (t), x3 (t) = y(t) and x4 (t) = y (t), the linear
algebraic equations of x (t) and y (t), that is x2 (t) and x4 (t), can be established. Denote
p1 (t) = x (t) = x2 (t) and p2 (t) = y (t) = x4 (t), the following commands can be used to
solve the algebraic equations:

>> syms x1 x2 x3 x4 p1 p2 % declare symbolic variables and solve equations


[p1,p2]=solve(p1+2*x4*x1==2*p2,p1*x4+3*x2*p2+x1*x4-x3==5,[p1,p2])
It is found that
10
2x3 (t) + 10 − 2x1 (t)x4 (t) − 6x1 (t)x2 (t)x4 (t)
p1 (t) = ,
2x4 (t) + 3x2 (t)
2
x3 (t) + 5 − x1 (t)x4 (t) + 2x1 (t)x4 (t)
p2 (t) = ,
2x4 (t) + 3x2 (t)

from which, the first-order explicit ODEs can be converted.


⎡ ⎤
x2 (t)
⎢ 2x3 (t) + 10 − 2x1 (t)x4 (t) − 6x1 (t)x2 (t)x4 (t) ⎥
⎢ ⎥

⎢ 2x4 (t) + 3x2 (t) ⎥

x (t) = ⎢ ⎥.
x4 (t) ⎥
⎢ ⎥
⎣ 2
x3 (t) + 5 − x1 (t)x4 (t) + 2x1 (t)x4 (t) ⎦
2x4 (t) + 3x2 (t)

10.2.5 Stiff ODEs


Stiff ODEs are not suitable to be solved by conventional first-order explicit ODE
solvers. The phenomenon is that, in the analytical solutions, if any, the curves are
smooth, while, with numerical methods, burrs can be erroneously introduced under
different step sizes in fixed-step algorithms. In variable-step algorithms, at some point,
extremely small step sizes must be adopted to accurately solve the ODEs, such that
the computational load increases drastically. The solution process is then made very
10.2 · Initial Value ODE Problems
301 10
difficult or even impossible. Dedicated algorithms must be employed to solve stiff
ODEs.

 Example 10.16
The mathematical form of van der Pol equation is y (t) + μ(y2 (t) − 1)y (t) + y(t) = 0,
with initial values y(0) = −0.2, y (0) = −0.7 and μ = 1000. Find the numerical solution
of van der Pol equation in t ∈ (0, 3000).
Solutions For the second-order ODE, select the state variables x1 (t) = y(t) and x2 (t) =
y (t), the standard form can be obtained as
   
x2 (t) −0.2
x  (t) =  2  , x(0) = .
−μ x1 (t) − 1 x2 (t) − x1 (t) −0.7

The following commands can be used to solve the differential equations. If ode15s()
function is replaced by other solvers, the measured data are obtained in . Table 10.4,
where after long time computing, ode87() failed to yield numerical solutions; the solver
ode23t() abnormally stopped at t = 806. The solution curves of the other solvers are the
same. Since the analytical solution is unknown for this example, the precision cannot be
assessed precisely. The total time elapse, number of points and the minimum step sizes can
be measured. It is seen that ode15s() is obviously better than other solvers.
>> ff=odeset; ff.RelTol=3e-14; ff.AbsTol=eps; % set control parameters
x0=[2;0]; tn=3000; mu=1000; % known parameters
f=@(t,x)[x(2); -mu*(x(1)^2-1)*x(2)-x(1)]; % describe the ODE
tic, [t,y]=ode15s(f,[0,tn],x0,ff); toc % solve ODE and measure time
length(t), h=diff(t); min(h), plot(t(1:end-1),h)
The step sizes under ode45() and ode15s() solvers are obtained in . Fig. 10.8. It can
be seen that at certain points, the small step size of around 10−10 must be selected. Apart
from these points, the step sizes selected by ode15s() is much larger than the ones in the
ode45() solver. Therefore, the efficiency of ode15s() is much higher. 

It can be seen from this table and . Table 10.3 that, for non-stiff ODEs, the
solvers ode45() or even ode87() is recommended, while for stiff ones (if ode45()
failed to yield solutions after a long time), the solver ode15s() is recommended.

. Table 10.4 The efficiency comparisons under different solvers

Solvers ode87() ode45() ode15s() ode23() ode113() ode23t() ode23tb()

Time elapse None 19.044 0.634 27.873 69.092 3.84 (failed) 61.446

Minimum step sizes − 6 × 10−9 3×10−10 2 × 10−8 2×10−10 3 × 10−12 2 × 10−8

Number of points − 10821721 30767 4873878 3529603 217128 1786955


302 Chapter 10 · Ordinary Differential Equation Solutions

3 ode15s()

0
0 500 1000 1500 2000 2500 3000
-4
10
3

ode45()
2

0
0 500 1000 1500 2000 2500 3000

. Fig. 10.8 Step size comparisons

10.3 Special ODEs


Conventional ODEs can be solved numerically with the methods discussed earlier.
For ODEs under certain forms, the solvers discussed earlier cannot be used directly. In
this section, the solutions of differential–algebraic equations (DAEs), implicit ODEs
and delay differential equations (DDEs) are presented.

10
10.3.1 Differential–Algebraic Equations
A class of relatively simple semi-explicit differential–algebraic equation is
   
M t, x(t) x  (t) = f t, x(t) , (10.6)
 
where M t, x(t) is also known as a mass matrix, and it is singular.
A numerical solver for index 1 DAEs is provided in MATLAB. In the ordinary
solvers presented earlier, set the control parameter Mass to the mass matrix, which
can be a constant matrix or a function handle. With these information, the solvers
such as ode45() can be used to solve directly the DAEs. An example is given next to
demonstrate the direct solutions of DAEs.

 Example 10.17
Consider the following DAE:
⎧ 
⎨ x1 (t) = −0.2x1 (t) + x2 (t)x3 (t) + 0.3x1 (t)x2 (t)
x (t) = 2x1 (t)x2 (t) − 5x2 (t)x3 (t) − 2x22 (t)
⎩ 2
0= x1 (t) + x2 (t) + x3 (t) − 1,

with given initial values x1 (0) = 0.8 and x2 (0) = x3 (0) = 0.1. Find the numerical solutions.
Solutions It is seen that the last one is the algebraic equation, which is regarded as the
algebraic constraints among the three state variables. The matrix form of the DAE is
10.3 · Special ODEs
303 10
expressed as
⎡ ⎤⎡  ⎤ ⎡ ⎤
1 0 0 x1 (t) −0.2x1 (t) + x2 (t)x3 (t) + 0.3x1 (t)x2 (t)
⎣0 1 0 ⎦ ⎣ x2 (t) ⎦ = ⎣ 2x1 (t)x2 (t) − 5x2 (t)x3 (t) − 2x22 (t) ⎦ .
0 0 0 x3 (t) x1 (t) + x2 (t) + x3 (t) − 1

The following anonymous function can be written for the right side:
>> f=@(t,x)[-0.2*x(1)+x(2)*x(3)+0.3*x(1)*x(2);
2*x(1)*x(2)-5*x(2)*x(3)-2*x(2)*x(2);
x(1)+x(2)+x(3)-1]; % description of the ODE
If matrix M is input to MATLAB workspace, the following commands are executed, such
that the numerical solution of the DAE is found, as shown in . Fig. 10.9. The time elapse
is 0.283 s, and the number of points is 4087.
>> M=[1,0,0; 0,1,0; 0,0,0]; % input the mass matrix
ff=odeset; ff.AbsTol=eps; ff.RelTol=3e-14;
ff.Mass=M; x0=[0.8; 0.1; 0.1]; % set mass matrix and initial values
tic, [t,x]=ode15s(f,[0,20],x0,ff); toc
plot(t,x), length(t) % solve DAE and draw plots


10.3.2 Implicit Differential Equations


The mathematical form of implicit ODEs is given by
 
F t, x(t), x  (t) = 0, (10.7)

with known initial values x(t0 ) = x 0 and x  (t0 ) = x 0 .

2( ) 3( )
0.8

0.6

0.4
1( )
0.2

-0.2

-0.4
0 2 4 6 8 10 12 14 16 18 20

. Fig. 10.9 Numerical solution of differential–algebraic equations


304 Chapter 10 · Ordinary Differential Equation Solutions

It is seen that the first-order explicit form is no longer needed. The implicit form
is used directly, such that the expression is much more flexible. On the other hand,
the x 0 term is still needed, besides, the initial values of the first-order derivative x 0
are also needed. Therefore, the conditions are more demanding than the first-order
explicit ODEs. Substituting the given t0 and x(t0 ) into (10.7), algebraic equations can
be solved to find the consistent x  (t0 ). Function decic() can also be used to find x 0 ,
with the syntax
[x 0 ,x 0']=decic(f ,t0 ,x 0 ∗ ,x F ∗ F
0 ,x 0' ,x 0' ,options)
where f is the function handle of the implicit ODE, x 0 ∗ is the initial values in the
searching process, vectors x F F
0 and x 0 are flags, indicating which element needs to be
retained. Normally, the former one is a one vector, and the latter the vector of zeros,
meaning to find the consistent x 0 from the given x 0 .
The solver ode15i() solves implicit ODEs in the syntax
[t,x]=ode15i(f ,tspan,x ∗0 ,x 0'∗ ,options)
where tspan is the same as the one defined earlier. It is seen that [t0 , tn ] is for the
interval, or a time vector t; options are the control parameters. An example is given
next to illustrate the description and solutions of implicit ODEs.

 Example 10.18
Solve the following implicit ODEs:
10  
x (t) sin y (t) + (y (t))2 = −2x(t)y(t)e−x (t) + x(t)x (t)y (t)
x(t)x (t)y (t) + cos y (t) = 3y(t)x (t)e−x(t) ,

with the initial values x(0) = y (0) = 1 and x (0) = y(0) = 0.


Solutions Select the state variables x1 (t) = x(t), x2 (t) = x (t), x3 (t) = y(t) and x4 (t) =
y (t), the original ODE are converted into the standard form of the implicit ODEs.
⎡ ⎤
x1 (t) − x2 (t)
⎢ x (t) sin x4 (t) + (x (t))2 + 2x1 (t)x3 (t)e−x2 (t) − x1 (t)x (t)x4 (t) ⎥
⎢ 2 4 2 ⎥ = 0.
⎣ x3 (t) − x4 (t) ⎦
  
x1 (t)x2 (t)x4 (t) + cos x4 (t) − 3x3 (t)x2 (t)e −x1 (t) .

With the following MATLAB commands, the implicit ODE is expressed first in an anony-
mous function, then the consistent initial values are found, and the numerical solutions
of the ODE are obtained. The total time elapse is 0.94 s, with 6334 points. The solutions
are shown in . Fig. 10.10. Function ode45() was used in Reference [1] to solve the same
problem, where the algebraic equation solver was embedded in describing the ODEs. Since
in each step, the algebraic equation is solved once, thus it is quite time-consuming. The
same results are obtained, and the time elapse is 12.65 s, with 2217 points computed.
>> f=@(t,x,xd)[xd(1)-x(2);
xd(2)*sin(x(4))+xd(4)^2+2*exp(-x(2))*x(1)*x(3)-x(1)*xd(2)*x(4);
xd(3)-x(4);
x(1)*xd(2)*xd(4)+cos(xd(4))-3*exp(-x(1))*x(3)*x(2)];
ff=odeset; ff.AbsTol=1e-8; ff.RelTol=1e-8;
10.3 · Special ODEs
305 10

3.5

1( )
3

2.5

2 2( )

1.5

3( )
1
4( )
0.5

0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

. Fig. 10.10 Numerical solutions of the implicit ODEs

x0=[1,0,0,1]'; x0F=ones(4,1); xd0=rand(4,1); x0F1=zeros(4,1);


[x0,xd0,f0]=decic(f,0,x0,x0F,xd0,x0F1,ff); % get consistent initial values
tic, [t,x]=ode15i(f,[0,2],x0,xd0,ff); toc % solve implicit ODEs
plot(t,x), length(t) % the solutions


10.3.3 Delay Differential Equations


If in an ODE, the information of the unknown variable x(t) at the current time t
and the values at earlier time instances are involved, the ODE is referred to as delay
differential equations (DDEs).
The simple form of DDE with constant delay terms is
 
x  (t) = f t, x(t), x(t − τ1 ), x(t − τ2 ), · · · , x(t − τm ) , (10.8)

where τi  0 are constant delays of the state variables x(t). Furthermore, the delays
can be functions of t and x(t).

1. DDEs with Constant Delays


If the delays τi are constants, the solver dde23() based on implicit Runge–Kutta
algorithm solves directly the DDEs, with the syntax
sol=dde23(f1 , τ ,f2 ,[t0 , tn ],options)
As the solvers introduced earlier, options is a structured variable, containing the
control parameters to the solver. The initial control parameters can be obtained with
ddeset() function, which is similar to odeset(), while there are differences. For
instance, AbsTol, RelTol, OutputFcn and Events are quite similar, or even they can
be used in the same way. Note that the relative error tolerance should not be selected
too small; otherwise, solutions may not be found. In the example next, the impact of
relative error tolerance on the solution speed is studied.
306 Chapter 10 · Ordinary Differential Equation Solutions

In the solution process, f1 is the function handle to describe the DDEs in MAT-
LAB, which will be demonstrated further in an example; f2 is used to describe the
functions when t  t0 , also known as history functions. A MATLAB function han-
dle can be used, or described as constants. Apart from the classical scalar t and state
x, matrix Z should also be provided, where the kth column Z (:,k) stores the state
vectors at τk time, that is x(t − τk ).
The returned argument sol is a structured variable, whose member sol.x is the
time vector t, and member sol.y is the transpose of the matrix x.
An example is used next to demonstrate the solutions of the simple DDEs. Sug-
gestions are made on the control parameter selections.

 Example 10.19
For the following DDE with constant delay terms

x (t) = 1 − 3x(t) − y(t − 1) − 0.2x3 (t − 0.5) − x(t − 0.5)
y (t) + 3y (t) + 2y(t) = 4x(t),

where when t  0, x(t) = y(t) = y (t) = 0, find the numerical solutions.


Solutions In the equation, the signal values of x(t) and y(t) at different instances t, t − 1
and t − 0.5 are involved. Dedicated solvers are needed in solving the DDEs. To find the
numerical solutions, it should be converted to first-order explicit DDE form.
The simplest way for the conversion is to select a set of state variables x1 (t) = x(t),
x2 (t) = y(t) and x3 (t) = y (t). The first-order explicit DDE can be obtained
10
⎧ 
⎨ x1 (t) = 1 − 3x1 (t) − x2 (t − 1) − 0.2x13 (t − 0.5) − x1 (t − 0.5)
x (t) = x3 (t)
⎩ 2
x3 (t) = 4x1 (t) − 2x2 (t) − 3x3 (t).

Define two time delay constants τ1 = 1 and τ2 = 0.5, it is seen from the equation that the
state variables at the first delay τ1 are stored in the first column of Z matrix. Therefore,
x2 (t − τ1 ) is the first column, second row element of matrix Z, that is Z(2, 1). If the state
variable x1 (t − τ2 ) is expected, the element Z(1, 2) is needed. It is not difficult to write out
the standard form of the DDE.
⎧ 
⎨ x1 (t) = 1 − 3x1 (t) − Z(2, 1) − 0.2Z 3 (1, 2) − Z(1, 2)
x (t) = x3 (t)
⎩ 2
x3 (t) = 4x1 (t) − 2x2 (t) − 3x3 (t).

The following anonymous function can be written to express the DDE:


>> f=@(t,x,Z)[1-3*x(1)-Z(2,1)-0.2*Z(1,2)^3-Z(1,2);
x(3);
4*x(1)-2*x(2)-3*x(3)];
Select different relative error tolerance ee, the following MATLAB commands can be used
to solve the DDE, as shown in . Fig. 10.11.
>> ff=ddeset; ee=1e-7; ff.RelTol=ee; ff.AbsTol=eps;
tau=[1 0.5]; x0=zeros(3,1); % set the vector with two delay constants
10.3 · Special ODEs
307 10

0.4

0.35 ( )

0.3

0.25

0.2
1( )
0.15

0.1

0.05
2( )
0

-0.05
0 1 2 3 4 5 6 7 8 9 10

. Fig. 10.11 Numerical solutions of the DDE

tic, tx=dde23(f,tau,x0,[0,10],ff); toc % solve the DDE


plot(tx.x,tx.y), length(tx.x) % draw the state variables in the DDE
Note that the information in the variable tx. y are stored in rows. If only the y(t) signal in
the original DDE is expected, it can be retrieved with tx.y(2,:) command, rather than
with tx.y(:,2).
Since the error tolerance selected here is rather tough, the solution process is very time-
consuming. It takes about 89.82 s to find the solution, with 60042 points computed. Differ-
ent error tolerance ee are tried, and the results are obtained in . Table 10.5. The precision
requirement is increased by ten times, the number of points is doubled. If the value of ee
is selected too small, no numerical solution can be found. 

2. DDEs with Variable Delays


Function ddesd() solves DDEs with variable delays, where function handles can
be used to describe the delays. The solver can be used to solve DDEs with variable
delays. The syntax of the ddesd() function is
sol=ddesd(f ,fτ ,f2 ,[t0 ,tn ],options)
where f is the function handle to describe the explicit DDEs; fτ is the function handle
to describe delay functions; f2 is the handle to describe history functions. These
function handles can be anonymous functions or M-functions.

. Table 10.5 Error tolerance and time elapse

Error tolerance ee 10−13 10−12 10−11 10−10 10−9 10−8 10−7 10−6 Default

Time elapse − 89.823 16.376 4.276 1.220 0.368 0.113 0.058 0.016

Number of points − 60042 29986 14900 7382 3647 1779 891 70


308 Chapter 10 · Ordinary Differential Equation Solutions

 Example 10.20
Solve the generalized DDE, where α = 0.77.
⎧ 
⎨ x1 (t) = −2x2 (t) − 3x1 (t − 0.2| sin t|)
x (t) = −0.05x1 (t)x3 (t) − 2x2 (αt) + 2
⎩ 2
x3 (t) = 0.3x1 (t)x2 (t)x3 (t) + cos(x1 (t)x2 (t)) + 2 sin 0.1t2 .

Solutions In the DDE, the first delay is t − 0.2| sin t|, while the second one is with the
x2 (0.77t) term. The delay function handles are described by an anonymous function, such
that the DDE is solved directly.

>> tau=@(t,x)[t-0.2*abs(sin(t)); 0.77*t]; % describe the delays


f=@(t,x,Z)[-2*x(2)-3*Z(1,1);
-0.05*x(1)*x(3)-2*Z(2,2)+2; % describe the DDEs
0.3*x(1)*x(2)*x(3)+cos(x(1)*x(2))+2*sin(0.1*t^2)];
ff=ddeset; ff.RelTol=1e-10; ff.AbsTol=eps;
sol=ddesd(f,tau,zeros(3,1),[0,30],ff); plot(sol.x,sol.y)


3. Neutral-Type DDEs
The general form of neutral-type DDE is
 
10 x  (t) = f t, x(t), x(t − τp1 ), · · · , x(t − τpm ), x  (t − τq1 ), . . . , x  (t − τqk ) , (10.9)

the equation contains not only the delay signals of the states but also delay signals
of the derivatives of the states. The two delay vectors τ 1 = [τp1 , τp2 , . . . , τpm ] and
τ 2 = [τq1 , τq2 , . . . , τqk ] are used to describe them, where τp and τq can be constant
vectors for constant delays, or even functions τp (t, x(t)) and τq (t, x(t)).
Function ddensd() solves neutral-type DDEs with the following syntax:
sol=ddensd(f ,τ 1 ,τ 2 ,f2 ,[t0 ,tn ],options)
If the delays in the DDEs are not constants, the methods in function ddesd() are
used to describe τ 1 and τ 2 as function handles, which are represented in anonymous
function or M-functions. The error tolerance cannot be selected to very small values.
It can be set to 10−5 or slightly larger values.

 Example 10.21
Solve the following neutral-type DDE:

x  (t) = A1 x(t − 0.15) + A2 x  (t − 0.5) + Bu(t),

where, the input signal u(t) ≡ 1, and the matrices are


⎡ ⎤ ⎡ ⎤ ⎡ ⎤
−13 3 −3 0.02 0 0 0
A1 = ⎣ 106 −116 62 ⎦ , A2 = ⎣ 0 0.03 0 ⎦, B = ⎣1⎦.
207 −207 113 0 0 0.04 2
10.4 · Boundary Value Problems
309 10
Solutions Since in the equations, x  (t) and x  (t−0.5) terms appear simultaneously, function
dde23() cannot be used to solve the problem. Function ddensd() should be used instead
for the solution. The delay constant for the state is τ 1 = 0.15, and the one for the derivative
of the state is τ 2 = 0.5. Therefore, an anonymous function describes the neutral-type DDE
and finds the numerical solutions. The state variables obtained are shown in . Fig. 10.12.

>> A1=[-13,3,-3; 106,-116,62; 207,-207,113];


A2=diag([0.02,0.03,0.04]); B=[0; 1; 2]; % input the matrices
u=1; x0=zeros(3,1); f=@(t,x,z1,z2)A1*z1+A2*z2+B*u; % describe the DDE
ff=ddeset; ff.RelTol=1e-5; ff.AbsTol=eps; % specify the error tolerance
sol=ddensd(f,0.15,0.5,x0,[0,15],ff); % solve neutral-type DDE
plot(sol.x,sol.y), length(sol.x) % draw the solutions of the DDE


10.4 Boundary Value Problems


The differential equation solution methods discussed so far are restricted to initial
value problems. That is when x(t0 ) is known, the solutions at other time instances
evolute step-by-step to find the numerical solutions. In applications, other kinds of
problems may be encountered. Some of the states at t = t0 instance are known, while
some states at the terminal time t = tn are known. This kind of problem is also known
as boundary value problems (BVPs). BVPs cannot be solved directly with the solvers
such as ode45(). In this section, numerical solutions of BVP problems are illustrated.

10.4.1 Mathematical Forms of Boundary Value Problems


For a second-order ODE, if the values of y(a) and y (a) are known, the problem
can be solved directly with the initial value problem solver. If y (a) is unknown but

3( )
4

2 2( )

0
1( )

-1
0 5 10 15

. Fig. 10.12 The numerical solutions of the DDE


310 Chapter 10 · Ordinary Differential Equation Solutions

y(b) is known, the problem is a BVP one. How to solve BVP problems? An effective
low-level method is the shooting method. Assume that y (a) (the initial angle of the
gun) is known, the initial value problem can be solved, and target spot ŷ(b) can be
found. It is obvious that the spot has differences with the known y(b) point. The error
is used to adjust the initial angle of the gun, and finally the target spot coincides with
the value of y(b). The solution then is the solution of the BVP.
More generally, the mathematical form of the BVPs with undetermined coeffi-
cients can be expressed as  
y (t) = f t, y(t), θ , (10.10)
where y(t) is the state vector, θ contains the undetermined coefficients. The boundary
conditions are  
φ y(a), y(b), θ = 0. (10.11)

10.4.2 Solutions of BVPs


The solver bvp5c() [4] provided in MATLAB can be used to solve BVPs directly. To
solve the BVPs, the following procedures are taken:
(1) Interpolation points. Function bvpinit() can be called to determine the inter-
mediate information through interpolation points. Of course, it is not restricted to
describe the boundary conditions, it can also be used to describe information on the
undetermined coefficients, with the syntax
10 sinit=bvpinit(v,x 0 ,θ 0 )
where v is the time vector, where command v=linspace(a, b, n) or colon expressions
can be used to generate the vectors. Note that to ensure the computational speed, the
length n should not be selected too large. Generally, n = 5 can be selected. Apart
from the v vector, the initial state values x 0 and interpolation points of undetermined
coefficients θ 0 can also be specified. In fact, if the relative error tolerance is selected
tough enough, the impact on the value of n can be neglected.
(2) MATLAB descriptions on ODEs and boundary conditions. The description of
ODEs is the same as it was in initial value problems. The boundary conditions in
(10.11) should also be described. The specific methods are demonstrated through
examples.
(3) BVP solutions. Call bvp5c() function to solve the BVP, with the syntax
sol=bvp5c(fun1,fun2,sinit, control parameters)
where fun1 and fun2 are the function handles to describe the ODE and bound-
ary conditions, respectively. They can be described with anonymous functions or
M-functions; the control parameters are the same as the ones in the ode45()
function; the returned sol is a structured variable, whose sol.x member is the t
row vector, while sol.y is a matrix whose rows correspond to each state variables;
sol.parameters returns the undetermined coefficients θ .
10.4 · Boundary Value Problems
311 10

 Example 10.22
Solve the following BVP [5] and assess the solution precision.
 3  
x u (x) = 1, 1 ≤ x ≤ 2,

with u(1) = u (1) = u(2) = u (2) = 0, and the analytical solution is
 
1 1 1
u(x) = (10 ln 2 − 3)(1 − x) + + (3 + x) ln x − x .
4 2 x

Solutions The original ODE cannot be solved directly. The first-order explicit ODE should
be converted first, then the solution can be found. For this particular example, some manip-
ulations on the left side should be made manually, or carry out necessary derivation with
Symbolic Math Toolbox.

>> syms c u(x), diff(x^3*diff(u,2),2) % symbolic formulation on the left side


It is found that
x3 u(4) (x) + 6x2 u (x) + 6xu (x) = 1.
Since the solution interval is x ∈ (1, 2), then x  = 0. Therefore, the explicit form can be
written as.
6 6 1
u(4) (x) = − u (x) − 2 u (x) + 3 .
x x x
Selecting the states y1 (x) = u(x), y2 (x) = u (x), y3 (x) = u (x) and y4 (x) = u (x), the
following first-order explicit ODE can be found
⎡ ⎤
y2 (x)
⎢ y3 (x) ⎥
y (x) = ⎢

⎥,

y4 (x)
−6y4 (x) /x − 6y3 (x) /x2 + 1/x3

while the boundary conditions can be written as y1 (a) = 0, y3 (a) = 0, y1 (b) = 0 and
y3 (b) = 0. For the standard boundary condition format, it is found that ya (1) = 0,
ya (3) = 0, yb (1) = 0 and yb (3) = 0.
The BVPs can be described directly with the following commands. The solution com-
mands are almost the same as the ones presented earlier. The differences exhibit only on the
descriptions of the ODE and the boundary conditions. The time elapse is about 13.037 s,
and the error is 2.7274 × 10−15 . The curves of u(x) and u (x) are shown in . Fig. 10.13,
where u(x) coincides with the theoretical one.

>> f=@(x,y)[y(2:4); -6*y(4)/x-6*y(3)/x^2+1/x^3]; % ODE description


g=@(ya,yb)[ya(1); ya(3); yb(1); yb(3)]; % boundary conditions
ff=odeset; ff.RelTol=3e-14; ff.AbsTol=eps; tic, N=10;
x0=rand(4,1); S1=bvpinit(linspace(1,2,N),x0); % intermediate points
s1=bvp5c(f,g,S1,ff); x=s1.x; y=s1.y; toc % solve the BVP
y0=(10*log(2)-3)*(1-x)/4+(1./x+(3+x).*log(x)-x)/2; % exact solution
plot(x,y([1,3],:),x,y0,'--'); norm(y(1,:)-y0) % compute the errors

312 Chapter 10 · Ordinary Differential Equation Solutions

0.01
( )
0

-0.01

-0.02

-0.03
( )
-0.04

-0.05
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2

. Fig. 10.13 Solution curves of the ODE

10.4.3 BVPs with Undetermined Coefficients


If the BVP has undetermined coefficients, they are represented in the θ vector. The
solver bvp5c() can still be used in finding the solutions directly. Meanwhile, the
undetermined coefficients are also found. In normal cases, each undetermined coeffi-
cient needs an extra boundary condition. If the number of given boundary conditions
is not sufficient, the undetermined coefficients and BVPs cannot be solved. In this
10 section, a BVP with undetermined coefficients is used as an example, to demonstrate
the solution process.

 Example 10.23
Consider the ODE below. Find the values α and β, and solve the BVP.
 
x (t) = 4x(t) − αx(t)y(t)
y (t) = −2y(t) + βx(t)y(t),

with given boundary conditions x(0) = 2, y(0) = 1, x(3) = 4 and y(3) = 2.


Solutions Introduce the state variables x1 (t) = x(t) and x2 (t) = y(t), let v1 = α and
v2 = β, the original problem can be converted to the ODE of state vector x.
 
4x1 (t) − v1 x1 (t)x2 (t)
x  (t) = .
−2x2 (t) + v2 x1 (t)x2 (t)

As in ordinary cases, denote a = 0 and b = 3, the standard form of the boundary conditions
can be expressed as x a (1)−2 = 0, x a (2)−1 = 0, x b (1)−4 = 0 and x b (2)−2 = 0. Therefore,
the following anonymous functions describe the ODE and its boundary conditions.
>> f=@(t,x,v)[4*x(1)+v(1)*x(1)*x(2);
-2*x(2)+v(2)*x(1)*x(2)]; % the ODE
g=@(xa,xb,v)[xa(1)-2; xa(2)-1; xb(1)-4; xb(2)-2]; % boundary conditions
The function bvpinit() can be called first to initialize the mesh grids in the solution,
and assign the initial values of α and β. Since there are two states, and two undetermined
10.5 · Exercises
313 10
coefficients, the initial values can be assigned to two random vectors rand(2,1). With
these parameters, function bvp5c() can be called to solve the BVP and the undetermined
coefficients α and β. The solution of the problem obtained is as shown in . Fig. 10.14.

>> x1=rand(2,1); v1=rand(2,1);


sinit=bvpinit(linspace(0,3,20),x1,v1); % intermediate points
ff=odeset; ff.RelTol=3e-14; ff.AbsTol=eps;
sol=bvp5c(f,g,sinit,ff); sol.parameters % undetermined coefficients
plot(sol.x,sol.y); % draw the solution curves
Meanwhile, it is found that α = −2.3721 and β = 0.8934. The boundary conditions are
satisfied on the curves, Therefore, the solutions obtained are correct. It should be noted
that, when selecting the initial vectors x 1 and v 1 , inappropriate selection of the vectors
may lead to singular Jacobian matrices. Thus if this happens, another sets of random initial
values should be selected again. 

10.5 Exercises
(1) Find the general solution for the following linear ODE:

y(5) + 13y(4) + 64y (t) + 152y (t) + 176y (t) + 80y(t) = u(t),

where u(t) = e−2t [sin (2t+π/3)+cos 3t]. If the known conditions are y(0) = 1,
y(1) = 3, y(π) = 2, y (0) = 1 and y (1) = 2, find the analytical solution of the
ODE, and draw the solutions.
(2) Find the general solutions of the following ODEs.

x (t) − 2y (t) + y (t) + x(t) − 3y(t) = 0
(a)
4y (t) − 2x (t) − x (t) − 2x(t) + 5y(t) = 0,

 
2x (t) + 2x (t) − x(t) + 3y (t) + y (t) + y(t) = 0
(b)
x (t) + 4x (t) − x(t) + 3y (t) + 2y (t) − y(t) = 0.

4.5

4 1( )

3.5

3
2( )
2.5

1.5

0.5
0 0.5 1 1.5 2 2.5 3

. Fig. 10.14 Solution of the ODE


314 Chapter 10 · Ordinary Differential Equation Solutions

(3) Find the general solutions of the ODE, and the analytical solutions satisfying
the conditions x(0) = 1, x(π) = 2 and y(0) = 0.

x (t) + 5x (t) + 4x(t) + 3y(t) = e−6t sin 4t
2y (t) + y(t) + 4x (t) + 6x(t) = e−6t cos 4t.

(4) Find the analytical solutions of the following nonlinear ODEs.


(a) y (x) = y4 (x) cos x + y(x) tan x, (b) xy2 (x)y (x) = x2 + y2 (x),
(c) xy (x) + 2y(x) + x5 y3 (x)ex = 0.
(5) Find the analytical solutions of the following nonlinear ODE.
  2 
x2 y(x)y (x) − 2x2 y (x) + axy(x)y (x) + ay2 (x) = 0.

(6) Consider the well-known Rössler chemical reaction equation.


⎧ 
⎨ x (t) = −y(t) − z(t)
y (t) = x(t) + ay(t)
⎩ 
z (t) = b + (x(t) − c)z(t).

If a = b = 0.2, c = 5.7 and x(0) = y(0) = z(0) = 0, draw the 3D phase space
curve and its projection on the xy plane. If a = 0.2, b = 0.5 and c = 10, draw
10 again the 2D and 3D plots.
(7) In the following ODEs [6], g = 0.032 and γ = 0.02. The initial values are
y(0) = 0 and v(0) = 0.5. The value of φ(0) can be selected as 0.3782 and 9.7456
respectively, find the numerical solutions of the ODEs.
⎧ 

⎪ y (t) = tan φ(t)

g sin φ(t)γ v2 (t)
v (t) = −

⎪ v(t) cos φ(t)
⎩ 
φ (t) = −g/v2 (t).

(8) Chua circuit is the commonly used ODE in chaos [7].


⎧ 
⎨ x (t) = α[ y(t) − x(t) − f (x(t))]
y (t) = x(t) − y(t) + z(t)
⎩ 
z (t) = −βy(t) − γ z(t),

where f (x) is the piecewise nonlinearity

1
f (x) = bx + (a − b)(|x + 1| − |x − 1|),
2

and a < b < 0. Write a MATLAB function to express the ODE, and draw the
phase space trajectory, when α = 15, β = 20, γ = 0.5, a = −8/7, b = −5/7, and
the initial values x(0) = −2.121304, y(0) = −0.066170 and z(0) = 2.881090.
10.5 · Exercises
315 10
(9) Find the numerical solutions of the ODE [8]

y (x) = −2xy(x) ln z(x)
z (x) = 2xz(x) ln y(x).

The initial values are y(0) = e and z(0) = 1, and the analytical solutions are
2 2
y(x) = ecos x and z(x) = esin x . Compare the speed and accuracy using different
solvers.
(10) In the following ODE [9], Ka = 31 × 10−8 , Kw = 3.25 × 10−18 , α = 55.5 × 106 ,
β = 10−5 and γ = 1.11 × 106 . If the initial values of the states are all 0’s, solve
the ODE.
⎧ 
⎪ w (t) = αKw + βy(t) − γ x(t)w(t) − αw(t)z(t)


x (t) = −x(t) + βy(t) − γ x(t)w(t) − y(t)z(t)/Ka

⎪ y (t) = x(t) − βy(t) + γ x(t)w(t) − y(t)z(t)/Ka
⎩ 
z (t) = αKw + x(t) + αw(t)z(t) − y(t)z(t)/Ka .

(11) Consider the Duffing equation.

x (t) + μ1 x (t) − x(t) + 2x3 (t) = μ2 cos t, where, x1 (0) = γ , x2 (0) = 0,

(a) If μ1 = μ2 = 0, find the numerical solutions. Draw the phase plane trajec-
tories for different initial values γ = [0.1 : 0.1 : 2].
(b) If μ1 = 0.01, μ2 = 0.001, select γ = 0.99, 1.01, draw the phase plane
trajectories.
(c) If x2 (0) = 0.2, draw phase plane trajectories for different values of γ ’s.
(12) Select the state variables, and convert the following nonlinear ODE into first-
order explicit ODEs. Solve the ODEs and draw the phase plane or phase space
trajectories.
 
x (t) = −x(t) − y(t) − (3x (t))2 + (y (t))3 + 6y (t) + 2t
(a)
y (t) = −y (t) − x (t) − e−x(t) − t,
where x(1) = 2, x (1) = −4, y(1) = −2, y (1) = 7 and y (1) = 6.
⎧ 
⎨ x (t) − 2x(t)z(t)x (t) = 3t2 x2 (t)y(t)
(b) y (t) − ey(t) y (t) = 4t2 x(t)z(t)

z (t) − 2tz (t) = 2tex(t)y(t) ,
where z (1) = x (1) = y (1) = 2, z(1) = x(1) = y(1) = 3.

 (4)
x (t) − 8 sin ty(t) = 3t − e−2t
(c)
y(4) (t) + 3te−5t x(t) = 12 cos t,
when x(0) = y(0) = 0, x (0) = y (0) = 0.3, x (0) = y (0) = 1, x (0) =
y (0) = 0.1.
(13) Solve the following ODE and find the analytical and numerical solutions.

x (t) = −2x(t) − 3x (t) + e−5t , x(0) = 1, x (0) = 2
y (t) = 2x(t) − 3y(t) − 4x (t) − 4y (t) − sin t, y(0) = 3, y (0) = 4.
  
316 Chapter 10 · Ordinary Differential Equation Solutions

(14) The simplified model of catalytic fluidized bed is [10]


⎧   
⎪ x (t) = 1.30 y2 (t) −

⎨  x(t) + 2.13 × 106 ky  1 (t)
y1 (t) = 1.88 × 103 y3 (t) − y1 (t)(1 + k)

⎪ y2 (t) = 1752 − 269y2 (t) + 267x(t)


y3 (t) = 0.1 + 320y1 (t) − 321y2 (t),

with x(0) = 761, y1 (0) = 0, y2 (0) = 600, y3 (0) = 0.1, and k = 0.006e20.7−15000/x(t) .
If t ∈ (0, 100), find the numerical solution of the stiff ODE.
(15) For the following linear stiff ODE [11]
⎡ ⎤ ⎡ ⎤
−2a a 0
⎢ 1 −2 1 ⎥ ⎢0⎥
⎢ ⎥ ⎢ ⎥
⎢ 0 1 −2 1 ⎥ ⎢0⎥
y (t) = ⎢
⎢ ... ... ... ⎥
⎥ y(t) + ⎢ .. ⎥ ,
⎢.⎥
⎢ ⎥ ⎢ ⎥
⎣ 1 −2 1 ⎦ ⎣0⎦
b −2b b

where a = 900 and b = 1000. If the initial value y(0) is a zero vector, and the
order n = 9, the solution interval is t ∈ (0, 120), find the solutions to the ODE.
(16) In the following nonlinear stiff ODE [11], γ = 100 and t ∈ (0, 1), the initial
states are all zero. Solve the ODE.
10 ⎧ 
⎪ y1 (t) = y2 (t)



⎪ y2 (t) = y3 (t)


⎨ y (t) = y (t)
3 4

⎪   y2 (t)y3 (t)


⎪ y4 (t) = y12 (t) − sin y1 (t) − γ 4 + − 4γ 3

⎪ y12 (t) + 1

⎩    
+ 1 − 6γ 2 y3 (t) + 10e−y4 (t) − 4γ y4 (t) + 1.
2

(17) In the following differential–algebraic equation [12], if the initial values are
x(0) = [1, 0, 0, 0]T and y(t) = 0, the constant g = 9.81, and the interval is
t ∈ (0, 6), find the numerical solutions of the differential–algebraic equations.


⎪ x1 (t) = x3 (t) − 2x1 (t)y2 (t)



⎪ x2 (t) = x4 (t) − 2x2 (t)y2 (t)

x3 (t) = −2x1 (t)y1 (t)

⎪ x4 (t) = −g − 2x2 (t)y1 (t)



⎪ x1 (t) + x22 (t) =
2 1

x1 (x)x3 (t) + x2 (t)x4 (t) = 0.

(18) Consider the following time-varying linear differential–algebraic equations [13].


If x1 (0) = x2 (0) = 1 and α is a constant, and the analytical solution is
x1 (t) = x2 (t) = et , z(t) = −et /(2 − t), find the numerical solution of the
differential–algebraic equations.
10.5 · Exercises
317 10
⎧   
⎨ x1 (t) = α − 1/(2 − t) x1 (t) + (2 − t)αz(t) + (3 − t)/(2 − t)
x (t) = (1 − α)x1 (t)/(t − 2) − x2 (t) + (α − 1)z(t) + 2e−t
⎩ 2
0= (t + 2)x1 (t) + (t2 − 4)x2 (t) − (t2 + t − 2)et .

(19) Consider the following implicit ODE [14], where m1 = m2 = 0.1, L = 1,


g = 9.81, y0 = [0, 4, 2, 20, −π/2, 2]T , the tine interval is t ∈ (0, 4). Find the
numerical solution of the implicit ODE.
⎧ 
⎪ 0 = y1 (t) − y2 (t)



⎪ 0 = (m1 + m2 )y2 (t) − m2 Ly6 (t) sin y5 (t) − m2 Ly62 (t) cos y5 (t)


0 = y3 (t) − y4 (t)
  
⎪ 0 = (m


1 + m2 )y4 (t) + m2 Ly6 (t) cos y5 (t) − m2 Ly6 (t) sin y5 (t) + (m1 + m2 )g
⎪ 
⎪ 0 = y5 (t) − y6 (t)


0 = −Ly2 (t) sin y5 (t) − Ly4 (t) cos y5 (t) − L2 y62 (t) + gL cos y5 (t).

(20) Consider the following DDE [15], where when t ≤ 0, y1 (t) = 5, y2 (t) = 0.1
and y3 (t) = 1. Find the numerical solution of the DDE in the time interval
t ∈ (0, 40). ⎧ 
⎨ y1 (t) = −y1 (t)y2 (t − 1) + y2 (t − 10)
y (t) = y1 (t)y2 (t − 1) − y2 (t)
⎩ 2
y3 (t) = y2 (t) − y2 (t − 10).
(21) Solve the following DDE, where a = 0.1, b = 0.2, n = 10 and r = 20. The
solution interval is t ≤ 1000.

by(t − τ )
y (t) = − ay(t).
1 + yn (t − τ )

(22) Solve the following DDE [15].


⎧   
⎨ V (t) = h1 − h2 F (t) V (t)  
C  (t) = ξ(m(t))h
 3 F (t − τ )V (t − τ ) − h5 C(t) − 1
⎩ 
F (t) = h4 C(t) − F (t) − h8 F (t)V (t),

where, τ = 0.5, h1 = 2, h2 = 0.8, h3 = 104 , h4 = 0.17, h5 = 0.5, h7 = 0.12,


h8 = 8 and h6 can be selected as 10 or 300. When t ≤ 0, V (t) = max(0, 10−6 +t),
C(t) = F (t) = 1. Function ξ(m(t)) is a piecewise function defined below, where,
m(t) satisfies m (t) = h6 V (t) − h7 m(t), and when t ≤ 0, m(t) = 0.

1,   if m(t) ≤ 0.1
ξ(m(t)) =
10 1 − m(t) /9, if 0.1 < m(t) ≤ 1.

(23) Solve the following DDE [6], where, when t ≤ 0, y1 (t) = y4 (t) = y5 (t) = et+1 ,
y2 (t) = et+0.5 and y3 (t) = sin(t + 1). The solution interval is t ∈ [0, 1].
318 Chapter 10 · Ordinary Differential Equation Solutions

⎧ 

⎪ y (t) = y5 (t − 1) + y3 (t − 1)
⎪ 1

⎨ y2 (t) = y1 (t − 1) + y2 (t − 0.5)
y3 (t) = y3 (t − 1) + y1 (t − 0.5)



⎪ y (t) = y5 (t − 1)y4 (t − 1)
⎩ 4
y5 (t) = y1 (t − 1).

(24) Solve the DDE with variable delay [16], with 0 ≤ t ≤ 1 and y(t) = 1.

t−1  
y (t) = y t − ln t − 1 y(t), t ≥ 1.
t

(25) Solve the following DDE [17], where, when t ≤ 0, x(t) = sin t. The known
analytical solution is x(t) = sin t. Assess the solutions of the DDE.
   
x (t) = −x t − 1 − e−t + cos t + sin t − 1 − e−t .

(26) Solve the simple neutral-type DDE [16]

y (t) = y(t) + y (t − 1),

where, when t ≤ 0, y(t) = 1, in the interval t ∈ (0, 3). The analytical solution is
⎧ t
⎨e , 0≤t≤1
10 y(t) = et + (t − 1)et−1 ,
⎩ t
1<t<2
e + et−1 + (t − 2)(t + 2e)et−2 /2, 2 ≤ t ≤ 3.

(27) Solve the following BVP, where y(0) = 0, y(1) = ln 2, y (0) = −1 and y (1) =
−0.25. The analytical solution is y(t) = ln(1 + t).

12
y(4) (t) = 6e−4y(t) − .
(1 + t)4

(28) Solve the following BVP [18]

y (x) − 400y(x) = 400 cos2 πx + 2π2 cos 2πx, where, y(0) = y(1) = 0.

e−20 20x 1
The analytical solution is y(x) = −20
e + e−20x − cos2 πx.
1+e 1 + e−20
(29) Solve the following BVP [18]
⎧   

⎪ y1 (t) = ay1(t) y3 (t) − y1(t) /y2 (t)


⎨ y2 (t) = −a y3(t) − y1 (t)   
y3 (t) = b − c y3 (t) − y5 (t) − ay3 (t) y3 (t) − y1 (t) /y4 (t)

⎪ 
⎪ y4 (t) = a y3 (t) − y1 (t) 


y5 (t) = −c y5 (t) − y3 (t) /d,
10.6 · Mini-Projects
319 10
where, a = 100, b = 0.9, c = 1000 and d = 10. The given boundary value
conditions are y1 (0) = y2 (0) = y3 (0) = 1, y4 (0) = −10 and y3 (1) = y5 (1).
(30) Solve the following BVP [6].
⎧ 

⎪ y1 (t) = y2 (t)


⎨ y2 (t) = y3 (t)
y3 (t) = −(3 − n)y1 (t)y3 (t)/2 − ny22 (t) + 1 − y42 (t) + sy2 (t)



⎪ y (t) = y5 (t)  
⎩ 4
y5 (t) = −(3 − n)y1 (t)y3 (t)/2 − (n − 1)y2 (t)y4 (t) + s y4 (t) − 1 ,

where, n = −0.1, s = 0.2. The given boundary conditions are y1 (0) = y2 (0) =
y4 (0) = y2 (b) = 0, y4 (b) = 1 and b = 11.3.
(31) Solve the following BVP in semi-infinite interval [19]. The boundary conditions
are y(0) = 0, z(0) = 1 and y (∞) = z (∞) = 0.
  
3y(t)y (t) = 2 y (t) − z(t)
z (t) = −y(t)z (t).

(32) Consider the following BVP [5].


⎧  
⎨ f  (t) − R (f  (t))2 − f (t)f  (t) + AR = 0
h (t) + Rf (t)h (t) + 1 = 0

θ  (t) + Pf (t)θ  (t) = 0,

where R = 10,P = 0.7R, and A is the undermined constant. If the given bound-
ary conditions are f (0) = f  (0) = 0, f (1) = 1, f  (1) = 0, h(0) = h(1) = θ (0) = 0
and θ (1) = 1, solve the problem. If R = 10000, solve the problem again.

10.6 Mini-Projects

1. A Relatively Complicated ODE


Consider the seven-body problem. The coordinates (xi (t), yi (t)) of the seven bodies
satisfy the following differential equations [15]:
 mj    mj  
xi (t) = xj (t) − xi (t) , yi (t) = yj (t) − yi (t) ,
rij (t) rij (t)
j=i j=i

where, mi = i, i = 1, 2, . . . , 7, and
 3/2
rij (t) = (xi (t) − xj (t))2 + (yi (t) − yj (t))2

The initial positions and speeds of the bodies are known as x1 (0) = 3, x2 (0) = 3,
x3 (0) = −1, x4 (0) = −3, x5 (0) = 2, x6 (0) = −2, x7 (0) = 2, y1 (0) = 3, y2 (0) = −3,
y3 (0) = 2, y4 (0) = 0, y5 (0) = 0, y6 (0) = −4, y7 (0) = 4, x6 (0) = 1.75, x7 (0) = −1.5,
320 Chapter 10 · Ordinary Differential Equation Solutions

y4 (0) = −1.25, y5 (0) = 1, and all the other xi (0) = yi (0) = 0. The simulation interval
is t ∈ (0, 3).
Different ways can be used to describe the complicated ODEs. Can you describe
them in the simplest form? Once you have found the numerical solutions, can you use
dynamic plotting facilities to show the trajectories of the seven bodies?
Remember to validate the numerical solutions.

2. Solving BVPs in a Different Way


Consider the BVP problem in Example 10.22. Of course, with the solver bvp5c(), the
problem can be solved directly. Unfortunately, there are quite a lot of BVP problems
which cannot be solved with existing solvers in MATLAB. For instance, for an ordi-
nary delay differential equation problem with known boundary conditions, there are
no existing solvers in MATLAB.
Let us make an assumption here. Assume that we do not know the bvp5c() solver,
we may consider converting the BVP problem into an algebraic equation solution
problem.
Consider the problem in Example 10.23. Since the initial values are already known,
let the unknowns x1 = α, x2 = β, and solve the ODE, the numerical solution x̂(t)
and ŷ(t) of the two states x(t) and y(t) can be found. The simultaneous algebraic
equations x̂(3) − 3 = 0 and ŷ(3) − 2 = 0 can be established, where x̂(3) and ŷ(3)
are determined by the unknowns x1 and x2 . An algebraic equation-based method can
then be established in solving BVPs. Solve Example 10.23 with the new method, and
solve again the problem in Example 10.22. See whether the same solutions can be
10 found.

References
1. Xue DY (2020) Differential equation solutions with MATLAB[M]. De Gruyter, Berlin
2. Polyanin AD, Zaitsev VF (2018) Handbook of ordinary differential equations — Exact solutions,
methods and problems[M]. CRC Press, Boca Raton
3. Govorukhin V (2003) Ode87 integrator[R]. MATLAB Central File ID: #3616
4. Kierzenka J, Shampine LF (2001) A BVP solver based on residual control and the MATLAB PSE[J].
ACM Trans Math Softw 27(3):299–316
5. Ascher UM, Mattheij RMM, Russel RD (1995) Numerical solution of boundary value problems for
ordinary differential equations[M]. SIAM Press, Philadelphia
6. Shampine LF, Gladwell I, Thompson S (2003) Solving ODEs with MATLAB[M]. Cambridge Uni-
versity Press, Cambridge
7. Zhang HG, Wang ZL, Huang W (2003) Control theory of chaotic systems(in Chinese)[M]. North-
eastern University Press, Shenyang
8. Felhberg E (1969) Low-order classical Runge–Kutta formulas with stepsize control and their appli-
cations to some heat transfer problems[R]. Washington DC: NASA Technical Report TR R-315
9. Chicone C (2018) An invitation to applied mathematics: differential equations, modeling and compu-
tation[M]. Elsevier, London
10. Lapidus L, Aiken RC, Liu YA (1974) The occurrence and numerical solution of physical and chemical
systems having widely varying time constants[M]. In: Willoughby RA (ed) Stiff differential systems.
Plenum Press, New York
11. Enright WH (1974) Optimal second derivative methods for stiff systems[M]. In: Willoughby RA (ed)
Stiff differential systems. Plenum Press, New York
References
321 10
12. Burger M, Gerdts M (2017) A survey on numerical methods for the simulation of initial value problems
with sDAEs[M]. In: Ilchmann A, Reis T (ed) Surveys in differential–algebraic equations IV. Springer,
Switzerland
13. Ascher UM, Petzold LR (1998) Computer methods for ordinary differential equations and differential-
algebraic equations[M]. SIAM Press, Philadelphia
14. Keskin AÜ (2019) Ordinary differential equations for engineers − Problems with MATLAB solu-
tions[M]. Springer, Switzerland
15. Hairer E, Nørsett SP, Wanner G (1993) Solving ordinary differential equations I: Nonstiff prob-
lems[M], 2nd edn. Springer, Berlin
16. Bellen A, Zennaro M (2003) Numerical methods for delay differential equations[M]. Oxford University
Press, Oxford
17. Cryer CW (1972) Numerical methods for functional differential equations[M]. In: Schmitt K (ed)
Delay and functional differential equations and their applications. Academic Press, New York
18. Scott MR, Watts HA (1976) A systematized collection of codes for solving two-point boundary-value
problems[M]. In: Lapidus L, Schiesser WE (ed) Numerical methods for differential systems — Recent
developments in algorithms, software, and applications. Academic Press, New York
19. Gladwell I (1979) The development of the boundary-value codes in the ordinary differential equations
— Chapter of the NAG library[M]. In: Childs B (ed) Codes for boundary-value problems in ordinary
differential equations. Springer, Berlin
323 11

Optimization Problem
Solutions
Contents

11.1 Unconstrained Optimization Problems – 324


11.1.1 Standard Form of Unconstrained Optimization
Problems – 324
11.1.2 Solutions of Unconstrained Optimization Problems – 325
11.1.3 Precision Control in Unconstrained Optimization
Solutions – 326

11.2 Linear and Quadratic Programming – 326


11.2.1 Linear Programming – 327
11.2.2 Quadratic Programming – 330
11.2.3 Problem-Based Description and Solutions – 330

11.3 Nonlinear Programming – 333


11.3.1 Mathematical Form of Nonlinear Programming
Problems – 333
11.3.2 Direct Solutions of Nonlinear Programming Problems – 333
11.3.3 Local and Global Optimum Solutions – 335

11.4 Attempting to Global Optimum Solutions – 337


11.4.1 Introduction to MATLAB Global Optimization Toolbox – 337
11.4.2 A New Global Unconstrained Optimization Solver – 339
11.4.3 A New Global Constrained Optimization Solver – 342

11.5 Exercises – 344

11.6 Mini-Projects – 351

References – 352

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_11
324 Chapter 11 · Optimization Problem Solutions

Optimization techniques are very important tools in scientific research and engineer-
ing, and they are also effective means in solving problems in science and engineering.
It is not exaggerating to say that, once equipped with the ideas and solution methods
of optimization, the user’s capability in scientific research will be boosted to an upper
level. In ordinary research, the user is very happy to find a solution to a problem,
while if he has optimization ideas in mind, it is quite natural that he will pursuit to
the best possible solution to the problem. Various optimization problems and solu-
tion methods are introduced in this chapter, with new global solvers developed for
unconstrained and constrained optimization problems.
In 7 Sect. 11.1, the solutions to unconstrained optimization problems are pre-
sented first. In 7 Sect. 11.2, description and solution methods are presented for linear
and quadratic programming problems. Besides, the new problem-based description
and solution methods are illustrated. In 7 Sect. 11.3, ordinary nonlinear program-
ming problems are presented. In 7 Sect. 11.4, a brief introduction to the intelligent
optimization solvers provided in the Global Optimization Toolbox is made first. Two
solvers aiming at finding global minimum solutions to unconstrained and constrained
problems are developed, respectively. Comparisons are made on the intelligent solvers
and the global optimization solvers. It is found that the global solvers are more effi-
cient than the solvers provided in the Global Optimization Toolbox [1].

11.1 Unconstrained Optimization Problems


Unconstrained optimization problems are a class of the simplest optimization prob-
lems. In this section, the solution methods for unconstrained optimization problems
11 are presented.

11.1.1 Standard Form of Unconstrained Optimization Problems


The mathematical form of an unconstrained optimization problem is

min f (x), (11.1)


x

where x = [x1 , x2 , . . . , xn ]T is referred to as the decision variables; the scalar function


f (·) is referred to as the objective function.
The physical meaning of the above mathematical notation is to find a vector
x, such that the value of the objective function f (x) is minimized. Therefore, the
problem is also known as the minimization problem. Since the values in the x vector
can be selected arbitrarily, the problem is referred to as unconstrained optimization
problems.
In fact, minimization problem is a general description of optimization problems,
without losing generality. To solve maximization problem, it can be converted to
minimization problem by multiplying the objective function f (x) by −1. There-
fore, in the following presentation in this chapter, only minimization problems are
considered.
11.1 · Unconstrained Optimization Problems
325 11
11.1.2 Solutions of Unconstrained Optimization Problems
A solver fminsearch() is provided in MATLAB to solve optimization problems.
An alternative solver fminunc() is presented in the Optimization Toolbox. The two
solvers have the same syntaxes
x=fminsearch(Fun,x 0 ), % simplest form
[x,f0 ,flag,out]=fminsearch(Fun,x 0 ,opt), % with control parameters
[x,f0 ,flag,out]=fminsearch(Fun,x 0 ,opt,p1 ,p2 ,· · · )
where, Fun is the handle for the objective function, which can be a MATLAB function
name, or an anonymous function; x 0 is the initial search vector; opt is the control
option. Apart from these, additional parameters p1 , p2 , · · · are also allowed, but not
recommended. An alternative method will be shown next. In the returned arguments,
x is the solution of the decision vector; f0 is the optimal value of the objective function;
flag is an identifier, if flag is greater than 0, the solution process is successful; if it is
negative, the solution is not found. The returned argument out contains intermediate
information, such as the number of iterations and so on.
In the solver fminsearch(), the improved simplex method in Reference [2] is
adopted, while in fminunc() function, quasi-Newton and trust region algorithms
are implemented. It can be seen from the algorithms that in fminsearch() function,
the gradient of the objective function is not needed, nor needed in the quasi-Newton
algorithm in function fminunc(). If trust region method is adopted in fminunc()
function, gradient information is needed.

 Example 11.1
Consider again the function z = f (x, y) = (x2 − 2x)e−x −y −xy in Example 5.21. Find the
2 2

minimum value of the function with MATLAB, and explain its physical meaning.
Solutions Since the independent variables x and y are involved, while in the optimization
problem, independent variable vector x is expected, variable substitutions should be made
first. Let x1 = x and x2 = y, the objective function can be modified manually into

z = f (x) = (x12 − 2x1 )e−x1 −x2 −x1 x2 .


2 2

To solve the problem, the objective function should be described in MATLAB first.
Normally, there are two ways describing it. One is to use MATLAB function, and the
other is to use anonymous function. Let us look at the MATLAB function programming
method. In this method, the vector x is used to compute the objective function y.
function y=c11mopt(x)
y=(x(1)^2-2*x(1))*exp(-x(1)^2-x(2)^2-x(1)*x(2));
end
Of course, for a simple problem, it is better to use anonymous function to describe
the objective function. The benefit of this method is that there is no need to create a
MATLAB file. A dynamic MATLAB command is sufficient. Another benefit is that the
variables in MATLAB workspace can be used directly. With the following commands,
326 Chapter 11 · Optimization Problem Solutions

the objective function can be described by the anonymous function, and then the solution
x = [0.6110, −0.3055] can be found directly. That is in the original problem, x = 0.6110
and y = −0.3055. Compare the surface obtained in . Fig. 5.21 that, the optimization
result is the valley of the surface. From the returned argument d, it can be seen that 46
times iterations are made, while the objective function is called 90 times.
>> f=@(x)(x(1)^2-2*x(1))*exp(-x(1)^2-x(2)^2-x(1)*x(2)); % objective function
x0=[2; 1]; [x,b,flag,d]=fminsearch(f,x0) % solve the optimization problem
If the same problem is solved with fminunc() function, the same results can be found.
The number of objective function call is 66, and the total number of iteration is 7. It is found
that the efficiency of this solver is obviously higher than the fminsearch() function.
>> [x,b,flag,d]=fminunc(f,[2; 1]) % another solver


11.1.3 Precision Control in Unconstrained Optimization Solutions


In the first syntax of the function, the argument opt is the same as the one for fsolve()
function in 7 Chap. 9. The initial variable can be read in with optimset() function.
Its TolX member controls the precision. To get the best possible solution under double
precision data type, it can be set to eps.

 Example 11.2
Find the most accurate solution to the problem in Example 11.1.

11 Solutions The control variable TolX can be set to eps, then the solution process is invoked
again. The total number of iterations is increased to 113, and the objective function is
called 262 times. The computational load is nearly doubled, compared with the results in
Example 11.1. The solution is the most accurate one under double precision framework.
>> f=@(x)(x(1)^2-2*x(1))*exp(-x(1)^2-x(2)^2-x(1)*x(2)); % objective function
x0=[2; 1]; ff=optimset; ff.TolX=eps; ff.TolFun=eps;
[x,b,flag,d]=fminsearch(f,x0,ff) % optimization problem from initial values


11.2 Linear and Quadratic Programming


In the unconstrained optimization problems, the decision variable x can be chosen
arbitrarily, without any restrictions. In applications, there are usually restrictions
on the decision variables. In this section, two special cases of constrained optimiza-
tion problems— linear and quadratic programming problems—are mainly discussed.
Problem-based description and solution methods are also illustrated.
11.2 · Linear and Quadratic Programming
327 11
11.2.1 Linear Programming
The mathematical description of linear programming is

min f T x, (11.2)


⎨ Axb
x s.t. Aeq x=beq


x m xx M

where s.t. means subject to. Therefore, the mathematical formula after it is referred
to as the constraints. The physical interpretation of the expressions is that, how to
select decision vector x, such that all the constraints are satisfied, and the value of
the objective function is minimized. The constraints here are further classified into
linear equation constraints Aeq x = B eq , linear inequality constraints Ax  B, upper
bounds x M and lower bounds x m for the decision vector x. The constraints are linear,
the objective function is also a linear combination of the decision variables. Therefore,
the optimization problem is referred to as linear programming problem.
For the inequalities, the standard definition in MATLAB is the  inequalities. If
in a certain inequality constraint, the relation  is used, −1 can be multiplied to both
sides, to convert them uniformly to  inequalities. Therefore,  inequalities are used
in the book.
A solver provided in MATLAB can be used to solve linear programming problems,
with the syntaxes
[x,fopt ,flag,out]=linprog( f , A,b, Aeq ,B eq ,x m ,x M ,options)
[x,fopt ,flag,out]=linprog(problem)
where in the first syntax, the definitions of the arguments f , A, b, Aeq , beq , x m and x M
are the same as the ones in (11.2). If a certain constraint does not exist, the matrices
can be set to empty ones such as []. The argument options is the control options.
After the optimization solution, the result is returned in vector x, while the objective
function value is returned in the argument fopt . Since linear programming problems
are convex ones, if a solution is obtained, it is the global optimum solution of the
original problem. There is no need to assign initial values artificially. If the returned
flag is positive, the solution process is successful. The argument out returns other
additional information.
In the second syntax, the entire linear programming problem is described in a
structure d variable problem, whose members are shown in . Table 11.1.
Examples are given next to demonstrate the solutions to linear programming
problems.

 Example 11.3
Solve the linear programming problem in Example 1.7 again.

min −2x1 − x2 − 4x3 − 3x4 − x5 .



⎨ 2x2 +x3 +4x4 +2x5 54
x s.t. 3x1 +4x2 +5x3 −x4 −x5 62

x1 ,x2 0,x3 3.32,x4 0.678,x5 2.57
328 Chapter 11 · Optimization Problem Solutions

. Table 11.1 Members for the structured variable for linear programming problems

Members Descriptions

f Coefficient vector f in the objective function

Aineq, bineq Matrix A and vector b in the linear inequality constraints

Aeq, beq Matrix Aeq and vector beq in the linear equation constraints

ub,lb The upper bound x M and lower bound x m of decision variables

Options Control options, the members of this variable can be modified first, then
passed to options

Solver Must be set to 'linprog'

Solutions Compare the problem and its standard form, it can be seen that the objective
function can be expressed by its coefficient vector f = [−2, −1, −4, −3, −1]T , and the
inequality can be expressed in matrix form.
   
0 2 1 4 2 54
A= , b= .
3 4 5 −1 −1 62

Besides, since there are no equation constraints, the matrices Aeq and beq can be set to
empty matrices. It is also seen from the mathematical expression that the lower bounds
of x are given by x m = [0, 0, 3.32, 0.678, 2.57]T , and there are no upper bounds. Thus,
11 the upper bounds can be set to an empty matrix. From the above analysis, it can be seen
that the following commands can be issued to solve the problem, and the solutions x =
[19.785, 0, 3.32, 11.385, 2.57]T and fopt = −89.5750 are found immediately.
>> f=-[2 1 4 3 1]'; A=[0 2 1 4 2; 3 4 5 -1 -1]; b=[54; 62];
Ae=[]; be=[]; xm=[0,0,3.32,0.678,2.57]; % input the matrices and vectors
[x,f_opt,key,c]=linprog(f,A,b,Ae,be,xm) % solve LP problem
It can be seen that key is 1, indicating that the solution process is successful. Only two
iterations are used to solve the linear programming problem. It can be seen that the solver
is powerful and can be used to solve linear programming problems. 

 Example 11.4
Solve the problem in Example 11.3 again with structured variable description.
Solutions The following commands construct the structured variable P for the linear pro-
gramming problem. Some of the members such as Aeq can be ignored, which are assigned
to the default empty matrix automatically, since Aeq matrix is not involved in the example.
There is also no need to specify the upper bound member. The solution obtained is identical
to the one obtained earlier. Note that before the solution procedure, clear command is
used to remove the existing P variable, if any, otherwise, the remaining members of the
existing P may affect the solution process.

>> clear P; P.f=-[2 1 4 3 1]'; % clear P from MATLAB workspace


P.Aineq=[0 2 1 4 2; 3 4 5 -1 -1]; P.Bineq=[54; 62];
11.2 · Linear and Quadratic Programming
329 11
P.lb=[0,0,3.32,0.678,2.57]; P.solver='linprog';
ff=optimset; ff.TolX=eps; P.options=ff; % input control options
[x,f_opt,key,c]=linprog(P) % solve the linear programming problem directly


 Example 11.5
Solve the following linear programming problem.

max 3x1 /4 − 150x2 + x3 /50 − 6x4 .



⎨ x1 /4−60x2 −x3 /50+9x4 0
x s.t. −x1 /2+90x2 +x3 /50−3x4 0

x3 1,x1 −5,x2 −5,x3 −5,x4 −5

Solutions In the original problem, maximization is expected. Therefore, it should be con-


verted into minimization problem first. That is to multiply the objective function by −1,
such that the new objective function is rewritten as −3x1 /4 + 150x2 − x3 /50 + 6x4 . Besides,
the second constraint should also be converted into the standard one. Therefore, the stan-
dard form of the linear programming problem is rewritten as

min −3x1 /4 + 150x2 − x3 /50 + 6x4 .



⎨ x1 /4−60x2 −x3 /50+9x4 0
x s.t. x1 /2−90x2 −x3 /50+3x4 0

x3 1,x1 −5,x2 −5,x3 −5,x4 −5

In the linear programming framework, it is found that the objective function coefficient
vector f T is [−3/4, 150, −1/50, 6], and the constraint matrices are
   
1/4 −60 −1/50 9 0
A= , B= .
1/2 −90 −1/50 3 0

Besides, the lower and upper bounds of the decision vector are

x m = [−5, −5, −5, −5]T , x M = [+∞, +∞, 1, +∞]T ,

where, Inf can be used to describe +∞. The first two constraints are both inequality ones.
In the second one, the  inequality is converted to  one, by multiplying both sides by −1.
Since there are no equation constraints, let Aeq =[] and B eq =[]. Finally, the following
commands solve the linear programming problem directly, such that the optimized solution
can be found.

>> f=[-3/4,150,-1/50,6]; Aeq=[]; Beq=[]; % objective function


A=[1/4,-60,-1/50,9; 1/2,-90,-1/50,3]; B=[0;0]; % inequality constraints
xm=[-5;-5;-5;-5]; xM=[Inf;Inf;1;Inf]; % decision variable bounds
F=optimset; F.TolX=eps; F.TolFun=1e-10; % precision setting
[x,f0,key,c]=linprog(f,A,B,Aeq,Beq,xm,xM,[],F) % direct solution
It can be seen that with three iterations, the optimum solution of the problem can be
found as x = [−5, −0.1947, 1, −5]T . If structured variable is used to describe the problem,
the identical solution can be found.
330 Chapter 11 · Optimization Problem Solutions

>> clear P; P.f=f; P.Aineq=A; P.Bineq=B; P.solver='linprog';


P.lb=xm; P.ub=xM; P.options=F; linprog(P) % structured variable


11.2.2 Quadratic Programming


The mathematical form of a quadratic programming problem is

1 T
min f Tx + x H x. (11.3)
⎧ 2

⎨ AxB
x s.t. Aeq x=B eq


x m xx M

Compared with linear programming problems, the constraints are the same. The
difference is in the objective function, where there is an extra quadratic term x T H x/2,
used to describe xi2 and xi xj terms. Therefore, the H matrix can be constructed for the
practical problems. If H matrix is positive-definite, the original problem is a convex
one, such that the solution obtained is the global optimum one.
A quadratic programming solver quadprog() is provided in MATLAB, with the
syntaxes
[x,fopt ,flag,out]=quadprog(problem)
[x,fopt ,flag,out]=quadprog(H, f , A,B, Aeq ,B eq ,x m ,x M ,options)
The quadratic programming problem can also be described by a structured vari-
11 able. The H member is used to describe the H matrix, while the solver member should
be set to ’quadprog’. Note that when matrix H is not positive-definite, the quadratic
programming problem is non-convex, the global optimum solution cannot be found
with the solver, or even, a feasible solution cannot be found.

11.2.3 Problem-Based Description and Solutions


The description and solution methods for linear and quadratic programming are pre-
sented earlier. To solve these problems, the optimization problems must be converted
first into the standard forms. In this section, an alternative description and solution
method is introduced. The method is referred to as problem-based method, and the
description of optimization problems is simpler and more straightforward.
The following procedures in problem-based description and solution methods for
linear and quadratic programming problems are
(1) Create of an optimization problem. Function optimproblem() creates a blank
optimization problem. The syntax of the function is
prob=optimproblem('ObjectiveSense','max')
11.2 · Linear and Quadratic Programming
331 11
If the ’ObjectiveSense’ property is not provided in the function call, the default
minimization problem is set.
(2) Define the decision variables with optimvar() function in the syntax
x=optimvar('x',n,m,k,'LowerBound',x m )
where, n, m and k are the sizes in the 3D array; if k is not given, an n × m decision
matrix x is defined; if m is 1, the decision vector n × 1 is defined. If x m is a scalar,
then the lower bounds of all the decision variables can be saved into the same values.
The property name LowerBound can be simplified as Lower. Similar methods can be
used to define the UpperBound property, simplified as Upper.
With the above two commands, the problem prob is used to define objective
functions and constraints. The specific format is illustrated through examples.
(3) Solve the optimization problem. With prob defined, the sols=solve(prob)
command solves directly the optimization problem. The result is returned in the struc-
tured variable sols, whose x member is the solution of the problem. Note that the
optimization discussed here can only be linear and quadratic programming ones.
If the Constraints are not specified, unconstrained optimization problems can be
solved directly.

 Example 11.6
Describe the linear programming problem in Example 11.5 with problem-based method.
For the convenience of demonstration, the original problem is provided again.

max 3x1 /4 − 150x2 + x3 /50 − 6x4 .



⎨ x1 /4−60x2 −x3 /50+9x4 0
x s.t. −x1 /2+90x2 +x3 /50−3x4 0

x3 1,x1 −5,x2 −5,x3 −5,x4 −5

Solutions Since there are differences in the problem with the standard form, manual con-
versions were needed in the previous methods. For instance, the maximization problem
and the ≥ inequality problem and so on. It may be an error-prone process to handle them
manually. A simpler and more straightforward problem-based description and solution
method can be used, and the results are the same as the one obtained in Example 11.5.

>> P=optimproblem('ObjectiveSense','max'); % maximization problem


x=optimvar('x',4,1,'LowerBound',-5); % decision variables and bounds
P.Objective=3*x(1)/4-150*x(2)+x(3)/50-6*x(4);
P.Constraints.cons1=x(1)/4-60*x(2)-x(3)/50+9*x(4)<=0;
P.Constraints.cons2=-x(1)/2+90*x(2)+x(3)/50-3*x(4)>=0;
P.Constraints.cons3=x(3)<=1; % the third upper bound
sols=solve(P); x0=sols.x % direct solution and extract the solutions

332 Chapter 11 · Optimization Problem Solutions

 Example 11.7
Describe and solve the linear programming problem with problem-based method.

max
⎧ 30x1 + 40x2 + 20x3 + 10x4 − 15s1 + 20s2 + 10s3 + 8s4 .

⎪ 0.3x1 +0.3x2 +0.25x3 +0.15x4 1000



⎪ 0.25x1 +0.35x2 +0.3x3 +0.1x4 1000



⎨ 0.45x1 +0.5x2 +0.4x3 +0.22x4 1000
x,s s.t. 0.15x1 +0.15x2 +0.1x3 +0.05x4 1000



⎪ x1 +s1 =800, x2 +s2 =750



⎪ x3 +s3 =600, x4 +s4 =500


xj 0, sj 0, j=1,2,3,4

Solutions To solve the problem with the old methods, manual conversion should be made
to convert the problem into a standard form. For instance, a new and unified decision
variable vector should be introduced to rewrite the problem, so as to find the standard
form. Function linprog() can then be called to solve the optimization problem. The
method is rather complicated and tedious. If problem-based method is used to describe the
problem, there is no need to convert the problem manually. Two decision variable vectors
can be defined. Direct expression of the problem is sufficient. Then the solution can be
found directly to the problem. The solutions found are x = [800, 750, 387.5, 500]T and
s = [0, 0, 212.5, 0]T .
>> P=optimproblem('ObjectiveSense','max'); % maximization problem
x=optimvar('x',4,1,'LowerBound',0); % decision variables and bounds
s=optimvar('s',4,1,'LowerBound',0); % another decision variables
P.Constraints.c1=0.3*x(1)+0.3*x(2)+0.25*x(3)+0.15*x(4)<=1000;
P.Constraints.c2=0.25*x(1)+0.35*x(2)+0.3*x(3)+0.1*x(4)<=1000;
11 P.Constraints.c3=0.45*x(1)+0.5*x(2)+0.4*x(3)+0.22*x(4)<=1000;
P.Constraints.c4=0.15*x(1)+0.15*x(2)+0.1*x(3)+0.05*x(4)<=1000;
P.Constraints.c5=x+s==[800;750;600;500]; % vectorized expressions
P.Objective=30*x(1)+40*x(2)+20*x(3)+10*x(4) ...
-(15*s(1)+20*s(2)+10*s(3)+8*s(4));
sols=solve(P); x0=sols.x, s0=sols.s


 Example 11.8
Solve the quadratic programming problem.

min (x1 − 1)2 + (x2 − 2)2 + (x3 − 3)2 + (x4 − 4)2 .



⎨ 1 2 +x3 +x4 5
x +x
x s.t. 3x1 +3x2 +2x3 +x4 10

x1 ,x2 ,x3 ,x4 0

Solutions Quadratic programming problems can also be described and solved with problem-
based methods. There is no need to formulate the H matrix manually. The following
commands can be used to describe the problem directly. Function solve() can then be
used to solve the original problem. The objective function and constraints can also be
described in vectorized form, such that the description is easier and more straightforward.
Execute the commands, the result obtained is x = [0, 0.6667, 1.6667, 2.6667].
11.3 · Nonlinear Programming
333 11
>> P=optimproblem; x=optimvar('x',4,1,'LowerBound',0);
P.Objective=sum((x-[1:4]').^2); % vectorized objective function
P.Constraints.cons1=sum(x)<=5; % two inequality constraints
P.Constraints.cons2=[3 3 2 1]*x<=10; % vectorized form
sols=solve(P); x0=sols.x % solution and extract the result


11.3 Nonlinear Programming


Linear and quadratic programming problems are special cases in nonlinear program-
ming problems. The constraints are linear, such that the problems are convex, which
ensures the global optimum solutions. Nonlinear programming problems are more
difficult to handle and global solutions cannot be guaranteed. In this section, the
mathematical form of nonlinear programming problems is presented, followed by
the direct solution methods.

11.3.1 Mathematical Form of Nonlinear Programming Problems


The mathematical form of the constrained optimization problem is

min f (x), (11.4)




⎪ AxB



⎨ Aeq x=B eq
x s.t. x m xx M



⎪ C(x)0


C eq (x)=0

where x = [x1 , x2 , . . . , xn ]T is the decision variable vector, and the objective function
f (x) is a scalar one.
The range of x satisfying all the constraints in (11.4) is known as the feasible region
of the nonlinear programming problem.

11.3.2 Direct Solutions of Nonlinear Programming Problems


Function fmincon() provided in MATLAB Optimization Toolbox solves directly
nonlinear optimization problems, with the syntaxes
[x,f0 ,flag,out]=fmincon(problem)
[x,f0 ,flag,out]=fmincon(f ,x 0 , A,B, Aeq ,B eq ,x m ,x M ,C,ff,p1 ,p2 ,· · · )
where f is the M-function or anonymous function written for the objective function; x 0
is the initial search point. If the matrices in the constraints do not exist, empty matrices
can be used instead. The term C is the handle of the M-function for the nonlinear
constraints, with two returned arguments c and ceq , with the former for nonlinear
inequalities, and the latter for nonlinear equations. Since two returned arguments are
334 Chapter 11 · Optimization Problem Solutions

needed, anonymous functions cannot be used to describe the nonlinear constraints.


M-function is the only way to describe the nonlinear constraints. The argument ff is
the control option, and additional parameters p1 , p2 , · · · are supported.
If structured variable is used to describe the nonlinear programming problem,
the members are shown in . Table 11.2. These members can be set directly. If the
constraints do not exist, they need not be set. If structured variable is used to describe
the optimization problem, additional parameters are not supported. Global variables
can be used to pass additional parameters. Or the parameters can be written into the
MATLAB function.

 Example 11.9
Solve the following constrained optimization problem.

min 1000 − x12 − 2x22 − x32 − x1 x2 − x1 x3 .


⎧ 2 2 2
⎨ 1 2 +x3 −25=0
x +x
x s.t. 8x1 +14x2 +7x3 −56=0

x1 ,x2 ,x3 0

Solutions It can be seen from the optimization problem that, there are nonlinear equations in
the constraints. Therefore, quadratic programming cannot be used to describe the problem.
Nonlinear programming must be adopted instead. The objective function can be expressed
directly with the anonymous function.

>> f=@(x)1000-x(1)*x(1)-2*x(2)*x(2)-x(3)*x(3)-x(1)*x(2)-x(1)*x(3);
Meanwhile, the two constraints are all equation ones, there are no inequality constraints,
11 and they can be set to an empty matrix. The following MATLAB function describes the

. Table 11.2 Members of the structured variable in nonlinear programming

Members Descriptions

Objective handle of the objective function

Aineq, bineq matrices A and b for nonlinear inequality

Aeq, beq matrices Aeq and beq for nonlinear equation constraints, where, if a
constraint does not exist, they can be set to empty matrices, or not used

ub, lb the upper bounds x M and lower bounds x m

options control options; the user may modify the control potions, and then set to
options members

solver can be set to 'fmincon'

nonlcon handle of the functions of the nonlinear constraints, which returns two
arguments, that is c and ceq

x0 initial search point x 0


11.3 · Nonlinear Programming
335 11
constraints. Note that, anonymous functions cannot be used to describe the nonlinear
constraints.
function [c,ceq]=opt_con1(x)
c=[]; % no nonlinear inequality constraints, and set to empty matrix
ceq=[x(1)*x(1)+x(2)*x(2)+x(3)*x(3)-25; 8*x(1)+14*x(2)+7*x(3)-56];
end
With the nonlinear inequality constraints described, matrices A, B, Aeq and B eq can
be set to empty matrices. Besides, the lower bounds of the decision variable are set to
x m = [0, 0, 0]T . An initial search point is set to x 0 = [1, 1, 1]T , then function fmincon()
can be called to solve the problem.
>> ff=optimset; ff.TolFun=eps; ff.TolX=eps; ff.TolCon=eps;
x0=[1;1;1]; xm=[0;0;0]; xM=[];
A=[]; B=[]; Aeq=[]; Beq=[]; % with empty linear constraints
[x,f0,flag,d]=fmincon(f,x0,A,B,Aeq,Beq,xm,xM,@opt_con1,ff)
The solution of the problem is x = [3.5121, 0.2170, 3.5522]T , and the objective function
is f0 = 961.7151. It can be seen from the components of d that, 15 iterations are made, and
the objective function is called 138 times.
Nonlinear programming problems can also be described with the following statements,
and the results obtained are the same. Structured variable description of the original prob-
lem is more concise and the solution process is more straightforward.
>> clear P; P.objective=f; P.nonlcon=@opt_con1;
P.x0=x0; P.lb=xm; P.options=ff; % structured variable description
P.solver='fmincon'; [x,f0,c,d]=fmincon(P) % solution
The second constraint is a linear equation. Therefore, it can be removed from the con-
straint function, such that the constraint can be simplified as
function [c,ceq]=opt_con2(x)
ceq=x(1)*x(1)+x(2)*x(2)+x(3)*x(3)-25; c=[]; % with linear equation removed
end
Linear equation constraint can be defined with the corresponding matrices. The follow-
ing commands can be used to solve again the problem, and the solution is exactly the same
as the ones obtained earlier. With the linear constraint removed, the number of iteration
is 16, and the objective function is called 107 times. The actual computational load is not
affected.
>> x0=[1;1;1]; Aeq=[8,14,7]; Beq=56; % use matrix to describe the constraints
[x,f0,c,d]=fmincon(f,x0,A,B,Aeq,Beq,xm,xM,@opt_con2,ff)


11.3.3 Local and Global Optimum Solutions


Consider the surface in Example 11.1. It happens that there is only one valley in
the original function. If there are more than one valleys, corresponding to different
objective function values, various initial values can be used to search for the optimum
solutions to yield different valleys. If the value of one valley is larger than another
one, the solution is referred to as local optimum solutions. Only the valley with the
336 Chapter 11 · Optimization Problem Solutions

smallest function value can be referred to as the global optimum solution. In normal
cases, it is useless to find local optimum solutions. Methods should be tried to find
the global optimum solutions of the problem, if possible.
Of course, it is not an easy task to judge whether a solution is a global optimum one
or not. For optimization problems with many decision variables, graphical methods
cannot be used to describe the optimum solutions. Besides, there is no analytical
solutions in a nonlinear programming problem, the term global optimum solution is
not recommended. The term best-known solution should be used instead.
The following example is used to demonstrate the local solutions and also demon-
strate a feasible way to find global optimum solutions.

 Example 11.10
Solve the following nonlinear programming problem [3].

⎧min k.
⎪ q3 +9.625q1 w+16q2 w+16w2 +12−4q1 −q2 −78w=0


⎪ 16q1 w+44−19q1 −8q2 −q3 −24w=0

q,w,k s.t. 2.25−0.25kq1 2.25+0.25k



⎪ 1.5−0.5kq2 1.5+0.5k

1.5−1.5kq3 1.5+1.5k

Solutions It can be seen from the optimization problem that, the decision variables are q,
w and k, while in standard optimization problems, only one vector is allowed. Therefore,
variable substitutions should be made. For this particular example, the decision variables
x1 = q1 , x2 = q2 , x3 = q3 , x4 = w and x5 = k can be selected. Besides, the nonlin-
ear inequalities can be further processed such that the original problem can be rewritten
11 manually into the form
⎧min x5 .

⎪ x3 +9.625x1 x4 +16x2 x4 +16x42 +12−4x1 −x2 −78x4 =0



⎪ 16x 1 x4 +44−19x1 −8x2 −x3 −24x4 =0



⎪ −0.25x 5 −x1 −2.25


x1 −0.25x5 2.25
x s.t.
⎪ −0.5x5 −x2 −1.5




⎪ x2 −0.5x5 1.5



⎪ −1.5x5 −x3 −1.5


x3 −1.5x5 1.5

It can be seen that there are two nonlinear equation constraints, no nonlinear inequality
ones. The following function can be written to describe the nonlinear constraints.
function [c,ce]=c11mnls(x)
c=[]; % nonlinear constraints where the inequality is set to empty
ce=[x(3)+9.625*x(1)*x(4)+16*x(2)*x(4)+16*x(4)^2+12-4*x(1)-x(2)-78*x(4);
16*x(1)*x(4)+44-19*x(1)-8*x(2)-x(3)-24*x(4)];
end
The matrix form of the linear inequalities can be written as Ax  b, where
11.4 · Attempting to Global Optimum Solutions
337 11
⎡ ⎤ ⎡ ⎤
−1 0 0 0 −0.25 −2.25
⎢ 1 0 0 0 −0.25 ⎥ ⎢ 2.25 ⎥
⎢ ⎥ ⎢ ⎥
⎢ 0 −1 −0.5 ⎥ ⎢ ⎥

A=⎢
0 0 ⎥ , b = ⎢ −1.5 ⎥ .
⎢ 0 1 0 0 −0.5 ⎥

⎢ 1.5 ⎥
⎢ ⎥
⎣ 0 0 −1 0 −1.5 ⎦ ⎣ −1.5 ⎦
0 0 1 0 −1.5 1.5

There are no linear equation constraints, and there are no upper and lower bounds.
Therefore, the constraints can be expressed as empty matrices. If structured variable is
used to describe the optimization problem, it is not necessary to express these constraints.
For simplicity, a structured variable is used in this example. Random initial value is selected
to find an optimum solution. The solution found is x = [1.9638, 0.9276, −0.2172, 0.0695,
1.1448], and the identifier flag is 1, indicating that the solution process is successful.

>> clear P; P.objective=@(x)x(5);


P.nonlcon=@c11mnls; P.solver='fmincon'; % structured variable description
P.Aineq=[-1,0,0,0,-0.25; 1,0,0,0,-0.25;
0,-1,0,0,-0.5; 0,1,0,0,-0.5;
0,0,-1,0,-1.5; 0,0,1,0,-1.5];
P.Bineq=[-2.25; 2.25; -1.5; 1.5; -1.5; 1.5];
P.options=optimset;
P.x0=rand(5,1); [x,f0,flag]=fmincon(P) % solve the problem
Normally, the last row of commands can be executed repeatedly for several times, and
a better solution may be found, whose objective function is 0.8175. This at least indicates
that the solution obtained earlier is a local optimum solution. It can be seen that when there
is no other a priori knowledge regarding the global optimum solution, some random initial
values can be tried, and they may lead to global optimum solutions. 

11.4 Attempting to Global Optimum Solutions


There are significant limitations in classical optimization solvers. It is quite com-
mon that the global optimum solution cannot be found. A Global Optimization
Toolbox is provided in MATLAB, where four commonly used intelligent solvers
are provided. The so-called intelligent solvers are those inspired by natural phenom-
ena. Good representatives are genetic algorithm solvers, particle swarm optimization
solvers, ant colony solvers and immunization solvers. The intelligent solvers provided
in the Global Optimization Toolbox are illustrated. Also two new global solvers will
be presented, and comparisons are made on the behaviors of the solvers.

11.4.1 Introduction to MATLAB Global Optimization Toolbox


In the MATLAB Global Optimization Toolbox, the genetic algorithm solver ga(),
particle swarm optimization solver particleswarm(), simulated annealing solver
simulannealbnd(), pattern search solver patternsearch() are provided. These
four solvers can all be used to solve the unconstrained optimization problems. Besides,
the genetic algorithm solver and pattern search solver claim to be able to solve con-
338 Chapter 11 · Optimization Problem Solutions

strained optimization problems. The genetic algorithm solver can also be used to solve
mixed integer programming problems.

1. Genetic Algorithm
A genetic algorithm based solver ga() has the syntaxes
[x,f0 ,flag,out]=ga(f ,n, A,B, Aeq ,B eq ,xm ,xM ,nfun,intcon)
[x,f0 ,flag,out]=ga(problem)
It is seen that the syntaxes are very close to the solver fmincon(). Also, the argu-
ment intcon solves mixed integer programming problems. The difference is that the
number of decision variables n should be provided, instead of the initial value vector
x 0 . The function also supports structured description, whose members are listed in
. Table 11.3.

2. Pattern Searching Algorithm


Pattern searching algorithm solver patternsearch() has the syntaxes
[x,f0 ,flag,out]=patternsearch(f ,x 0 , A,B, Aeq ,B eq ,x m ,x M ,nfun)
[x,f0 ,flag,out]=patternsearch(problem)
Different to the solver ga(), the patternsearch() function does not support the
member intcon, which means that the mixed integer programming problem cannot
be solved. Besides, the reference initial search vector x 0 is needed, rather than n. If
the problem is described by a structured variable problem, the objective member
rather than the fitnessfcn member is used to describe the objective function.

11 3. Particle Swarm Optimization Solver


The syntaxes of the particle swarm optimization solver particleswarm() are
[x,f0 ,flag,out]=particleswarm(f ,n,x m ,x M ,options)
[x,f0 ,flag,out]=particleswarm(problem)

. Table 11.3 Members of structured variables in ga() function

Members Descriptions

fitnessfcn the function handle for the fitness function, equivalent to the objective
functions in other optimization problems

nvars the number of decision variables n

options the default setting, can be set with optimset() or optimoptions()


functions

solver should be set to 'ga'. The above four members are essential

Aineq and so on this type of members also contain bineq, Aeq, beq, lb and ub; in addition, the
members nonlcon and intcon are supported. The definitions of these
members are the same as the ones used in other functions
11.4 · Attempting to Global Optimum Solutions
339 11
It can be seen that particleswarm() function only applies to solve unconstrained
optimization problems. If structured variable is used to describe the problem, the
members objective, nvars, lb and ub are used.

4. Simulated Annealing Solver


Simulated annealing solver simulannealbnd() call be called
[x,f0 ,flag,out]=simulannealbnd(f ,x 0 ,x m ,x M ,options)
[x,f0 ,flag,out]=simulannealbnd(problem)
It can be seen that the syntaxes of the function is close to particleswarm(), where
nvars member is not needed, while an initial search vector x 0 is used instead.

11.4.2 A New Global Unconstrained Optimization Solver


Similar to the ideas in the equation solution discussed earlier, the following algorithm
can be used to find the global optimum solution. At first, generate random initial
values in the predefined interval (a, b), then find an optimum solution x with ordinary
searching method. For another random initial search point, the objective function
value f1 = f (x) can be evaluated. If the new objective function is smaller than the
recorded one, record the new solution. The process is executed N times to solve the
problem, and it is likely to find the global optimum solution. Based on the ideas,
the following solver can be written in MATLAB for solving global optimization
problems.
function [x,f0]=fminunc_global(f,a,b,n,N,varargin)
arguments, f, a(:,1) double; b(:,1) double
n(1,1) {mustBeInteger, mustBePositive}
N(1,1) {mustBeInteger, mustBePositive}
end
arguments (Repeating) varargin, end
k0=0; f0=Inf;
if isstruct(f), k0=1; end % with structured variable
for i=1:N, x0=a+(b-a).*rand(n,1); % generate initial search point
if k0==1, f.x0=x0; [x1,f1,key]=fminunc(f); % structured
else, [x1,f1,key]=fminunc(f,x0,varargin{:}); end
if key>0 && f1<f0, x=x1; f0=f1; end % record better solution
end, end
The syntax of the solver is [x,f0 ]=fminunc_global(fun,a,b,n,N), where fun is
the function handle of the objective function, which can be an anonymous function or
an M-function. It can also be the structured variable for the optimization problem.
The arguments a and b are the allowed intervals of the decision variables; n is the
number of independent variables; N is the number of trials in the loop. If N is suitable,
it is likely that the returned arguments x and f0 are, respectively, the global optimum
solution and the value of the objective function. If necessary, a and b can be selected
as vectors.
It is worth mentioning that although a and b are specified, they are only the range
of random initial values. The final solution may exceed the range.
340 Chapter 11 · Optimization Problem Solutions

 Example 11.11
Consider a modified Rastrigin multi-peak function [1]
x 2  x 2  x  x 
1
f (x1 , x2 ) = 20 + − 1 + 2 − 1 − 10 cos 2π 1 − 1 + cos 2π 2 − 1 ,
30 20 30 20

where, −100  x1 , x2  100. The solver fminsearch_global() is compared with the four
solvers in the Global Optimization Toolbox. Each solver is executed 100 times. Observe
what is the success rate for each solver to find the global optimum solution, and assess the
time elapse.
Solutions The following commands can be executed, such that each solver is executed 100
times, so that the success rate can be measured. The detailed comparisons are provided
in . Table 11.4. When measuring time elapse, execute one solver only for 100 times, by
commenting off the remaining solvers.
>> f=@(x)20+(x(1)/30-1)^2+(x(2)/20-1)^2-...
10*(cos(2*pi*(x(1)/30-1))+cos(2*pi*(x(2)/20-1))); % objective function
A=[]; B=[]; Aeq=[]; Beq=[]; xm=-100*ones(2,1); xM=-xm; F=[]; tic
for i=1:100, x0=100*rand(2,1); % execute the solvers 100 times
[x,f0]=ga(f,2,A,B,Aeq,Beq,xm,xM); F=[F; x(:)',f0];
[x,f0]=patternsearch(f,x0,A,B,Aeq,Beq,xm,xM); F=[F; x(:)',f0];
[x,f0]=particleswarm(f,2,xm,xM); F=[F; x(:)',f0];
[x,f0]=simulannealbnd(f,x0,xm,xM); F=[F; x(:)',f0];
end, toc
r=nnz(F(:,3)<1e-5) % find the success rate, 1e-2 for simulannealbnd solver
f1=F(F(:,3)<1e-5,3); mean(f1) % average precision for each successful trail
11 It can be seen that the fastest one is the particle swarm optimization solver. The success
rate of the solver fminunc_global() is nearly the highest one, and precision is obviously
higher than other solvers. The time elapse is higher, but is usually acceptable, with average
of 0.49 s for each run. The success rate of the genetic algorithm solver is not very high, but
usually, 5∼6 runs may lead to the global optimum solution at least once. It is a meaningful
solver for this particular example. The pattern search solver and simulated annealing solver
depend upon the selections of the initial values. It is deliberately selected as random numbers
in the interval [-100,100], but the success rate is very low. Besides, the error bound of 1e-2 is
used in the assessment of the simulated annealing solver. If 1e-5 is used as in other solvers,
the success rate is zero, indicating that the precision is extremely low. The two solvers are
not very suitable for this problem. 

. Table 11.4 Success rate comparisons of various algorithms

Solvers ga() pattern- particle- simulanneal- fminunc_


search() swarm() bnd() global()

Success rate 21 5 89 23* 85

Time elapse 8.46 2.75 2.11 25.26 49.02

Average 3.2312 × 10−10 3.3404×10−9 1.8876×10−9 0.0026 7.3802 × 10−13


accuracy
11.4 · Attempting to Global Optimum Solutions
341 11

 Example 11.12
For the following Griewangk benchmark problem, with n = 50
⎛ ⎞
n
xi2 n
x
min ⎝1 + cos √ ⎠ , where, xi ∈ [−600, 600],
i

x 4000 i
i=1 i=1

compare different solvers.


Solutions It is obvious that the global minimum solution is xi = 0, with optimum objective
function of 0. The intelligent solvers and the solver fminunc_global() can be executed
each for 100 times, and the comparisons are provided in . Table 11.5. The conclusion is
different from the one in . Table 11.4, since the scale of the problem is larger, which leads
to the accuracy of the intelligent algorithms very low. Therefore, different error bounds 
are tried in the table.

>> n=50; f=@(x)1+sum(x.^2/4000)-prod(cos(x(:)./[1:n]'));


A=[]; B=[]; Aeq=[]; Beq=[]; xm=-600*ones(n,1); xM=-xm; F=[]; tic
for i=1:100, i, x0=600*rand(n,1); % execute each solvers 100 times
[x,f0]=ga(f,n,A,B,Aeq,Beq,xm,xM); F=[F; f0];
[x,f0]=patternsearch(f,x0,A,B,Aeq,Beq,xm,xM); F=[F; f0];
[x,f0]=particleswarm(f,n,xm,xM); F=[F; f0];
[x,f0]=simulannealbnd(f,x0,xm,xM); F=[F; f0];
[x,f0]=fminunc_global(f,-600,600,n,10); F=[F; f0];
end, toc
ee=1e-2; r=nnz(F<ee), f1=F(F<ee); mean(f1) % reduce slightly ee
It is obvious that the most reliable one is the fminunc_global() solver, where almost
100% times the global optimum solutions are found, and the accuracy is more than 1010
times higher than the rest ones. The execution time is also acceptable, with around 0.42 s
each. The genetic algorithm ranked second here, with 96% success rate when the error
bound is selected as 10−2 . The precision and speed of the solver is much lower. The best
one in the previous example, the particle swarm one, is with a success rate of only 18%,
and the accuracy is much lower. The pattern search solver has only 4% of success rate, and
cannot be used. While the simulated annealing solver is with a success rate of 0, the smallest
objective function value is 7.2352 in the 100 runs, which is far larger than the theoretical
value of 0.

. Table 11.5 Success rate comparisons of different solvers

Solvers ga() pattern- particle- simulanneal- fminunc_


search() swarm() bnd() global()

 = 10−4 56% 1% 10% 0% 100%

 = 10−3 95% 1% 10% 0% 100%

 = 10−2 96% 4% 18% 0% 100%

Average 2.4539 × 10−4 0.0074 0.0044 − 6.3109 × 10−12

Time elapse 481.78 319.38 42.11 2045.52 41.84


342 Chapter 11 · Optimization Problem Solutions

Even when n = 500, the solutions cannot be found by other intelligent solvers, the solver
fminunc_global() still works, and the value of the objective function is f0 = 1.1858 ×
10−11 , with a single execution time of 6.46 s.
>> n=500; f=@(x)1+sum(x.^2/4000)-prod(cos(x(:)./[1:n]'));
tic, [x,f0]=fminunc_global(f,-600,600,n,10), toc


11.4.3 A New Global Constrained Optimization Solver


Similar to the ideas in function fminunc_global(), a MATLAB solver can be writ-
ten to find global optimum solutions of nonlinear programming problems with con-
straints. The eventual target is to find global optimum solutions of nonlinear pro-
gramming problems.
function [x,f0,flag]=fmincon_global(f,a,b,n,N,varargin)
arguments, f, a(:,1) double; b(:,1) double
n(1,1) {mustBeInteger, mustBePositive}
N(1,1) {mustBeInteger, mustBePositive}
end
arguments (Repeating) varargin, end
x0=rand(n,1); k0=0;
if isstruct(f), k0=1; end % structured variable
if k0==1, f.x0=x0; [x,f0,flag]=fmincon(f); % direct solution
else, [x,f0,flag]=fmincon(f,x0,varargin{:}); end
11 if flag==0, f0=1e10; end
for i=1:N
x0=a+(b-a).*rand(n,1); % random initial points
if k0==1, f.x0=x0; [x1,f1,flag]=fmincon(f);
else, [x1,f1,flag]=fmincon(f,x0,varargin{:}); end
if flag>0 && f1<f0, x=x1; f0=f1; end % record better solution
end, end
The syntax is [x,f0 ]=fmincon_global(fun,a,b,n,N,other arguments), where fun can
be a structured variable, or the handle of the objective function; a and b are the allowed
range of the decision variables. If x m and x M are finite vectors, they can be used to
replace a and b; n is the number of decision variables; N is the number of calls to the
low-level fmincon() function. Normally, N = 5 ∼ 10 are sufficient. If fun is the
handle of the objective function, other arguments include the constraints, the specific
form and order is the same as in fmincon() function. That is, all the remaining
arguments in fmincon(), besides F and x 0 . The returned argument x is likely the
global optimum solution, while f0 is the value of the objective function.

 Example 11.13
A constrained optimization problem is studied in Example 11.10. Run the function
fmincon_ global() 100 times, and assess the success rate of finding global optimum solu-
tions with the new solver.
11.4 · Attempting to Global Optimum Solutions
343 11
Solutions Run the solver fmincon_global() 100 times, the total time elapse is 92.52 s, and
the success rate of finding global optimum solutions is 100%, with the average of precision
3.8540 × 10−10 , indicating that each time the same result is found.

>> clear P; P.objective=@(x)x(5); % define objective function


P.nonlcon=@c11mnls; P.solver='fmincon'; % structured variable description
P.Aineq=[-1,0,0,0,-0.25; 1,0,0,0,-0.25;
0,-1,0,0,-0.5; 0,1,0,0,-0.5;
0,0,-1,0,-1.5; 0,0,1,0,-1.5];
P.Bineq=[-2.25; 2.25; -1.5; 1.5; -1.5; 1.5];
P.options=optimset; P.x0=rand(5,1); F=[]; tic % structured variable P
for i=1:100 % call the solver fmincon_global() 100 times
[x,f0]=fmincon_global(P,-10,10,5,20); F=[F; x(:)' f0];
end, toc, std(F(:,6))


In the four solvers provided in the Global Optimization Toolbox, only the two
solvers, ga() and patternsearch(), claim to be capable of solving constrained opti-
mization problems. The two functions can be tried in an example and see whether
they are really able to solve constrained optimization problems.

 Example 11.14
Solve again the constrained optimization problem in Example 11.10, and see whether the
global optimum solutions can be found.
Solutions Now try to solve the problem with ga() function. It is executed 9 times, and the
total time elapse is 18.01 s. 9 different solutions are found and listed in . Table 11.6. It is a
pity that not a single time, the global optimum solution marked * is found. All the objective
function values are much larger than the global one, indicating that ga() function fails to
find the global optimum solution. If the patternsearch() solver is called 10 times to solve
the problem, the results obtained are even worse.

>> clear P; P.fitnessfcn=@(x)x(5);


P.nonlcon=@c11mnls; P.solver='ga'; P.nvars=5;
P.Aineq=[-1,0,0,0,-0.25; 1,0,0,0,-0.25; 0,-1,0,0,-0.5;
0,1,0,0,-0.5; 0,0,-1,0,-1.5; 0,0,1,0,-1.5];
P.Bineq=[-2.25; 2.25; -1.5; 1.5; -1.5; 1.5];
P.options=optimoptions('ga'); F=[]; tic
for i=1:9 % call the ga() solver 9 times, and record the result
[x,f0,flag]=ga(P); if flag==1, F=[F; x(:).' f0]; end
end, toc


In fact, many more comparative examples are provided in Reference [1]. In normal
cases, if the default format of the intelligent solvers is called, the global optimum
solutions cannot be found. Sometimes the solutions found are far away from the
global ones. The two dedicated global solvers provided in this section always yield
344 Chapter 11 · Optimization Problem Solutions

. Table 11.6 Call the ga() solver 9 times

Number x1 x2 x3 x4 x5 f (x )

1 1.7118 0.9806 11.9480 2.4541 12.5689 12.5689

2 0.0194 2.2527 10.48 0.63864 16.3616 16.3616

3 −2.0987 11.6811 −11.1412 0.0272 20.8280 20.8280

4 0.5110 5.5544 −0.6817 −0.5980 9.0191 9.0191

5 5.0060 1.1473 2.1174 1.1126 11.0331 11.0331

6 4.9042 1.4428 −1.4808 1.0877 10.736 10.736

7 0.7634 7.3772 3.9484 −2.8401 12.358 12.358

8 1.9921 2.7221 −6.1384 1.205 8.0358 8.0358

9 4.9178 1.3533 −0.3205 1.0962 12.2399 12.2399

* 2.4544 1.9088 2.7263 1.3510 0.8175 0.8175

11
the global optimum solutions, with much higher precision. Therefore, these solvers
are recommended in solving genuine problems.

11.5 Exercises
(1) Solve the unconstrained optimization problem.

100(x2 − x12 )2 + (1 − x1 )2 + 90(x4 − x32 )2 + (1 − x3 )2


min
x + 10.1 (x2 − 1)2 + (x4 − 1)2 + 19.8(x2 − 1)(x4 − 1).

(2) Find the global valley of the surface of the function


  
sin 0.1 + (x1 − 4)2 + (x2 − 9)2
f (x1 , x2 ) = − .
1 + (x1 − 4)2 + (x2 − 9)2

(3) Solve the Ackley benchmark problem [4].


11.5 · Exercises
345 11
⎡ ⎛  ⎞ " #⎤
1 1
p p
min ⎣20 + 10−20 exp ⎝−0.2! xi2 ⎠ − exp cos 2πxi ⎦ .
x p p
i=1 i=1

(4) Solve the Kursawe benchmark problem.


p
J = min |xi |0.8 + 5 sin3 xi + 3.5828,
x
i=1

where, select p = 2 and p = 20, respectively.


(5) Solve the extended Freudenstein−Roth minimization problem for n = 20.


n/2
 2
f (x) = − 13 + x2i−1 + ((5 − x2i )x2i − 2)x2i
i=1
 2
+ − 29 + x2i−1 + ((x2i + 1)x2i − 14)x2i .

The initial point is x 0 = [0.5, −2, . . . , 0.5, −2]T , analytical solution is x ∗ =


[5, 4, . . . , 5, 4]T , with fopt = 0. If the searching range is increased, whether the
solvers can still find the global optimum solutions?
(6) Solve the minimization problem for the extended Rosenbrock function, n = 20.


n/2
 2
2
f (x) = 100 x2i − x2i−1 + (1 − x2i−1 )2 ,
i=1

with initial point x 0 = [−1.2, 1, . . . , −1.2, 1], analytical solution is xi = 1, with


fopt = 0. If x2i −x2i−1
2 is substituted to x2i −x2i−1
3 , it is converted to the extended
White−Holst problem. Find the solution of the problem.
(7) Solve the minimization problem for the extended Beale function, n = 20.


n/2
 2
f (x) = 1.5 − x2i−1 (1 − x2i )
i=1
 2 2 2
  
3 2 2
+ 2.25 − x2i−1 (1 − x2i ) + 2.625 − x2i−1 (1 − x2i ) ,

with initial value of x 0 = [1, 0.8, . . . , 1, 0.8]T . The analytical solution is


unknown.
(8) Find the solutions of the two Raydan problems, n = 20.


n
i  xi 
n
 x
f1 (x) = e − xi , f2 (x) = e i − xi .
10
i=1 i=1

1
n
Initial values x 0 = [1, 1, . . . , 1]T , and analytical solution xi = 0, f1opt = i,
10
i=1
f2opt = n.
346 Chapter 11 · Optimization Problem Solutions

(9) Find the global minimum solutions to the Schwefel function, when n = 20.


n $
f (x) = 418.9829n − xi sin |xi |.
i=1

The search interval is −500  xi  500, with analytical solution of xi =


420.9687, with fopt = 0. If n = 2, draw the surface of the objective function.
(10) Find the global minimum solution of the Eggholder function
% & & &
&x & &
f (x, y) = −(y + 47) sin & + (y + 47)& − x sin &x − (y + 47)&,
2

and draw the surface of the objective function.


(11) Solve the following linear programming problems.
(a) min
⎧ 10x1 − 57x2 + 9x3 − 24x4 , (b) max
⎧ v.

⎪ 0.5x1 −5.5x2 −2.5x3 +9x4 0 ⎪
⎪ −x2 +2x3 +v0

⎨ 0.5x −1.5x −0.5x +x 0 ⎪

1 2 3 4 ⎪
⎨ 3x1 −4x3 +v0
x s.t.

⎪ x1 1 x,v s.t. −5x1 +6x2 +v0

⎩ ⎪

x1 ,x2 ,x3 ,x4 0 ⎪ x1 +x2 +x3 =1



x1 ,x2 ,x3 0
(12) Solve the following linear programming problem.

max
⎧ −3x1 − x2 + x3 + 2x4 − x5 + x6 − x7 − 4x8 .

⎪ x1 +4x3 +x4 −5x5 −2x6 +3x7 −6x8 =7

⎨ x −3x −x +4x +x −2x +5x =−3
2 3 4 5 6 7 8
11 x s.t.




0x1 8, 0x2 6, 0x3 10, 0x4 15
0x5 2, 0x6 10, 0x7 4, 0x8 3

(13) Solve the following linear programming problem.

max
⎧ −22x1 + 5x2 − 7x3 − 10x4 + 8x5 + 8x6 − 9x7 .

⎪ 3x1 −2x3 −2x4 +3x7 4



⎪ 2x1 +3x2 +x3 +3x6 +x7 1



⎪ 2x1 +4x2 −4x3 +2x4 −3x5 +2x6 +2x7 2





⎪ 2x2 −2x3 −3x5 +2x6 +2x7 −4

⎨ x −2x −x +5x +x =2
2 3 4 6 7
x s.t.

⎪ 5x1 +x2 −x3 +x4 −5x6 −x7 −3



⎪ 5x1 −3x2 +x3 +2x4 +3x5 +2x6 +x7 =−2





⎪ x1 −2x2 +2x3 −3x4 +x5 +6x6 +4x7 3


⎪ 3x2 −5x3 −x4 +3x5 +3x6 +3x7 2



xi −5, i=1,2,...,7

(14) Solve the Finkbeiner−Kall quadratic programming problem [5].

1 2 1 2
min x + x + 3x1 + 7x2 + x4 .
⎧ 2 1 2 2
⎪ x
⎨ 1 +2x 2 +x3 =8
x s.t. x1 +2x2 +x4 =5


x1,2,3,4 0
11.5 · Exercises
347 11
(15) Use problem-based method to input the quadratic programming problem [6]
into MATLAB environment, then find the solution. Is the solution the global
optimum solution? If not, how to find the global optimum one?

1 T
min cT x + d T y − x Qx,
' 2
AXb, X=[x; y]
x s.t.
0X1

where
⎡ ⎤ ⎡ ⎤
−2 −6 −1 0 −3 −3 −2 −6 −2 −2 −4
⎢ 6 −5 8 −3 0 1 3 8 9 −3 ⎥ ⎢ 22 ⎥
⎢ ⎥ ⎢ ⎥
⎢ −5 6 5 3 8 −8 9 2 ⎥
0 −9 ⎥ ⎢ −6 ⎥
⎢ ⎢ ⎥
⎢ 9 5 0 −9 1 −8 3 −9 −9 −3 ⎥ ⎢ −23 ⎥
⎢ ⎥ ⎢ ⎥
⎢ −8 7 −4 −5 −9 1 −7 −1 3 −2 ⎥ ⎢ −12 ⎥
⎢ ⎥ ⎢ ⎥
A=⎢
⎢ −7 −5 −2 0 −6 −6 −7 −6 7 7⎥ ⎢ ⎥
⎥ , b = ⎢ −3 ⎥ ,
⎢ 1 −3 −3 −4 −1 0 −4 1 6 0⎥⎥ ⎢ ⎥
⎢ ⎢ 1⎥
⎢ 1 −2 6 9 0 −7 9 −9 −6 4⎥⎥ ⎢ ⎥
⎢ ⎢ 12 ⎥
⎢ −4 6 7 2 2 0 6 6 −7 4⎥⎥ ⎢ ⎥
⎢ ⎢ 15 ⎥
⎣ 1 1 1 1 1 1 1 1 1 1 ⎦ ⎣ 9⎦
−1 −1 −1 −1 −1 −1 −1 −1 −1 −1 −1

where, x has 7 elements, y has 3 elements, Q = 10I, and

d = [10, 10, 10]T , c = [−20, −80, −20, −50, −60, −90, 0]T .

(16) Solve the following optimization problem.

max
⎧ x + y.

⎨ y2x −8x +8x +2
4 3 2

x,y s.t. y4x4 −32x3 +88x2 −96x+36




0x3, 0y4

(17) Solve the following convex quadratic programming problem.

1 T
max cT x + dy + x Qx.
⎧ 2

⎨ 6x1 +3x2 +3x3 +2x4 +x5 6.5
x, y s.t. 10x1 +10x3 +y20


0xi 1, y>0

and cT = [−10.5, −7.5, −3.5, −2.5, −1.5], Q = I, d = 1.


348 Chapter 11 · Optimization Problem Solutions

(18) Solve the following nonlinear programming problem.


  
1 31.5
min x1 x2 (1 + x5 ) + x3 x4 1 + .
2 cos x6 x5


⎪ 0.003079x13 x23 x5 −cos3 x6 0

⎪ 0.1017x3 x3 −x2 cos3 x 0



⎪ 3 4 5 6
⎪ 0.09939(1+x )x3 x2 −cos2 x 0

⎨ 5 1 2 6
x s.t. 0.1076(31.5+x5 )x33 x42 −x52 cos2 x6 0



⎪ x3 x4 (x5 +31.5)−x5 [2(x1 +5) cos x6 +x1 x2 x5 ]0



⎪ 0.2x1 0.5,14x2 22,0.35x3 0.6



16x4 22,5.8x5 6.5,0.14x6 0.2618

(19) Solve the following nonlinear programming problem [6].

min
⎧ k,

⎪ a4 (q)w4 −a2 (q)w2 +a0 (q)=0



⎪ a 3 (q)w −a1 (q)=0
2


⎨ 10−kq 10+k
1
q,w,k s.t.
⎪ 1−0.1kq2 ,q3 1+0.1k




⎪ 0.2−0.01kq4 0.2+0.01k



0.05−0.005kq5 0.05+0.005k

where
a4 (q) = q32 q2 (4q2 + 7q1 ),
a3 (q) = 7q4 q32 q2 − 64.918q32 q2 ,
11 a2 (q) = 3(264.896q3 q2 −9.81q3 q22 −9.81q3 q1 q2 −4.312q32 q2 )+3(q4 q4 −9.274q5 ),
a1 (q) = (−147.15q4 q3 q2 + 1364.67q3 q2 − 27.72q5 )/5,
a0 (q) = 54.387q3 q2 .
(20) Solve the following optimization problem [6].

(a) min

x10.6 + x20.6 + x30.4 + 2u1 + 5u2 − 4x3 − u3 ,

⎪ x2 −3x 1 −3u1 =0



⎪ x3 −2x 2 −2u2 =0



⎪ 4u1 −u3 0


⎨ x +2u 4
1 1
x s.t.

⎪ x2 +u2 4



⎪ x3 +u3 6




⎪ x1 3, u2 2, x3 4


x1 ,x2 ,x3 ,u1 ,u2 ,u3 0

(b) min

x10.6 + x20.6 − 6x1 − 4u1 + 3u2 .

⎪ x2 −3x1 −3u1 =0



⎨ x1 +2u1 4
x s.t. x2 +2u2 4



⎪ x1 3, u2 1


x1 ,x2 ,u1 ,u2 0
11.5 · Exercises
349 11
(21) Solve the following nonlinear programming problem [6].

⎧min 37.293239x1 + 0.8356891x1 x5 + 5.3578547x32 − 40792.141.



⎪ −0.0022053x 3 x5 +0.0056858x2 x5 +0.0006262x1 x4 −6.6655930



⎪ 0.0022053x x 5 −0.0056858x2 x5 −0.0006262x1 x4 −85.3344070


3


⎨ 0.0071317x2 x5 +0.0021813x3 +0.0029955x1 x2 −29.487510
2

x s.t. −0.0071317x2 x5 −0.0021813x32 −0.0029955x1 x2 +9.487510




⎪ 0.0047026x3 x5 +0.0019085x3 x4 +0.0012547x1 x3 −15.6990390




⎪ −0.0047026x3 x5 −0.0019085x3 x4 −0.0012547x1 x3 +10.6990390



78x1 102, 33x2 45, 27x3 ,x4 ,x5 45

(22) Find the global optimum solution of the following nonlinear programming
problem [7].

5x5 6x6
max

5x1 + e−2x2 − e−x2 + x1 x3 + 4x3 + 6x4 + + .
⎪ x1 +x2 +x3 +x4 +x5 +x6 10 x5 + 1 x6 + 1




⎨ x1 +x3 +x4 5
x s.t. x1 −x22 +x3 +x5 +x62 5



⎪ x2 +2x4 +x5 +0.8x6 =5

⎩ 2 2 2
x3 +x5 +x6 =5

(23) Solve the following nonlinear programming problem [8], where the objective
function is

f (x) = l(x1 x2 + x3 x4 + x5 x6 + x7 x8 + x9 x10 ),

with the constraints

6Pl 6P(2l)
2
− σmax  0, − σmax  0,
x9 x10 x7 x82

6P(3l) 6P(4l) 6P(5l)


− σmax  0, − σmax  0, − σmax  0,
x5 x62 x3 x42 x1 x22
" #
Pl 3 244 148 76 28 4
+ + + + − δmax  0,
E x1 x23 x3 x43 x5 x63 x7 x83 3
x9 x10
x2 x4 x6 x8 x10
− 20  0, − 20  0, − 20  0, − 20  0, − 20  0,
x1 x3 x5 x7 x9
where the upper and lower bounds of the decision variables are

1  x1,7,9  5, 30  x2,8,10  65, 2.4  x3,5  3.1, 45  x4,6  60,

where, l = 100, P = 50000, δmax = 2.7, σmax = 14000 and E = 2 × 107 .


350 Chapter 11 · Optimization Problem Solutions

(24) Solve the following nonlinear programming problems [9].


" #
10 
10
xj xk
(a) min e cj + xj + ln e ,
j=1 k=1
⎧ x

⎪ e 1 +2ex2 +2ex3 +ex6 +ex10 −2=0

⎨ ex4 +2ex5 +ex6 +ex7 −1=0
x s.t. x

⎪ e 3 +ex7 +ex8 +2ex9 +ex10 −1=0


−100xi 100, i=1,2,...,10


10  
xj
(b) min xj cj + ln ,
x1 + x2 + · · · + x10
j=1


⎪ x +x +x +2x6 +x10 −2=0
⎪ 2 2 3
⎨ x4 +2x5 +x6 +x7 −1=0
x s.t.
⎪ x3 +x7 +x8 +2x9 +x10 −1=0


⎩ −6
10 xi , i=1,2,...,10

where, c1 = −6.089, c2 = −17.164, c3 = −34.054, c4 = −5.914, c5 = −24.721,


c6 = −14.986, c7 = −24.100, c8 = −10.708, c9 = −26.662, c10 = −22.179.
(25) Solve the following optimization problem [6], where the objective function is
 0.6  0.6  0.6
Q1 Q2 Q3
min + + ,
U1 A1 U2 A2 U3 A3

with the following constraints


11
Q1 = C(T1 − Tm ), Q2 = C(T2 − T1 ), Q3 = C(TM − T2 ),

Q1 = C(t1 − t1 ), Q2 = C(t2 − t2 ), Q3 = C(t3 − t3 ),


(t1 − Tm ) − (t1 − T1 )
A1 =  ,
ln (t1 − Tm )/(t1 − T1 )
(t2 − T1 ) − (t2 − T2 )
A2 =  ,
ln (t2 − T1 )/(t2 − T2 )
(t3 − T2 ) − (t3 − TM )
A3 =  ,
ln (t3 − T2 )/(t3 − TM )
Tm  T1 , T2  TM , t1  t1 , t2  t2 , t3  t3 ,
with known constants Tm = 100, TM = 500, C = 105 , t1 = 300, t2 = 400,
t3 = 600, U1 = 120, U2 = 80, U3 = 40. Hints: the decision variables can be
chosen as T1 , T2 , t1 , t2 , t3 , Q1 , Q2 , Q3 .
(26) Use intelligent solvers to solve the above optimization problems, and see
whether the global optimum solutions can be found or not.
11.6 · Mini-Projects
351 11
(27) Use the two global optimization solvers in this book to solve the above problems
and see whether the global optimum solutions can be found. Also assess the
success rate and precision of the global optimization problem solvers.
(28) Assume that a differential equation is given
⎧ 

⎪ x (t) = x2 (t)
⎨ 1
x2 (t) = −x1 (t) − 3x2 (t) + e−5t

⎪ x3 (t) = x4 (t)


x4 (t) = 2x1 (t) − 4x2 (t) − 3x3 (t) − 4x4 (t) − sin t,

the boundary conditions x1 (0) = 1, x2 (0) = 2, x3 (10) = −0.021677, x4 (10) =


0.15797 are known. Convert the problem into an optimization problem, and find
the numerical solutions of the differential equation in the interval t ∈ (0, 10).

11.6 Mini-Projects

1. An Application Problem
The mathematical model and illustration shown in . Fig. 11.1 is proposed by Haverly
[10], where a and b are the two channels of petrol flowing into the pool, c is the flow to
the splitter. The sulfur contents of the three input channels are, respectively, 3%, 2%
and 1%. After the blending process, the flows of the two output channels are, respec-
tively, x and y, with sulfur contents of 2.5% and 1.5%, respectively; the variables px ,
py , cx and cy are the flows in the figure. Based on the given conditions, considering the
price information, the following mathematical model can be established to maximize
the profit:
max 9x + 15y − 6a − c1 b − 10(cx + cy ) (11.5)


⎪ px +py −a−b=0



⎪ x−px −cx =0



⎪ y−py −cy =0


⎨ pp +2c −2.5x0
x x
v s.t.

⎪ ppy +2cy −1.5y0



⎪ pp x +ppy −3a−b=0





⎪ 0xc 2 , 0y200

0a,b,cx ,cy ,p,px ,py 500

where, the decision variables are selected as v = [x, y, a, b, cx , cy , p, px , py ]T , with c1


and c2 the known quantities.
Consider the above optimization model, let c1 = 13 and c2 = 600, which is the
third plan in Reference [10], find the solutions of the problem.

2. Mixed Integer Linear Programming Problem


Integer programming problems are those whose decision variables must be integers.
If some of the decision variables are required to be integers, the problem is referred
to as mixed integer programming problems. This topic has not been presented in this
book, but it is a very important topic in optimization applications. For instance, if
the physical meaning of a certain decision variable is the number of persons, it must
be integers.
352 Chapter 11 · Optimization Problem Solutions

pool mixer 1

splitter mixer 2

. Fig. 11.1 Pooling and blending illustration

A mixed integer linear programming solver, intlinprog(), is provided in MAT-


LAB. Find the relevant online help information of the function and revisit Example
11.3. If all the decision variables are required to be integers, what is the solution of
the integer programming problem? If only x3 and x4 are required to be integers, what
is the solution of the mixed integer programming problem?

References
1. Xue DY (2020) Solving optimization problems with MATLAB[M]. De Gruyter, Berlin
2. Nelder JA, Mead R (1965) A simplex method for function minimization[J]. Comput J 7(4):308−313
3. Henrion D (2006) A review of the global optimization toolbox for Maple[R/OL]. 7 https://homepages.
laas.fr/henrion/Papers/mapleglobopt.pdf
4. Ackley DH (1987) A connectionist machine for genetic hillclimbing. Kluwer Academic Publishers,
Boston, USA

11 5. Bazaraa MS, Sherali HD, Shetty CM (2006) Nonlinear programming−Theory and algorithms[M], 3rd
edn. Wiley-interscience, New Jersey
6. Floudas CA, Pardalos PM (1990) A collection of test problems for constrained global optimization
algorithms[M]. Springer-Verlag, Berlin
7. Bhatti MA (2000) Practical optimization methods with Mathematica applications[M]. Springer-
Verlag, New York
8. Chakri A, Ragueb H, Yang X-S (2018) Bat algorithm and directional bat algorithm with case stud-
ies[M]. In: Yang X-S (ed) Nature-inspired algorithms and applied optimization. Springer, Switzerland,
pp 189−216
9. Hock W, Schittkowski K (1990) Test examples for nonlinear programming code[M]. Springer-Verlag,
Berlin
10. Floudas CA, Pardalos PM, Adjiman CS et al (1999) Handbook of test problems in local and global
optimization[M]. Kluwer Scientific Publishers, Dordrecht
353 12

Data Processing
and Statistics
Contents

12.1 Data Interpolations – 354


12.1.1 One-Dimensional Interpolation – 354
12.1.2 Two- and Multidimensional Interpolations – 355
12.1.3 Spline Interpolations – 357
12.1.4 Spline-Based Numerical Calculus – 360

12.2 Fitting Mathematical Models from Data – 361


12.2.1 Polynomial Fitting – 362
12.2.2 Least Squares Curve Fitting – 363
12.2.3 Neural Network-Based Data Fitting – 364

12.3 Statistical Analysis – 367


12.3.1 Probability Density and Distribution Functions – 367
12.3.2 Pseudorandom Number Generation – 369
12.3.3 Mean and Variance – 370
12.3.4 Outlier Detections – 371

12.4 Hypothesis Tests and Variance Analysis – 375


12.4.1 Hypothesis Test – 375
12.4.2 Variance Analysis – 378

12.5 Exercises – 381

12.6 A Mini-Project – 383


References – 384

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_12
354 Chapter 12 · Data Processing and Statistics

In scientific research and engineering, data are often acquired. The data can be ana-
lyzed to explore further certain rules. Data interpolation and function approximation
are the often encountered problems. The measured data can be used as samples. The
so-called interpolation means that the function values at unknown points can be com-
puted based on the given samples. In 7 Sect. 12.1, one-, two- and multidimensional
interpolation problems are presented first, then a spline-based interpolation method
is illustrated, and based on it, numerical differentiation and integral problems are also
addressed. In 7 Sect. 12.2, sample points are used to acquire the mathematical mod-
els, such as polynomial fitting, least squares curve fitting and artificial neural network
approximations. In 7 Sect. 12.3, pseudorandom number-based statistical experimen-
tation methods are presented. Box plot representation and outlier detection methods
are also demonstrated. In 7 Sect. 12.4, statistical analysis methods are presented. The
statistical quantities such as mean and variance are computed. Hypothesis tests and
variance analysis methods are also illustrated.

12.1 Data Interpolations


Data interpolation means that from a set of samples, evaluate the function values at
unknown points. In this section, one-, two- and multidimensional data interpolation
problems are presented. Interpolation-based numerical differentiations and integrals
are also explored.

12.1.1 One-Dimensional Interpolation


Assume that f (x) is a one-dimensional function, but the function is unknown, for a
set of m distinct independent variable values x1 , x2 , . . ., xm , the function values y1 , y2 ,
12 . . ., ym are known. The known data (x1 , y1 ), (x2 , y2 ), . . ., (xm , ym ) are also referred
to as samples. The method to evaluate the function values at unknown points from
the given samples is referred to as data interpolation. If the unknown points are
within the range of samples, the interpolation is referred to as interior interpolation,
otherwise it is called extrapolation. If the problem is understood in the time domain,
the interpolation beyond xm is also known as forecasting.
The function y1 =interp1(x, y,x 1 ,'spline') solves one-dimensional interpo-
lation problems, where x = [x1 , x2 , . . . , xm ]T and y = [y1 , y2 , . . . , ym ]T vectors store
the samples of independent variables and function values. Variable x 1 is a set of val-
ues for the independent variables to be interpolated, which can be a scalar, a vector
or even a matrix. The returned y1 is the interpolation results at the points in x 1 . The
'spline' option is the recommended one, representing cubic spline interpolation
algorithm. Besides, other options such as 'linear', 'nearest' and 'pchip' can
be used, but 'spline' is considered the best choice.

 Example 12.1
Assume that the samples are generated from the function f (x) = (x2 − 3x + 5)e−5x sin x.
Generate a set of samples, and take interpolation such that smooth interpolation curve
12.1 · Data Interpolations
355 12
can be found. Compare the result with the original function, and assess interpolation algo-
rithms.
Solutions The samples are generated directly from the given function, and in the two vectors
x and y. Based on the two vectors, interpolation can be carried out. The options 'pchip'
and 'spline' are demonstrated here, while the others are poor. The comparison of the
interpolation results and that of the theoretical values are shown in . Fig. 12.1. It can be
seen that the two methods yield smooth interpolation result, but the option 'pchip' yields
rather large errors, and 'spline' provides much better interpolation results.

>> x=0:0.1:1; y=(x.^2-3*x+5).*exp(-5*x).*sin(x); % generate samples


x0=0:0.02:1; y0=(x0.^2-3*x0+5).*exp(-5*x0).*sin(x0); % theoretical values
y1=interp1(x,y,x0,'pchip'); y2=interp1(x,y,x0,'spline');
plot(x0,y0,x,y,'o',x0,y1,'--',x0,y2,':') % comparisons of the algorithms


12.1.2 Two- and Multidimensional Interpolations


There are two kinds of problems in 2D interpolation. One is the samples on the
mesh grid points are provided, and the other, the samples are given as scattered data.
The two types of interpolation problems are discussed in this section, and then an
introduction is made on multidimensional interpolation problems.

1. Mesh Grid Data Interpolation


MATLAB function interp2() can be used in 2D interpolation. If the samples are
provided in the mesh grid matrices x 0 , y0 and z 0 , and the interpolation points are
specified in x 1 and y1 , the interpolation result z 1 can be found with z 1 =interp2(x 0 ,
y0 ,z 0 ,x 1 , y1 ,'spline'). Although other algorithms are supported in the function,
the interpolation quality is not recommended.

0.35

0.3

0.25

0.2

0.15

0.1

0.05

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

. Fig. 12.1 Interpolation result comparisons


356 Chapter 12 · Data Processing and Statistics

 Example 12.2
For the given 2D function z = f (x, y) = (x2 − 2x)e−x −y −xy , compute a set of sparsely
2 2

distributed samples in mesh grids. Based on the samples, the interpolation surface can be
obtained with various algorithms. Compare the fitting qualities.
Solutions Consider the given 2D function, the following commands generate the samples in
mesh grids. Another set of interpolation points in mesh grid can be generated, with smaller
increments. Interpolation can be obtained with the following commands, and compare the
result with the theoretical ones. The interpolation error can be obtained, which are almost
the same as the one in . Fig. 5.21. With the following commands, the errors in the surface
can be drawn, as shown in . Fig. 12.2.

>> [x,y]=meshgrid(-3:.6:3, -2:.4:2); % generate sparsely distributed samples


z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y);
[x1,y1]=meshgrid(-3:.1:3, -2:.1:2); % densely distributed interpolation points
z1=interp2(x,y,z,x1,y1,'spline'); % 2D interpolation evaluations
z0=(x1.^2-2*x1).*exp(-x1.^2-y1.^2-x1.*y1); % compute theoretical values
surf(x1,y1,abs(z1-z0)) % draw the surface of the errors


2. Scattered Data Interpolation


In real applications, most of the problems are based on the (xi , yi , zi ) scattered data,
therefore the function interp2() cannot be used to carry out 2D interpolation.
A more general function griddata() in MATLAB performs scattered data inter-
polation, with the syntax z=griddata(x 0 , y0 ,z 0 ,x, y,'v4'), where x 0 , y0 and z 0 are
the samples in vectors. It is not necessary to have them in mesh grid form. They can be
arbitrarily distributed. The vectors x and y are the expected interpolation points. The
obtained z vector is the same dimensions of the arrays x and y. It is the interpolation
12 result. The option 'v4' is the interpolation algorithm provided in MATLAB 4.0,
which is regarded as a good interpolation method. The option 'v4' is used to repre-
sent such an algorithm. Apart from the 'v4' option, the options such as 'linear',
'cubic' and 'nearest' can be used, while the quality may be much poorer than
the 'v4' option.

. Fig. 12.2 Surface of the errors


12.1 · Data Interpolations
357 12

 Example 12.3
Consider again the original function z = f (x, y) = (x2 − 2x)e−x −y −xy . Generate a set
2 2

of random samples (xi , yi ) in the rectangular regions x ∈ [−3, 3] and y ∈ [−2, 2], and
compute the function values zi . Based on the obtained data, generate interpolation result
with the function griddata(), and assess the fitting quality.
Solutions Generating a set of 200 random points with the following commands, such that the
vectors x, y and z are created. Since the samples are not in mesh grid form, it is not possible
to draw the 3D surface from the scattered data only. Densely distributed interpolation
points x 1 and y1 are generated, in mesh grid format, then function griddata() computes
interpolation results. The interpolated surface is almost the same as the one obtained in
. Fig. 5.21. Compared with the theoretical values, the error surface can be obtained as
shown in . Fig. 12.3.

>> x=-3+6*rand(200,1); y=-2+4*rand(200,1); % generate random samples


z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); % evaluate the function values
[x1,y1]=meshgrid(-3:0.1:3, -2:0.1:2); % generate interpolation points
z1=griddata(x,y,z,x1,y1,'v4'); % scatter interpolation
z0=(x1.^2-2*x1).*exp(-x1.^2-y1.^2-x1.*y1); % compute theoretical values
surf(x1,y1,abs(z1-z0)) % draw the error surfaces


3. Interpolation from Multidimensional Samples


Multidimensional interpolation problems can be computed directly with the solvers
interpn() and griddatan(). In the former one, mesh grid samples are required,
while the latter is used to process multidimensional scattered data interpolation prob-
lems.

12.1.3 Spline Interpolations


To improve the interpolation results, cubic spline and B spline classes are supported
in MATLAB. The following commands construct cubic and B spline objects:

. Fig. 12.3 Error surface from the scattered data interpolation


358 Chapter 12 · Data Processing and Statistics

S=csapi(x, y), % generates a cubic spline


S=spapi(k,x, y), % generates kth-order B spline object, where k can be 4 or 5
where x and y are the samples, S is the generated spline object. The interpolation
results of csapi() function are exactly the same as the interp1() function, since the
mathematical models are identical. Furthermore, for multidimensional problems, the
following syntaxes can be used to create the spline objects:
S=spapi({k1 ,k2 ,· · · ,kn },{x 1 ,x 2 ,· · · ,x n },z), % multivariate B spline
Four spline object manipulating functions are provided in MATLAB, as shown
in . Table 12.1. They are used to solve interpolation and numerical calculus prob-
lems directly for univariate and multivariate functions. Examples are used next to
demonstrate spline interpolation computing and plotting.

 Example 12.4
Consider the data and prototype function in Example 12.1. Compare the efficiencies of
different interpolation algorithms.
Solutions The input samples can be entered first, then the samples can be used to set up
directly the two spline objects. The interpolation curves can be found, together with the
exact curve. It can be seen that the interpolation results are very satisfactory in the two
spline objects.

>> x=0:0.12:1; y=(x.^2-3*x+5).*exp(-5*x).*sin(x); % make samples


syms x0; fplot((x0^2-3*x0+5)*exp(-5*x0)*sin(x0),[0,1]) % exact values
hold on; S1=csapi(x,y); S2=spapi(4,x,y); % the two spline objects
fnplt(S1), fnplt(S2); hold off % draw the interpolation results

12

. Table 12.1 Operations of spline objects

Operations Syntaxes and descriptions

Plotting fnplt(S) draws the plot for the spline object S. For univariate problems,
curves can be drawn, while for multivariate ones, surfaces are drawn

Interpolation y = fnval(S, x) computes interpolation values, which is similar to the


interp1()or interp2() function

Differentiation S1 = fnder(S, n) computes the nth-order derivative from the given object S.
The result is also a spline object S1 . For multivariate problems, partial
derivatives can be found by replacing n with a vector [k1 , k2 , . . . ]

Integral S1 = fnint(S) computes the integral S1 of the object S. It is applicable to


univariate object only. For multivariate ones, function fnder() should be
used instead, with negative orders
12.1 · Data Interpolations
359 12

 Example 12.5
Consider an example with sparsely distributed samples. Assume that the sinusoidal function
values at x = 0, 0.4, 1, 2, π are known, carry out data interpolation with these five samples,
and assess the interpolation precisions.
Solutions The five points can be input into MATLAB workspace, then set up the spline
objects from the samples, and carry out spline interpolations. Compared with theoretical
ones, the maximum error can be assessed, as shown in . Table 12.2. It can be seen that
the cubic spline result is exactly the same with the interp1() function. The interpolation
results using B splines are better than cubic splines. For this particular example, the fifth-
order B spline yields the most accurate results, where the sinusoidal function is almost
completely restored.

>> x=[0,0.4,1,2,pi]; y=sin(x); % generate sparsely distributed samples


x0=linspace(0,pi,30); y0=sin(x0); % theoretical result
y1=interp1(x,y,x0,'spline'); max(abs(y1-y0))
S=spapi(4,x,y); y2=fnval(S,x0); max(abs(y2-y0))


2D and multidimensional interpolation problems can also be solved directly with


functions such as csapi(). The conditions to use such function are rather tough,
since only mesh grid data generated by ndgrid() function can be used, which is
different from the ones in the meshgrid() function. Only mesh grid data can be
used in interpolation. An example is used next to demonstrate 2D interpolation and
interpolation surface plotting method.

 Example 12.6
Solve the 2D interpolation problem in Example 12.2 using splines.
Solutions The scaling points for x- and y-axes can be generated first in a and b vectors. Then
function ndgrid() is used to generate the samples. With the samples, the two spline objects
are constructed. Function spapi() allows the user to select independently the orders for the
two axes. When the splines are created, function fnplt() draws the interpolation surface.
For this particular example, the interpolation results are satisfactory.

>> a=-3:0.6:3; b=-2:0.4:2; [x,y]=ndgrid(a,b); % generate mesh grids


z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); % compute function values
S1=csapi({a,b},z); S2=spapi({4,4},{a,b},z); % construct splines
fnplt(S2) % draw interpolation surface directly


. Table 12.2 Comparison of different solvers

Interpolation interp1() cubic 3rd order B 4th order B 5th order B 6th order B

Maximum error 0.0363 0.0363 0.0466 0.0309 0.0012 0.0012


360 Chapter 12 · Data Processing and Statistics

12.1.4 Spline-Based Numerical Calculus


From the given samples, functions fnder() and fnint() can be used directly to
evaluate numerical differentiations and integrals. Note that fnint() function evalu-
ates the primitive function, but it cannot be used to solve multiple numerical integral
problems. The solver fnder() can be used instead, with negative orders.
It is seen in theory that, for a cubic spline object, the first-order derivative is a piece-
wise quadratic function, further derivative is a piecewise linear function. Therefore
cubic spline object is not suitable for computing high-order derivatives. For integral
problems, the integral of a cubic spline is also a cubic spline, thus it is not suitable
either for finding numerical integrals as well. Cubic splines are not recommended in
solving numerical calculus problems. On the contrary, high-order B spline objects can
be used to solve numerical calculus problems. Examples are given next to demonstrate
numerical derivatives and integrals.

 Example 12.7
Find the third-order derivative for the problem in Example 7.37 with spline interpolation
methods.
Solutions Numerical differentiation with spline interpolation method is different from the
ones in 7 Chap. 7. With the traditional numerical calculus methods, the values at the sample
points are obtained, and with B spline interpolation, the numerical derivative at any point
within the region can be found. For this particular problem, the order of the B spline can
be selected as n + 3, such that high-order B spline object can be obtained. The numerical
derivative curve is almost the same as the theoretical one, and cannot be distinguished in
the figure window. With the B spline interpolation method, the seventh-order numerical
derivatives failed in Example 7.37 can be solved successfully. The B spline interpolation
result is shown in . Fig. 12.4. Apart from the two terminal points in the interval, the fitting
is successful in the other points.
12
>> syms x; f(x)=log(1+x)/2-log(x^2-x+1)/4+atan((2*x-1)/sqrt(3))/sqrt(3);
h=0.02; x0=1.5:h:3.5; y0=double(f(x0)); % generate samples
n=3; f1=diff(f,n); S=spapi(n+3,x0,y0); S1=fnder(S,n)
fplot(f1,[1.5,3.5]), hold on, fnplt(S1), hold off


 Example 12.8
Draw the integral surface with interpolation method.
 1  2
e−x /2 sin(x2 + y)dxdy.
2
J=
−1 −2

Solutions The B spline object can be created first. Function fnder() carries out −1st-order
derivatives with respect to x and y. The integral function can be obtained, and the integral
surface can be found as shown in . Fig. 12.5. It can be seen that the integral function can
also be found, while with the method in 7 Chap. 7, the integral function cannot be found.
The method in 7 Chap. 7 only yields the value of the definite integral.
12.2 · Fitting Mathematical Models from Data
361 12

-10

-20

-30

-40

-50

-60

-70
1.5 2 2.5 3 3.5

. Fig. 12.4 Theoretical value of seventh-order derivative and B spline

. Fig. 12.5 Integral surface of spline interpolation

>> x0=-2:0.1:2; y0=-1:0.1:1; [x y]=ndgrid(x0,y0); % generate samples


z=exp(-x.^2/2).*sin(x.^2+y); S=spapi({5,5},{x0,y0},z); % B spline
S1=fnder(S,[-1 -1]); S2=fnval(S1,{x0,y0}); surf(y0,x0,S2)


12.2 Fitting Mathematical Models from Data


In the previous section, data interpolation methods are introduced. The function
values at interested points can be found by interpolation methods. In this section,
concentrations are made on function fitting from the given data. The polynomial
fitting method is introduced first, followed by the least squares fitting of functions
with prototype forms. Artificial neural network fitting is finally demonstrated. In fact,
the cubic and B spline objects obtained are also the mathematical models for the data.
362 Chapter 12 · Data Processing and Statistics

12.2.1 Polynomial Fitting


In 7 Chap. 7, Taylor series expansions of functions are presented, where the poly-
nomial approximation to given functions is demonstrated. If the samples are known,
polynomial fitting can also be made upon the samples, such that the polynomial
coefficients can be found. The MATLAB function polyfit() finds the polynomial
coefficients directly with c=polyfit(x, y,n), where x and y are sample vectors, n is
the expected degree of the polynomial, and the vector c returns the coefficient vector
of the polynomial in the descending order of s.

 Example 12.9
Fit the samples in Example 12.1 with polynomials of different degrees, and assess the fitting
quality.
Solutions The samples can be generated first, and different degrees are tried in polynomial
fitting. The fitting behaviors of polynomials of degree 3 and degree 6 can be found as shown
in . Fig. 12.6. It can be seen that the cubic polynomial fitting is rather poor. The polynomial
of degree 6 approaches the original function satisfactorily. Besides, the maximum error in
fitting of polynomials of different degrees is measured, as shown in . Table 12.3. It is seen
that the polynomial of degree 6 is good enough. There is no need to increase the degrees,
otherwise side effects may be introduced.

>> x=0:0.1:1; y=(x.^2-3*x+5).*exp(-5*x).*sin(x); % generate samples


x0=0:0.02:1; y0=(x0.^2-3*x0+5).*exp(-5*x0).*sin(x0); % theoretical values
n=3; c1=polyfit(x,y,n); y1=polyval(c1,x0); max(abs(y0-y1))
n=6; c2=polyfit(x,y,n); y2=polyval(c2,x0); max(abs(y0-y1))
plot(x0,y0,x,y,'o',x0,y1,'--',x0,y2,':') % compare different degrees

12

0.35
theoretical and polynomial of degree 6
0.3
polynomial of degree 3
0.25

0.2

0.15

0.1

0.05

–0.05
0 0.2 0.4 0.6 0.8 1

. Fig. 12.6 Polynomial fitting comparisons


12.2 · Fitting Mathematical Models from Data
363 12

. Table 12.3 Polynomial fitting results

Degrees 3 4 5 6 7 8 9

Maximum error 0.0769 0.0323 0.0104 0.0029 7.131×10−4 1.658×10−4 3.726×10−5

12.2.2 Least Squares Curve Fitting


If the prototype function ŷ(x) = f (a, x) is known, where a is the vector of unde-
termined coefficients, the target of least squares curve fitting is to determine the
undetermined coefficients. The following optimization problem is established:
m
 m

J = min [yi − ŷ(xi )]2 = min [yi − f (a, xi )]2 . (12.1)
a a
i=1 i=1

Function lsqcurvefit() provided in MATLAB Optimization Toolbox solves


the least squares fitting problems, with the syntax
[a,Jm ]=lsqcurvefit(Fun,a0 ,x, y,am ,aM ,options),
where Fun is the MATLAB representation of the prototype function, which can be
an M-function or an anonymous function; a0 is the initial vector for optimization;
vectors x and y are used to store the original input and output data; the vectors am
and aM are the allowed bounds for the parameter vector a. If there are no boundary
vectors, empty matrices can be used. The argument options is the control template
for optimization problems, as in other optimization problem solvers.

 Example 12.10
Consider again the problem in Example 12.1. If the prototype function is f (x) = (a1 x2 −
a2 x + a3 )e−a4 x sin x, but the parameters ai ’s are unknown, find the undetermined coeffi-
cients with the least squares method.
Solutions Generate the samples, and use anonymous function to describe the proto-
type functions, then call the solver. The undetermined coefficient vector is found as
a = [1, 3, 5, 5], and the error may reach 10−13 level.

>> x=0:0.1:1; y=(x.^2-3*x+5).*exp(-5*x).*sin(x);


f=@(a,x)(a(1)*x.^2-a(2)*x+a(3)).*exp(-a(4)*x).*sin(x);
ff=optimset; ff.TolX=eps; ff.TolFun=eps;
a0=rand(1,4); a=lsqcurvefit(f,a0,x,y,[],[],ff)
Under certain initial values, a warning message “Solver stopped prematurely” may be
displayed, such that incorrect results are found. If the commands are executed from another
random vector again, correct results may be found. 

If the prototype function has several independent variables, z = f (a, x1 , x2 ,


. . . , xm ), function lsqcurvefit() can still be used to find the undetermined coef-
ficients a, where a = [a1 , a2 , . . . , an ]. Prototype function should be specified first,
then call lsqcurvefit() function to find the undetermined coefficient vector a. An
364 Chapter 12 · Data Processing and Statistics

example is given next to demonstrate the fitting of multivariate functions using least
squares methods. Please pay attention to the format in the anonymous functions.

 Example 12.11
For the prototype function v = a1 xa2 x + a3 ya4 (x+y) + a5 za6 (x+y+z) , if a set of samples
are provided in a text file c12data1.dat, whose first three columns are the independent
variables x, y and z, the fourth column is the function values. Use least squares method to
find the undetermined coefficients ai .
Solutions To solve this type of problem, a vector x for the independent variables is needed.
For instance, let x1 = x, x2 = y and x3 = z, the original function can be rewritten as
a x a (x +x ) a (x +x +x )
v = a1 x12 1 +a3 x24 1 2 +a5 x36 1 2 3 . Since the data file is in a text form, command
load() reads the data into MATLAB workspace. Submatrix extraction methods to find
the input matrix X and the output vector v. The following commands can be used to find
the undetermined coefficients a = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]. In fact, the data in the file
was generated under the same set of parameters. Therefore the undetermined coefficients
can be accurately determined with the commands.

>> f=@(a,X)a(1)*X(:,1).^(a(2)*X(:,1))+... % prototype function


a(3)*X(:,2).^(a(4)*(X(:,1)+X(:,2)))+... % pay attention to the format
a(5)*X(:,3).^(a(6)*(X(:,1)+X(:,2)+X(:,3)));
XX=load('c12data1.dat'); X=XX(:,1:3); v=XX(:,4); % read in the samples
a0=[2 3 2 1 2 3]; a=lsqcurvefit(f,a0,X,v) % least squares fitting


12.2.3 Neural Network-Based Data Fitting

12 Artificial neural networks are developed upon the basis of the research and under-
standing of complicated biological neural networks. Human brain is composed of
about 1011 highly interconnected units, referred to as neurons. Each neuron has
about 104 connections [1]. To simulate biological neurons, mathematical expressions
are used to describe neurons, and the concept of artificial neurons are introduced.
Various neural networks can be constructed by the interconnections of neurons. With
the restriction of the current stage of computer development, it is not possible that
artificial neural networks are as complicated as human brains. In this section, funda-
mental concepts of artificial neurons and neural networks are presented first. Then
an introduction is illustrated on the applications of neural networks on data fitting.
The mathematical expression of a single neuron is illustrated in . Fig. 12.7, where
x1 , x2 , . . . , xn is a set of input signals. With the weights wi , the weighted sum of them
can be found, plus the threshold of b, the signal u can be found. It can be regarded
as the linear combination of the input signals. The signal can be fed into the transfer
function f (·), such that the output y of the neuron is generated. It can be seen that
the parameters of an artificial neuron are weights, threshold and transfer function.
The term artificial is omitted in the book.
If many neurons are interconnected in certain patterns, a neural network model
can be constructed. For instance, an m-layer network can be defined in this way. In
12.2 · Fitting Mathematical Models from Data
365 12

. Fig. 12.7 Basic structure of an artificial neuron

the ith layer, there are hi neurons. A prototype model of a neural network can be
established.
If the user does not want to learn too much on the internal structures and essential
knowledge of neural networks, but just wants to use neural network to solve certain
problems, neural network can be simply regarded as an information processing unit.
It accepts p channels of input signals, and has q channels of output signals. The neural
networks have their own internal parameters, for instance, the weights in each neuron.
The internal parameters in the neural network model can be obtained by the training
process from the sample data X 0 and Y 0 . After training, the neural network is tuned
for ready use. For instance, for the neural networks used for data fitting, the neural
network can be regarded as a device or a mathematical model. The new data X can
be fed into the neural network model, and the output signal Y can be regarded as the
interpolations of X. The following procedures are used to set up and utilize neural
network models in data fitting:
(1) Create a neural network. For data fitting problems, the command net=fitnet
([h1 ,h2 ,. . .,hm ]) can be used to construct a blank neural network model net. Nor-
mally select m = 1 or 2.
(2) Train the net. With command net=train(net,X 0 ,Y 0 ), the trained neural
network can be obtained. For multivariate problems, X 0 and Y 0 can be matrices of
many rows, representing the input and output matrices of the samples.
(3) Generalization. If the neural network object is net, the command Y =net(X)
gets the output of the neural network, which is similar to the interpolation result. Or
the command Y =sim(net,X) can be used in the interpolation computing.
If there is a set of samples, it can be divided randomly into two groups, one is
used in training and the other for validation. It is worth mentioning that the values of
the internal parameters do not have any physical interpretation. The trained values
should be used, but the weights cannot be adjusted or fine-tuned manually, otherwise
the adjusted neural network may be useless.
In fact, the application of neural network in one-dimensional data fitting has been
demonstrated in Example 1.8. In this section, the neural network fitting of 2D surfaces
is demonstrated through examples.

 Example 12.12
Consider the scattered data interpolation problem in Example 12.3. Use neural network to
interpolate the surface of the function.
366 Chapter 12 · Data Processing and Statistics

Solutions Although neural networks can be used to fit data, the reasonable selections of
hidden layer numbers and number of nodes in each layer are not simple things. Repeated
trial and errors should be made to get reasonable parameters. If the numbers selected are too
small, the fitting error may be large; if they are selected too large, over-fitting phenomena
may occur, that is, the fitting on the samples is extremely good, however, very large bias
occurs elsewhere. In this example, two hidden layers are selected, with node numbers of 20
and 10, respectively. The following commands create and train the neural network directly.
Please pay attention to the styles in the representations of the input data, which is a matrix
with two rows. The output signal is a row vector. The fitted surface from neural network
is obtained as shown in . Fig. 12.8. Compared with the interpolation methods discussed
earlier, the fitting quality of neural network is much worse.

>> x=-3+6*rand(1,200); y=-2+4*rand(1,200); % random samples


z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); % compute function values
[x1,y1]=meshgrid(-3:0.1:3, -2:0.1:2); % interpolation points in mesh grids
net=fitnet([20,10]); net=train(net,[x; y],z); % create & train neural network
z1=net([x1(:).'; y1(:).']); z1=reshape(z1,size(x1));
surf(x1,y1,z1) % draw surface


Radial basis neural network is also supported in MATLAB. The command net=
newrbe(X 0 ,Y 0 ) creates and trains the neural network. Normally the fitting quality
is better than the neural network discussed earlier.

 Example 12.13
Use the radial basis neural network to solve the scattered data interpolation problem in
Example 12.3.
12 Solutions With function newrbe(), the radial function neural network can be created and
trained. The interpolated surface can be found as shown in . Fig. 12.9. It can be seen that
the result is better than the neural network with fitnet() function, but it is worse than
the interpolation result obtained earlier.

. Fig. 12.8 Fitted surface with the neural network


12.3 · Statistical Analysis
367 12

. Fig. 12.9 Surface obtained by radial basis network

>> x=-3+6*rand(1,150); y=-2+4*rand(1,150); % generate random samples


z=(x.^2-2*x).*exp(-x.^2-y.^2-x.*y); % compute function values
[x1,y1]=meshgrid(-3:0.1:3, -2:0.1:2); % generate mesh grids
net=newrbe([x; y],z); % create and train neural network
z1=net([x1(:)'; y1(:)']); z1=reshape(z1,size(x1)); surf(x1,y1,z1)


12.3 Statistical Analysis


In this section, pseudorandom number generating methods and statistical analysis
methods are presented. The definitions and computing of mean and variance are
presented. Finally the concept and detection methods of outliers are presented.

12.3.1 Probability Density and Distribution Functions


The probability density function (PDF) of a continuous stochastic variable is denoted
as p(x), satisfying
 ∞
p(x)  0, and p(x)dx = 1. (12.2)
−∞
The cumulative distribution function (CDF) is defined upon the PDF as
 x
F (x) = p(t)dt. (12.3)
−∞

The physical interpretation of the function F (x) is the probability of the stochastic
variable ξ satisfying ξ  x. The function is a monotonic nondecreasing function, and

0  F (x)  1, with F (−∞) = 0, F (∞) = 1. (12.4)


368 Chapter 12 · Data Processing and Statistics

If the CDF value is fi = F (xi ), and the value of xi is needed, various tables are
provided in statistics textbooks, and lookup table methods can be used to find the
value xi . Since the CDF function is a nondecreasing one, the suitable value of xi can
be found. The problem is referred to as the inverse distribution problem.
Various analysis functions are provided in MATLAB to carry out different anal-
ysis, for different distributions. The commonly used keywords and corresponding
parameters are shown in . Table 12.4. Based on these functions, the CDFs, PDFs

. Table 12.4 Keywords of different distributions

Keywords Distribution names Parameters

beta Beta distribution a, b

bino Binomial distribution n, p

chi2 χ 2 distribution k

ev Extreme value distribution μ, σ

exp Exponential distribution λ

f F-distribution p, q

gam Gamma distribution a, λ

geo Geometrical distribution p

hyge Hypergeometric distribution m, p, n

Normal logarithmic distribution μ, σ


12
logn

mvn Multivariate normal distribution μ, σ

nbin Negative binomial distribution ν1 , ν2 , δ

ncf Nonzero F-distribution k, δ

nct Nonzero t-distribution k, δ

ncx2 Nonzero χ 2 distribution k, δ

norm Normal distribution μ, σ

poiss Poisson distribution λ

rayl Rayleigh distribution b

t t-distribution k

unif Uniform distribution a, b

wbl Weibull distribution a, b


12.3 · Statistical Analysis
369 12
and inverse CDFs can be evaluated. If the horizontal x vector is generated, the follow-
ing commands can be used to draw the curves of PDF for the specified distribution:
y=pdf(keyword,x,p1 ,p2 ,· · · ,pk ), plot(x, y)
Similar to the above commands, the CDF and inverse CDF can also be evaluated
with the following commands:
y1 =cdf(keyword,x,p1 ,p2 ,· · · ,pk )
y2 =icdf(keyword,x,p1 ,p2 ,· · · ,pk )

 Example 12.14
If b = 1, draw the PDF curve of Rayleigh distribution.
Solutions The keyword for Rayleigh distribution is rayl, with parameter b = 1. Generate
a horizontal vector in the interval [0, 4], the pdf() function evaluates PDF values, and
draws its curve, as shown in . Fig. 12.10.

>> x=0:0.01:4; b=1; y=pdf('rayl',x,b); plot(x,y)




It can be seen from the example that with such a method, the PDF or CDF curve
of any commonly used distribution can be drawn directly.

12.3.2 Pseudorandom Number Generation


A great amount of pseudorandom number generating functions are provided in MAT-
LAB, with the keywords in . Table 12.4. The pseudorandom numbers satisfying a
particular distribution can be generated easily, with the following syntax:
X=random(keyword,p1 ,p2 ,· · · ,pk ,n,m)
where n and m are the row and column numbers of the matrices.

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
0 0.5 1 1.5 2 2.5 3 3.5 4

. Fig. 12.10 Probability density function of Rayleigh distribution


370 Chapter 12 · Data Processing and Statistics

 Example 12.15
Generate a 10000×5 pseudorandom matrix, whose elements satisfy Rayleigh distribution
when b = 1.
Solutions It is found from . Table 12.4 that the keyword for Rayleigh distribution is
'rayl', therefore the following commands generate directly the expected pseudorandom
numbers.

>> b=1; X=random('rayl',b,10000,5); % generate the expected random matrix




The characteristics of pseudorandom number is the word pseudo, meaning that


the random numbers are generated with mathematical formulas, from the given seeds.
The random numbers generated satisfy the expected statistical distributions. The seeds
for the random number generators can be controlled, such that repeated pseudoran-
dom numbers can be generated, so as to carry out repeatable experiments. Command
s =rng extracts current seeds and other parameters, where s is a structured variable.
The next time the random numbers are generated, the rng(s) command sets the seeds,
so that the same set of random numbers can be generated, for repeatable experiment.

 Example 12.16
In normal cases, if the commands in Example 12.15 are executed twice, the two pseu-
dorandom matrices generated are completely different. Control the seeds in the random
number generator, such that the identical random matrices can be generated, with the same
commands.
Solutions Before generating the first random matrix, the seeds can be extracted first. Then
before generating the second random matrix, the same seeds can be used, such that the
identical random matrix is generated.
12
>> s=rng; b=1; X1=random('rayl',b,10000,5); % generate random matrix
rng(s); X2=random('rayl',b,10000,5); norm(X1-X2) % the error is 0


12.3.3 Mean and Variance


Assume that the samples are stored in a vector x = [x1 , x2 , x3 , . . . , xn ]T , the following
formulas compute their mean μ, variance σ 2 and standard deviation s:

n n  n
1  1  1  
μ= xi , σ 2 = (xi − μ)2 , s =  (xi − μ)2 . (12.5)
n n n−1
i=1 i=1 i=1

MATLAB functions mean(), var() and std() evaluate the mean, variance
and standard deviation directly. The syntaxes of the functions are μ=mean(x),
s2 =var(x) and s=std(x). The three functions can also be used to handle matrix
x. The explanation is that, for each column in matrix x, the mean, variance and stan-
dard deviation are computed. Therefore vectors are returned. For instance, to find the
12.3 · Statistical Analysis
371 12
mean value of all the samples in the matrix or multidimensional array X, the simplest
command is μ=mean(x(:)), where x(:) command expands all the elements in x
into a column vector.
Another important statistical quantity is the median value. If the vectors are sorted
as x1  x2  · · ·  xn , and if n is odd, the median is defined as x(n+1)/2 , while if n
is even, the median is defined as (xn/2−1 + xn/2+1 )/2. The median value can also be
evaluated directly with m=median(x).
Consider a set of normally distributed data in the interval (−5, 5), if there are
some values located far away, for instance, located at around 30, they are referred to
as outliers. Outliers will be presented later. Due to the existence of these values, the
mean values may be significantly affected by the outliers, which may lead to wrong
conclusions. Median values may be less affected by the outliers.

 Example 12.17
Generate a set of 30000 normally distributed pseudorandom numbers, whose mean is 0.5
and standard deviation is 1.5. Compute from the data the sample mean, variance, standard
deviation and median value. If the number of points is reduced, what will happen?
Solutions Generate the pseudorandom numbers with the following commands, the sample
mean value is 0.4879, with variance of 2.2748, standard deviation of 1.5083 and median
value of 0.5066. It is seen that the mean and standard deviation are rather close to their
theoretical values, indicating that the quality of the pseudorandom numbers generated are
satisfactory.

>> p=random('norm',0.5,1.5,30000,1); % generate normal random numbers


mean(p), var(p), std(p), median(p) % compute the statistical quantities
If the number of pseudorandom numbers is reduced to 300, the mean value is changed
to 0.4745, with variance of 1.9118 and standard deviation of 1.3827. It is seen that the
differences between the values and theoretical ones are too large. Therefore when using
statistical methods to carry out accurate analysis, the number of random numbers should
not be selected too small.

>> p=random('norm',0.5,1.5,300,1); mean(p), var(p), std(p)




12.3.4 Outlier Detections


Outliers are the observations located outside the main body of the distribution [2].
Outliers can be detected by the means of direct observation, histograms or the maps
describing distributions. In the real problems in multivariate cases, the outlier detec-
tion methods are in particular useful in statistical analysis since graphical methods
cannot be well used.
The median in the vector v is introduced earlier, denoted as q2 . Two sub-vectors
can be created from the median, with the sub-vector with smaller values is denoted
as v 1 and the other one denoted as v 2 . The medians of the two sub-vectors can then
be found and denoted, respectively, as q1 and q3 . Therefore vector q = [q1 , q2 , q3 ] is
referred to as the quartiles. More specifically, they are referred to as the first, second
and third quartiles. The command q=quantile(v,3) can be used to compute them
directly. The interquartile range (IQR), the distance between the first and the third
372 Chapter 12 · Data Processing and Statistics

quartiles, can also be defined, such that IQR = q3 − q1 . The point exceeds q3 by
1.5×IQR, or smaller than q1 by 1.5×IQR is referred to as an outlier.
The box plot of the data vector v can be drawn directly with boxplot(v) com-
mand. When calling the boxplot() function, if v is a matrix of m columns, m such
box plots are drawn simultaneously. An example is given next for demonstrations.

 Example 12.18
Assume that the life time of a batch of 200 luminescent lamps is provided in . Table 12.5
[3]. It can be seen that the data are distributed sparsely over the interval (500, 1500). Draw
the box plot and compute the quartiles and outliers.
Solutions The data in the table are stored in the data file c12dlamp.dat. The data can be
loaded into MATLAB workspace first, then function boxplot() can be called to draw the
box plot, as shown in . Fig. 12.11. In the box plot, there are three horizontal lines in the
box, indicating the quartiles q = [904.75, 996, 1106]. Besides, there are some cross signs,
indicating the outliers. With the zooming facilities in MATLAB, it is found that the values
are, respectively, 1425, 521 and 529. Besides, the two other horizontal lines are, respectively,
q3 + 1.5 × IQR and q1 − 1.5 × IQR.

. Table 12.5 The life time of 200 luminescent lamps

1067 919 1196 785 1126 936 918 1156 920 948 855 1092 1162 1170

929 950 905 972 1035 1045 1157 1195 1195 1340 1122 938 970 1237

956 1102 1022 978 832 1009 1157 1151 1009 765 958 902 923 1333

811 1217 1085 896 958 1311 1037 702 521 933 928 1153 946 858

12 1071 1069 830 1063 930 807 954 1063 1002 909 1077 1021 1062 1157

999 932 1035 944 1049 940 1122 1115 833 1320 901 1324 818 1250

1203 1078 890 1303 1011 1102 996 780 900 1106 704 621 854 1178

1138 951 1187 1067 1118 1037 958 760 1101 949 992 966 824 653

980 935 878 934 910 1058 730 980 844 814 1103 1000 788 1143

935 1069 1170 1067 1037 1151 863 990 1035 1112 931 970 932 904

1026 1147 883 867 990 1258 1192 922 1150 1091 1039 1083 1040 1289

699 1083 880 1029 658 912 1023 984 856 924 801 1122 1292 1116

880 1173 1134 932 938 1078 1180 1106 1184 954 824 529 998 996

1133 765 775 1105 1081 1171 705 1425 610 916 1001 895 709 610

916 1001 895 709 860 1110 1149 972 1002


12.3 · Statistical Analysis
373 12

outlier
1400
3 +1.5× IQR
1300
1200
3
1100
1000 2

900 1

800
700
600 1 − 1.5× IQR

two outliers
500
1

. Fig. 12.11 Box plots with quantiles and outliers labeled

>> A=load('c12dlamp.dat'); boxplot(A) % draw box plot


q=quantile(A,3) % compute quartiles


The third-party MATLAB function outliers() [4] extracts the outliers in the vec-
tor v, with the syntax [v 1 ,v 2 ]=outliers(v,opts,α). The IQR method and Grubbs
algorithm can be used to find the outliers, where opts can be selected, respectively,
as 'grubbs' or 'quartile'. In the former one, the significant level α can also be
assigned. In the latter syntax, the default value can be set to α = 1.5. The returned
vector v 2 contains only the outliers, while v 1 vector contains the remaining entities.
There is a bug in the original source code, and it is fixed in the one provided in the
toolbox of this book.

 Example 12.19
Consider the data in Example 12.18. Find the outliers with Grubbs algorithm.
Solutions The following commands detect the outliers v 2 = [521, 529]T , v 4 = [521,
529, 1425]T . In the latter case, the results are identical to the ones in . Fig. 12.11.

>> A=load('c12dlamp.dat'); % load data from file


[v1 v2]=outliers(A,'grubbs',0.05) % detect outliers with Grubbs algorithm
[v3 v4]=outliers(A,'quartile',1.5) % detect outliers with interquartile range


For multivariate problems, the third-party function moutlier1() [5] can be called
to find the outliers, with the command moutlier1(X,α), where X is the matrix with
m columns, and α is the significance level.

 Example 12.20
In . Table 12.6 [2], some data of 29 NBA teams are provided [2]. Find out the outliers for
the multivariate problem.
374 Chapter 12 · Data Processing and Statistics

. Table 12.6 Some data of the NBA teams

Team Team Venue Income Team no. Team Venue Income


no. value value value value

1 447 149 22.8 2 401 160 13.5

3 356 119 49 4 338 117 −17.7

5 328 109 2 6 290 97 25.6

7 284 102 23.5 8 283 105 18.5

9 282 109 21.5 10 280 94 10.1

11 278 82 15.2 12 275 102 −16.8

13 274 98 28.5 14 272 97 −85.1

15 258 72 3.8 16 249 96 10.6

17 244 94 −1.6 18 239 85 13.8

19 236 91 7.9 20 230 85 6.9

21 227 63 −19.7 22 218 75 7.9

23 216 80 21.9 24 208 72 15.9

25 202 78 −8.4 26 199 80 13.1

12 27 196 70 2.4 28 188 70 7.8

29 174 70 −15.1

Solutions The data in the table is provided in the file c12dteam.dat. They can be loaded
into MATLAB workspace. Then function moutlier1() is called, and it is indicated that
the data of the 14th team is the outlier.

>> X=load('c12dteam.dat'); % input the data


moutlier1(X,0.05) % find the outliers the for multivariate problem
The projections of different orthogonal planes such as xz and yz can be found, as shown
in . Fig. 12.12. The information of the 14th team is also superimposed. It is seen that the
above analysis is correct.
12.4 · Hypothesis Tests and Variance Analysis
375 12

. Fig. 12.12 The projections on the orthogonal planes

>> subplot(221), plot(X(:,1),X(:,2),'o',X(14,1),X(14,2),'x') % xy plane


subplot(222), plot(X(:,1),X(:,3),'o',X(14,1),X(14,3),'x') % xz plane
subplot(223), plot(X(:,2),X(:,3),'o',X(14,2),X(14,3),'x') % yz plane
subplot(224) % divide the window in different regions for the plots
plot3(X(:,1),X(:,2),X(:,3),'o',X(14,1),X(14,2),X(14,3),'x') % 3D plot


12.4 Hypothesis Tests and Variance Analysis


With the data measured, useful and meaningful conclusions may be extracted from
them. In this section, statistical methods such as hypothesis test and analysis of vari-
ance are presented. Concentrations are made on MATLAB to carry out statistical
analysis, such that meaningful results can be achieved.

12.4.1 Hypothesis Test


Assume first that there is a certain statistical specification for the observations. Then
pose a hypothesis, and check whether the hypothesis can be accepted or rejected. The
method is referred to as hypothesis test method. Hypothesis test is a very important
method in statistics. For instance, if someone poses a hypothesis that the average life
time of a batch of bulbs is over 3000 h, how to check whether such a hypothesis is
correct or not? The deterministic and most reliable way is to turn on all the bulbs
until they are all burn out. Unfortunately this method is meaningless. In statistics,
some samples can be chosen randomly to carry out hypothesis test. Hypothesis tests
of two types of problems are presented in this section.
376 Chapter 12 · Data Processing and Statistics

1. Significance Tests
Assume that a specification of a product is μ0 . To test whether the assumption (the
term hypothesis is used later) is correct or not, n samples can be selected randomly
from the product, and find the mean value x̄ and standard deviation s of the samples.
A hypothesis can be proposed in mathematics such that H0 : μ = μ0 , which implies
that the mean value of the product is μ0 . The following procedures can be used to
check whether the hypothesis can be accepted: √
n(x̄ − μ0 )
(1) Construct the statistical quantity u = . It is known that u satisfies
s
a standard normal distribution N(0, 1).
(2) Specify the significance level. Since statistical hypothesis test is not a determin-
istic test, there are possibilities of errors whether or not the hypothesis is accepted.
The meaning of α is that it is the possibility where the hypothesis is wrongly accepted.
Since random numbers are involved in the test, we should not expect that α = 0. Nor-
mally the values such that α = 0.05 or α = 0.02 can be adopted, indicating verbally
“having 95% or 98% of confidence to accept or reject a hypothesis”.
(3) With α value, inverse normal distribution function can be used to find the value
K , such that
 K 1
√ e−x /2 dx < 1 − α,
2
(12.6)
−K 2π
which can be obtained with the command K =norminv(1−α/2) or K =icdf('norm'
,1 − α/2,0,1).
(4) Make a decision: If |u| < K , then the hypothesis H0 cannot be rejected. Oth-
erwise, there are (1 − α) × 100 percent of confidence to reject the hypothesis H0 .

12  Example 12.21
It is known that the average strength of a product is μ0 = 9.94 kg. Now the manufacturing
technique is changed. If 200 products are selected randomly in the newly produced product,
it is found that the mean value is x̄ = 9.73 kg, with standard deviation of s = 1.62 kg. Whether
the new technique has significant impact on the product’s strength, if the new technique is
adopted [6]?
Solutions A hypothesis can be made first, H0 : μ = 9.94 kg, which implies that there is
no significant impact on the strength of the product, if the new technique is adopted. To
solve the hypothesis test problem, the following procedures and MATLAB commands are
issued:

>> n=200; mu0=9.94; xbar=9.73; s=1.62; % the given information


u=sqrt(n)*(mu0-xbar)/s % compute the quantity u
alpha=0.02; K=norminv(1-alpha/2), H=abs(u)<K % hypothesis test
The intermediate results are u = 1.8332 and K = 2.3263. More importantly, H = 1, which
implies that |u| < K . Therefore, the hypothesis H0 cannot be rejected. In other words, the
new technique has no significant impact on the strength of the product. 
12.4 · Hypothesis Tests and Variance Analysis
377 12
2. Test Whether Two Sets of Data have Significant Differences
Select randomly two groups of samples from the two sets of data, the numbers are,
respectively, n1 and n2 . The mean values are computed as x̄1 and x̄2 , with standard
deviations of s1 and s2 , respectively. Now make up a hypothesis that H0 : μ1 = μ2 ,
implying that the two sets of data have no significant differences. The following
procedures carry out the hypothesis test:
x̄1 − x̄2
(1) Construct a statistical quantity t =  , satisfying t-distribution.
s12 /n1 + s22 /n2
(2) Select a significance level α, and compute T =tinv(α/2,k) or T =icdf('t',
α/2,k), where k = min(n1 − 1, n2 − 1).
(3) Make a decision: If |t| < |T |, the hypothesis H0 cannot be rejected, otherwise
there is (1−α)×100 percent of confidence to reject the hypothesis.

 Example 12.22
Randomly divide the patients suffering insomnia into two groups, A and B, with 10 patients
each. Each group uses different medicine for a certain duration. The hours extended in
sleep are measured to all the subjects, as shown in . Table 12.7. A hypothesis test should
be carried out to check whether the two medicines have significant differences in curing
insomnia.
Solutions The hypothesis H0 : μ1 = μ2 can be made first. The hypothesis states that the
mean values of the two sets of data are the same, implying that there are no significant
differences in the drug effect. Following the above procedures in the hypothesis test, the
following MATLAB commands can be issued:

>> x=[1.9,0.8,1.1,0.1,-0.1,4.4,5.5,1.6,4.6,3.4];
y=[0.7,-1.6,-0.2,-1.2,-0.1,3.4,3.7,0.8,0,2]; % input the samples
n1=length(x); n2=length(y); k=min(n1-1,n2-1); % find the DOF
t=(mean(x)-mean(y))/sqrt(std(x)^2/n1+std(y)^2/n2) % compute t
a=0.05; T=tinv(a/2,k), H=abs(t)<abs(T) % hypothesis test
It is found that t = 1.8608, k = 9 and T = −2.2622. Since H = 1, the hypothesis cannot
be rejected. In other words, there is no significant differences in the drug effect.
Since the two sets of data are known, the box plot can be drawn, as shown in . Fig. 12.13.
It can be seen that there are overlapped portions in the two boxes, therefore the above
conclusion is correct.

>> boxplot([x(:) y(:)]) % draw the box plots of the two vectors


. Table 12.7 Extended sleeping time in hours

A 1.9 0.8 1.1 0.1 −0.1 4.4 5.5 1.6 4.6 3.4

B 0.7 −1.6 −0.2 −1.2 −0.1 3.4 3.7 0.8 0 2


378 Chapter 12 · Data Processing and Statistics

-1

1 2

. Fig. 12.13 Box plots of the two sets of data

12.4.2 Variance Analysis


Analysis of variance (ANOVA) is a statistical analysis method proposed by British
statistician Ronald Fischer [7]. It is widely used in the fields such as medical science,
experimental science, quality control and so on. ANOVA technique is an extension to
the hypothesis test discussed earlier. Assume that there are N groups of samples, and
it is assumed that the mean values of these samples are the same. That is to propose
the following hypothesis:

H0 : μ1 = μ2 = · · · = μN . (12.7)

Since the impact of the factors on the samples are different, ANOVA are usually
12 classified into one-way ANOVA, two-way ANOVA and n-way ANOVA. Various
ANOVA problems are processed with MATLAB as follows:

1. One-Way ANOVA
One-way ANOVA means that for certain observations, there is only one external
factor affecting the values of the observations. Assume that there are N types of
medicine used for a certain disease. The patients are divided randomly into N groups,
with m patients each. The curling performance indexes, for instance, the curling days,
are recorded as xi,j , where the subscripts j indicates the jth group, j = 1, 2, . . . , m,
while i indicates the ith patient in the group, i = 1, 2, . . . , N. A matrix X can be
constructed with the measured data.
With the anova1() function, [p,tab,stats]=anova1(X), the ANOVA table
tab and the box plots are obtained. The most important parameter is p, also known
as the statistical p value. If one does not want to learn too much information on
ANOVA, but only wants to use ANOVA to solve certain problems, the quantity of
p is sufficient. If p < α, where 1 − α is the confidence level, the hypothesis H0 should
be rejected. Otherwise, it should not be rejected. An example is presented next to
demonstrate the use of the one-way ANOVA method.
12.4 · Hypothesis Tests and Variance Analysis
379 12

 Example 12.23
There are 5 medicines used in treating a certain disease, and the effects are to be assessed.
Assume that there are 30 patients, divided randomly into 5 groups, with 6 patients each.
One medicine is used to a group. The healing time is measured for each patient, as shown
in . Table 12.8. Whether the 5 medicines have significant impact on the healing time [8]?
Solutions Based on the table, matrix A can be constructed and input into MATLAB directly.
The mean values of each column can be evaluated. The following analysis results can be
found, where m = [7.5, 5, 4.3333, 5.1667, 6.1667], and the probability value p = 0.0136 is
found.

>> A=[5,4,6,7,9; 8,6,4,4,3; 7,6,4,6,5; 7,3,5,6,7;


10,5,4,3,7; 8,6,3,5,6];
m=mean(A), [p,tbl,stats]=anova1(A) % find means and ANOVA
Meanwhile anova1() function opens two windows automatically: the ANOVA table in
. Table 12.9 and the box plot in . Fig. 12.14 can be obtained accordingly. Since the
value of the probability is p = 0.0136 < α, where α = 0.02 or 0.05, the hypothesis should
be rejected. That is, significant differences are witnessed in the healing time. In fact, it is
seen from the box plot that the healing time of the third medicine is significantly less than
the first one. 

. Table 12.8 Healing time in days

Patient Medicine 1 Medicine 2 Medicine 3 Medicine 4 Medicine 5

1 5 4 6 7 9

2 8 6 4 4 3

3 7 6 4 6 5

4 7 3 5 6 7

5 10 5 4 3 7

6 8 6 3 5 6

. Table 12.9 The ANOVA table obtained

Sources Squared sums Degrees of Mean square F -value p-value


freedom values

Columns 36.4667 4 9.1167 3.896 0.0136

Errors 58.5 25 2.34

Total 94.9667 29
380 Chapter 12 · Data Processing and Statistics

10

3
1 2 3 4 5

. Fig. 12.14 Box plots

2. Two-Way ANOVA
If there are two factors affect certain phenomena, the concept of two-way ANOVA
should be introduced. Function anova2() provided in the Statistics Toolbox solves
two-way ANOVA problems. The syntax of the function is rather close to the function
anova1(): [ p,tab,stats]=anova2(X). An example is presented next to demon-
strate the use of the two-way ANOVA method.

 Example 12.24
To assess the differences in the growing status of three types of pines in four different
regions, five pines of each type are selected randomly in each region. The chest radii of
them are measured as shown in . Table 12.10. Check whether the type of pine and growth
12 region have impact on the growth of the pines [8].
Solutions To assess the impact of the two factors on the growth of the pines, two-way
ANOVA can be adopted. The data in the table can be loaded into MATLAB workspace,
and then function anova2() can be called to carry out ANOVA. The ANOVA result
obtained in . Table 12.11 is the same as the ones in Reference [8].

. Table 12.10 The chest radii of the pines

Pine species Regions

1 2 3 4

1 23 15 26 13 21 25 20 21 16 18 21 17 16 24 27 14 17 19 20 24

2 28 22 25 19 26 30 26 26 20 28 19 24 19 25 29 17 21 18 26 23

3 18 10 12 22 13 15 21 22 14 12 23 25 19 13 22 16 12 23 22 19
12.5 · Exercises
381 12

. Table 12.11 Two-way ANOVA table

Sources Squared sums Degrees of Mean squared F -value p-value


freedom error

Columns 355.6 2 177.8 9.6762 2.9466×10−4

Rows 49.65 3 16.55 0.9007 0.4478

Interaction 106.4 6 17.7333 0.9651 0.4588

Errors 882 48 18.375

Total 1393.6 59

>> B=[23,15,26,13,21,25,20,21,16,18,21,17,16,24,27,14,17,19,20,24;
28,22,25,19,26,30,26,26,20,28,19,24,19,25,29,17,21,18,26,23;
18,10,12,22,13,15,21,22,14,12,23,25,19,13,22,16,12,23,22,19];
[p,tab]=anova2(B',5); % two-way ANOVA, pay attention to the matrix
It is seen from the ANOVA table that the three probabilities in the last column are very
important, where p1 corresponds to the first factor, p2 corresponds to the second one, while
p3 corresponds to the interaction of the two factors. If a certain probability value is smaller
than the value of α, the factor has significant impact on the observations. It is seen from
the results that since the value of p1 is very small, the corresponding hypothesis should be
rejected, while the other two cannot be rejected. It can be seen that A factor, that is, the
tree species, has significant impact on observation, that is, the chest radii. 

12.5 Exercises
(1) Generate a set of sparsely distributed data from function y(t) = t2 e−5t sin t. Use
one-dimensional interpolation to the data to fit the curve. Use neural network
to fit the data as well, and compare the results with the theoretical ones.
(2) Generate a set of samples in the interval (0, 3) for the function y(t) = sin(10t2 +
3), and interpolate the samples with the data. Compare the results with the
theoretical ones.
1
e−x −y sin(xy2 +
2 4
(3) Generate mesh grid data from the function f (x, y) = 3
3x + y
x2 y), or a set of randomly distributed scattered data. Fit the surface with inter-
polation methods and neural network methods, and compare the surfaces with
the theoretical one.
(4) Assume that a set of data is given in . Table 12.12, use interpolation method to
draw the smooth curve in the interval x ∈ (−2, 4.9). Compare the advantages
of various interpolation methods.
(5) Assume that a set of measured data are provided in the file c12pdat.dat. Draw
the 3D surface from the data.
(6) Assume that the data is provided in the file c12pdat3.dat, where the first
through the third columns are the coordinates of x, y and z, while the fourth
382 Chapter 12 · Data Processing and Statistics

. Table 12.12 Data in Exercise (4)

xi −2 −1.7 −1.4 −1.1 −0.8 −0.5 −0.2 0.1 0.4 0.7 1 1.3

yi 0.1029 0.1174 0.1316 .1448 0.1566 0.1662 0.1733 0.1775 0.1785 0.1764 0.1711 0.1630

xi 1.6 1.9 2.2 2.5 2.8 3.1 3.4 3.7 4 4.3 4.6 4.9

yi 0.1526 0.1402 0.1266 0.1122 0.0977 0.0835 0.0702 0.0577 0.0469 0.0373 0.0291 0.0224

column is the measured function of V (x, y, z). Carry out 3D interpolation from
the samples.
√ √
1+x− x−1
(7) Consider the function f (x) = √ √ . Generate a set of samples
2+x+ x−1
at x = 3:0.4:8. Use cubic splines and B splines to fit the data, respectively.
Find the second-order derivatives from the data and compare the results of
theoretical ones.
(8) Consider again the data in Exercise (4). Use polynomial fitting to the data, and
find a suitable degree for the fitting polynomial, such that the data can be well
fitted.
1
(9) Assume that the data in Exercise (4) satisfy the function y(x) = √
2πσ
e−(x−μ) /2σ , which can be used as the prototype function. Use least squares
2 2

method to find the values μ and σ , and draw the fitting curve of the function.
Compare the curve with the samples.
(10) Generate a set of 30000 pseudorandom numbers satisfying normal distribution
of N(0.5, 1.42 ). Check the sample mean value and the standard deviation, and
12 see whether they fit well with the theoretical ones. Use histogram to draw the
probability density function to the data and see whether it agree well with the
theoretical ones. If the bin-width in the histogram is changed, what conclusion
can be obtained from the data. Are there any outliers in the samples?
(11) For the 20 patients suffering from insomnia, divided into two groups. Medicines
A and B are used, respectively, to the two groups, the extended sleeping hours
are measured, as shown in . Table 12.13. Check whether there are significant
differences in the two types of medicines.

. Table 12.13 Extended sleeping hours

A 1.9 0.8 1.1 0.1 −0.1 4.4 5.5 1.6 4.6 3.4

B 0.7 −1.6 −0.2 −1.2 −0.1 3.4 3.7 0.8 0 2

. Table 12.14 The samples of two random variables

A 10.42 10.48 7.98 8.52 12.16 9.74 10.78 10.18 8.73 8.88 10.89 8.1

B 12.94 12.68 11.01 11.68 10.57 9.36 13.18 11.38 12.39 12.28 12.03 10.8
12.6 · A Mini-Project
383 12
(12) Assume that the randomly selected samples of two stochastic variables A and B
are provided in . Table 12.14. Check whether they have significant differences.
(13) For the cloths made by the same materials, processed by different dyeing tech-
niques, the washing shrinkage is measured as shown in . Table 12.15, which
is composed of five different dyeing techniques, and four piece of cloths each.
Check whether or not the dyeing technique impacts significantly the washing
shrinkage of the cloths.
(14) The heights of pupils of Grade 5 in three schools are measured randomly as
shown in . Table 12.16. Are there any significant differences in the heights of
pupils in the three schools? (Note that α = 0.05).
(15) In . Table 12.17, the daily output of three operators on four different machines
is recorded. Test whether there are significant differences on the (1) operators?
(2) machines? (3) The interactions of operator and machines? (Note that α =
0.05).

12.6 A Mini-Project
Principal component analysis (PCA) is an effective method in modern statistics. If a
phenomenon is affected at the same time by several factors, PCA method can be used
to recognize which factors are important and which are not, so that the less important
factors can be neglected to reduce the dimensions of the problems.
Assume that a phenomenon is affected by n factors, x1 , x2 , . . . , xn . There are m
sets of measured data, described by an m × n matrix X. The PCA method can be
carried out with the following procedures:
(1) From the measured matrix X, find its n × n covariance matrix R.
(2) Find the sorted eigenvalues λ1  λ2  · · ·  λn  0 of R, and the correspond-
ing normalized eigenvectors ei .
(3) Compute the contributions from each eigenvalues

. Table 12.15 Washing shrinkage of the cloths

Cloth Dyeing technique Cloth Dyeing techniques

1 4.3 6.1 6.5 9.3 9.5 2 7.8 7.3 8.3 8.7 8.8

3 3.2 4.2 8.6 7.2 11.4 4 6.5 4.2 8.2 10.1 7.8

. Table 12.16 The heights of the pupils

School The measured heights

1 128.1 134.1 133.1 138.9 140.8 127.4

2 150.3 147.9 136.8 126 150.7 155.8

3 140.6 143.1 144.5 143.7 148.5 146.4


384 Chapter 12 · Data Processing and Statistics

. Table 12.17 Operations records

Operators Operators

Machines 1 2 3 Machines 1 2 3

M1 15 15 17 19 19 16 16 18 21 M3 15 17 16 18 17 16 18 18 18

M2 17 17 17 15 15 15 19 22 22 M4 18 20 22 15 16 17 17 17 17

i
λi λk
γ i = n , δi = k=1
n . (12.8)
k=1 λk k=1 λk

where γi is the contribution rate of the ith eigenvalue, while δi is the contribution rate
of the first i eigenvalues. If the accumulated contributions from the first s eigenvalues
reach a predefined amount, for instance, 85−95%, the first s factors are the principal
components, such that the n-dimensional problem can be reduced to the s-dimensional
problem.
(4) Set up a new coordinate framework Z = X L, that is,


⎪ z1 = l11 x1 + l21 x2 + · · · + ln1 xn

⎨ z2 = l12 x1 + l22 x2 + · · · + ln2 xn
.. (12.9)

⎪ .


zn = l1n x1 + l2n x2 + · · · + lnn xn

where the coefficients in the ith column of the transformation matrix L, lji , can be
evaluated from lji = λi eji .
12 Write a MATLAB solver for implementing the PCA algorithm. Generate a set of
sample points from x = t cos 2t, y = t sin 2t, z = 0.2x + 0.6y [9], and carry out PCA,
so as to reduce the 3D problem into a 2D one, and assess the accuracies.

References
1. Hagan MT, Demuth HB, Beale MH (1995) Neural network design[M]. PWS Publishing Company,
Boston
2. Moore DS, McCabe GP, Craig BA (2007) Introduction to the practice of statistics[M], 6th edn. W H
Freeman and Company, New York
3. Ross MS (2009) Introduction to probability and statistics for engineers and scientists[M], 4th edn.
Elsevier Academic Press, Burlington
4. Battistini N. Outliers[R]. MATLAB Central File ID: #35048
5. Trujillo-Ortiz A. MOUTLIER1: Detection of outlier in multivariate samples test[R]. MATLAB Central
File ID: #12252
6. Mathematics Handbook Editorial Group (1979) Mathematics handbook (in Chinese)[M]. Peoples’
Education Publishers, Beijing
7. Fischer RA (1925) Statistical methods for research workers[M]. Oliver and Boyd, Edinburgh
8. Lu X (1999) Applied statistics (in Chinese)[M]. Tsinghua University Press, Beijing
9. Xue DY (2020) Linear algebra and matrix computations with MATLAB[M]. De Gruyter, Berlin
385 III

System Simulation
387 13

Modeling and Simulation


with Simulink
Contents

13.1 Simulink Interface – 389


13.1.1 Block Library and Blank Model Windows – 390
13.1.2 Simulink Toolbars – 391

13.2 Commonly Used Block Groups – 392


13.2.1 Input and Output Blocks – 392
13.2.2 Continuous and Discrete Blocks – 393
13.2.3 Computing Blocks – 395
13.2.4 Examples in Simulink Modeling and Simulation – 396

13.3 Simulink Parameters Settings – 399


13.3.1 Solver Settings – 400
13.3.2 Input and Output Parameter Settings – 401
13.3.3 Pre-processing of Model Parameters – 401

13.4 Modeling and Solutions of ODEs with Simulink – 403


13.4.1 Suggested Simulink Modeling Rules – 403
13.4.2 Low-Level Modeling Schemes – 404
13.4.3 Vectorized Modeling Approach – 405
13.4.4 Standard Framework for ODEs – 407
13.4.5 Modeling of ODE Sets – 409
13.4.6 Modeling of Implicit ODEs – 410
13.4.7 Modeling of Delay Differential Equations – 412

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_13
13.5 Exercises – 413

13.6 A Mini-Project – 417


References – 418
13.1 · Simulink Interface
389 13
System simulation is the study of system performance based on the mathematical
models and systems behavior of real systems. In particular, it refers to use computers
to investigate system performances. The fundamental contents of computer simu-
lation include systems, modeling, algorithms, programming and simulation result
display, analysis and validations. In this chapter, the essential knowledge of Simulink
is presented, and the modeling strategies for various ODEs are explored.
System simulation is becoming the third important methodology to understand
and change the world, after theoretical research and scientific experiment [1]. Many
tasks that cannot be undertaken in theoretical and experimental research may be
solved easily with system simulation techniques. For instance, the experiments which
cannot be carried out in hazardous environment, or the experiments whose cost is
too high or too time-demanding can be carried out in simulation, such that reliable
results can be achieved. System simulation technology has been used successfully in
almost all aspects in science and engineering.
Simulab environment was first released in 1990 by MathWorks, where block dia-
grams are used to build up simulation models for complicated systems and then carry
out simulation studies directly. It was renamed to Simulink in 1992, and it gradually
became the main-stream tool in the field of system modeling and simulation. In 1997,
Stateflow was released in MathWorks, to support finite-state machine modeling. In
MATLAB version R2008a, multi-domain physical modeling concept was proposed,
and the Simscape tool and Simscape language were put forward, allowing the user to
create complicated system models with the mechanical, electrical, electronic and con-
trol domains under the same framework, using building block methods. The capabil-
ities of Simulink in engineering systems are boosted with the modeling methodology.
In MATLAB R2019b, a new Simulink 10.0 was proposed. A brand new interface is
provided, such that the modeling and simulation with Simulink are even more flexible.
In this chapter and in 7 Chap. 14, systematic knowledge will be addressed in
applying Simulink in the system model and simulation processes. In 7 Sect. 13.1,
the fundamental knowledge on Simulink block library and toolbars are introduced.
In 7 Sect. 13.2, a brief introduction is made on various commonly used blocks and
groups provided in Simulink. This established a necessary foundation in Simulink
modeling. In 7 Sect. 13.3, parameter setting of Simulink are introduced, with concen-
trations on solver and input/output control parameters. In 7 Sect. 13.4, the modeling
and solution of various ODEs are introduced. Ordinary rules and unified frameworks
are presented in the Simulink modeling process. Examples are used to demonstrate
the modeling and solutions of the ODEs.

13.1 Simulink Interface


Simulink modeling means to set up a Simulink model to describe the systems to be
studied. A very powerful block library is provided in Simulink, including the Simulink
block groups, the blocksets of various toolboxes and the user’s own or third-party
blocksets. The blocks in these libraries and blocksets can be used to draw Simulink
models. Then the facilities in Simulink carry out simulation analysis of the models. In
this section, essential operations of Simulink block library and blank model window
are presented, and then the Simulink toolbars are illustrated.
390 Chapter 13 · Modeling and Simulation with Simulink

13.1.1 Block Library and Blank Model Windows


There are many methods to open the Simulink block library. A convenient way to
open block library is as follows. Issue the command open_system('simulink') in
MATLAB command window, and the model library in . Fig. 13.1 can be opened.
The icons in the library are referred to as block groups. There are lower-level groups
or blocks in each of these groups.
There are other ways in opening block libraries. For instance, command
simulink can be issued in MATLAB command window, or by clicking the Simulink
icon in the MATLAB command window toolbar. The form of the block library is
different from the one shown in . Fig. 13.1. These methods are not recommended in
this book.
Click the New icon in the toolbar, a blank Simulink model window is opened, as
shown in . Fig. 13.2. The blocks needed in modeling can be dragged into the blank

13

. Fig. 13.1 Simulink block library


13.1 · Simulink Interface
391 13

. Fig. 13.2 A blank model window in Simulink

model window, or using “copy−paste” method. The blocks can then be connected
accordingly so as to set up the simulation model.

13.1.2 Simulink Toolbars


It can be seen from the block library window and blank model window that various
toolbars are provided in Simulink. The main toolbar is shown in . Fig. 13.3. Various
panes are provided and the current one is SIMULATION. The zones on the bottom are
provided such as FILE, LIBRARY, PREPARE, SIMULATE and so on. The FILE zone provides
various buttons for file operations, used to create, open or save models. There is a
sign beside each button, which is equivalent to the popup menus, providing more
options in file manipulations. There are two types of MATLAB model files, one is the
readable .mdl file, the other is the binary .slx file. The latter is the default format.

. Fig. 13.3 Main toolbar in Simulink model window


392 Chapter 13 · Modeling and Simulation with Simulink

In the LIBRARY zone, the button Library Browser allows the user to open a block
library. If it is already opened, it is brought to the front. Various Apps are provided
in the PREPARE zone, which are not discussed further here.
SIMULATE zone is the most important one in Simulink toolbar. It is provided in
many controls. The simulation interval can be set in this zone, while Run and Stop
buttons control the simulation process. The buttons such as Step Forward can be used
to carry out single-step execution in the simulation process. Besides, the Fast Restart
toggle button sets or cancels the fast restart mode in simulation. The facilities and
applications will be presented later.
Clicking other panes, various other toolbars are displayed. Here the toolbar under
MODELING pane is obtained as shown in . Fig. 13.4. Similar zones are provided under
this toolbar, as the ones in SIMULATE zone. Various App buttons are also provided,
such as Model Adviser. They are not further discussed here. In the SETUP zone, a series
of model setting dialog boxes are supported, such as Model Settings ( ) button. It
opens a model parameter setting dialog box, and the specific information will be
explained later.

13.2 Commonly Used Block Groups


Many fundamental and professional blocks are provided in MATLAB. Theoretically
speaking, systems of any complexity can be modeled with the blocks. In this section, a
brief introduction to some commonly used blocks and their parameter-setting meth-
ods are illustrated. Then simple Simulink modeling methods are demonstrated with
the commonly used blocks.

13.2.1 Input and Output Blocks


Double click the Sources icon in the model library in . Fig. 13.1, the block group is
13 shown in . Fig. 13.5. The commonly used blocks are presented in . Table 13.1.
Double click the Sinks group icon, the group is opened, and the commonly used
blocks are presented in . Table 13.2. The blocks in this group are used to display
directly the signals in the Simulink models.

. Fig. 13.4 Simulink MODELING toolbar


13.2 · Commonly Used Block Groups
393 13

. Fig. 13.5 Input source group

. Table 13.1 Commonly used input source blocks

Blocks Descriptions with default values in brackets

Step Step input block, with key parameters of Step time (default of 1, usually
should be set to 0), Initial value (0) and Final value (1)

In1 Input port block, the port number is arranged by Simulink automatically

Clock Clock block, to generate the time t

Sine wave Sinusoidal wave block, with Amplitude (1), Frequency (1) and Phase (0)

Constant Constant block, with Constant parameter (1); vector is allowed to generate
vector signals

Signal generator Signal generator block, with selections of sine, sawtooth and square waves

13.2.2 Continuous and Discrete Blocks


Various continuous and discrete block groups are provided in Simulink. The com-
monly used blocks in the Continuous group are shown in . Table 13.3.
Double click the Discrete group icon, the discrete block group is opened. The
major blocks are presented in . Table 13.4. It can be seen that many linear systems
can be modeled directly with the blocks in the two groups.
In fact, the blocks in the two groups are sometimes complicated to describe cer-
tain linear models. For instance, the multivariable transfer function matrix G(s) with
delays [2]. A concise block is introduced here. Double click the Blocksets and Tool-
boxes icon, the other associated model blocksets can be opened, from which in the
Control System Toolbox group, the LTI System block describes linear time invariant
(LTI) object in MATLAB Control System Toolbox.
394 Chapter 13 · Modeling and Simulation with Simulink

. Table 13.2 Commonly used output blocks

Blocks Descriptions and major parameters

Scope Scope block, connected to an interested signal to display it in the


simulation process

Out1 Output port block, the port number is arranged automatically in


Simulink

Terminator Terminator block, to avoid warning messages by connecting it to a


suspended signal

STOP simulation Stop block, which terminates the simulation process if its input
signal is true

To workspace Writes the signal back to MATLAB workspace

. Table 13.3 Commonly used continuous blocks

Blocks Descriptions and major parameters

Integrator Integrator block, whose output signal is the integral of its input signal.
The commonly used parameter is Initial values (0). The variations of the
block such as Integrator Limited and so on are provided

Transfer fcn Transfer function block, with numerator coefficient vector (1) and
denominator coefficient vector [1,1], describing the transfer function
1/(s + 1). In the coefficient vectors, the coefficients are arranged in the
descending order of s

State space State space block, which describes multivariable systems

Zero–pole Zero−pole block, with the zero and pole vectors and the gain (1)

13 Transport delay Delay block, with delay constant (1). The output is the input signal at
1 s earlier

PID controller PID controller block, with variations of 2DOF PID controller blocks

 Example 13.1
Express the multivariable transfer function matrix block with Simulink [3].
⎡ ⎤
0.1134 −0.72s 0.924
⎢ 1.78s2 + 4.48s + 1 e ⎥
2.07s + 1
G(s) = ⎢

⎥.

0.3378 −0.3s − 0.318 e−1.29s
e
0.361s + 1.09s + 1
2 2.93s + 1

Solutions For such a multivariable system, the sub-transfer functions can be entered into
MATLAB first, then the transfer function matrix can be composed, just as if an ordinary
matrix is created. The MATLAB commands are as follows:
13.2 · Commonly Used Block Groups
395 13

. Table 13.4 Commonly used discrete blocks

Blocks Descriptions with major paremeters

Unit delay Unit delay block whose output is the input signal at the previous
sample time. Major parameters are the sample time (−1, indicating
inherits the sample time of its input signal)

Discrete transfer fcn Discrete transfer function; besides, Discrete State-Space and Discrete
Zero–Pole blocks also allowed, with default sample time of −1

Zero-order hold Zero-order hold block whose output signal is kept unchanged during
the same sample time

Memory Memory block, whose output is the input signal at the previous time
instance

Discrete PID controller Discrete PID controller blocks

>> g11=tf(0.1134,[1.78 4.48 1],'ioDelay',0.72); % input the sub-TFs


g21=tf(0.3378,[0.361 1.09 1],'ioDelay',0.3);
g12=tf(0.924,[2.07 1]); g22=tf(-0.318,[2.93 1],'ioDelay',1.29);
G=[g11, g12; g21, g22]; % input the transfer function matrix as a matrix
When the G object is created in the MATLAB workspace, the above-mentioned LTI System
block can be used, and fill G into the block dialog box. Therefore, Simulink can be used to
describe the model directly. 

13.2.3 Computing Blocks


Various operations can be made through the Simulink blocks. For instance, if a signal
is fed into a nonlinear block or a mathematical operations block, the processed signal
can be obtained directly. Besides, function blocks are adopted for more complicated
operations on the input signals. In this section, direct operations on the signals are
made in Simulink. Also applications of the signal routing blocks are demonstrated.

1. Nonlinearity Blocks
If a signal is fed into a block in the Discontinuities group, nonlinear actions can
be performed on its input signal. Double click the group icon, the commonly used
nonlinear elements are shown in . Table 13.5.

2. Mathematical Function Group


Double click the Math Operations group icon, the group can be opened and the
commonly used blocks are as shown in . Table 13.6. Algebraic manipulations of the
input signals can be processed.
396 Chapter 13 · Modeling and Simulation with Simulink

. Table 13.5 Commonly used nonlinear blocks

Blocks Descriptions with major parameters

Saturation Saturation block, with common parameters of the bounds (±0.5); Dynamic saturation
also supports blocks with dynamic upper and lower bounds, driven by external
signals

Dead-zone Dead-zone nonlinearity whose parameters are the bounds of the dead zone (±0.5);
also provides Dynamic Dead-Zone blocks

Backlash Backlash nonlinearity block

Relay Relay nonlinear block

. Table 13.6 Commonly used nonlinear blocks

Blocks Descriptions with major parameters

Sum Sum block, where two or several input signals can be added up to generate
the output signal; Simulink multiplication and division can be
implemented with Product and Divide blocks

Abs Absolute value block, whose output is the absolute value of the input

Gain Gain block, returns the input times the gain. Matrix multiplication and
dot product are also supported in the gain block

Algebraic constraints Algebraic constraint block used in solving algebraic equations

3. User-Defined Functions Group


13 Apart from the above blocks with fixed functions, Simulink also allows to define his
own functions. Theoretically, operations of any complexity can be worked out. The
commonly used blocks in the User-Defined Functions group are shown in . Table
13.7.

4. Signal Routing Group


Double click the Signal Routing group, many signal routing blocks are provided, as
shown in . Table 13.8.

13.2.4 Examples in Simulink Modeling and Simulation


Two simple examples are given here, to demonstrate the modeling method in Simulink.
Also simple simulation methods are illustrated.
13.2 · Commonly Used Block Groups
397 13

. Table 13.7 User-defined function blocks

Blocks Descriptions and parameters

Fcn Simple function block. If the input signal is u, function expression


can be specified in the edit box of the Fcn block. For instance, if
the string u(2)^2*sin(u(1)*u(2)) is specified, the
mathematical formula u22 sin(u1 u2 ) is implemented. Such a block
was removed in R2020b and recovered in the next version

Interpreted MATLAB Function A MATLAB function block, should be associated to an


M-function file

MATLAB Function Similar to the Interpreted MATLAB Function block, but no need to
associate .m file. The function with an editor is embedded in the
block

S-function S-function block used to describe system blocks, see details in


7 Chap. 14

 Example 13.2
Construct a Simulink model for the control system structure in . Fig. 13.6.
Solutions Analyzing the block diagram of the system in . Fig. 13.6, it is seen that the
following blocks are needed in building up the Simulink model.

. Table 13.8 Signal routing blocks

Blocks Descriptions with major parameters

Mux Mux block, merges several scalar or vector signals into a vector signal

Demux Demux block decompose a vector signal into several scalar and vector signals

Switch Switch block, which uses its second input signal to decide which channel of input
signals is connected. There are two variations: Multiport switch and Manual Switch

Selector Selector block, which picks up one or several signals from the input vector

( ) 0.3 ( ) 1 ( )
1+ 4 +4 3 +6 2 +4
− 0.5 +1

0.1

. Fig. 13.6 Block diagram of a feedback control system


398 Chapter 13 · Modeling and Simulation with Simulink

(1) Transfer function block. The controller 1+0.3/s and plant 1/(s4+4s3+6s2+4s+1) are both
transfer function blocks. The Transfer Fcn block from the Continuous group can be copied
into the model window. The parameters in the blocks should be modified accordingly, to
keep consistent with the ones in . Fig. 13.6. Besides, in the process of model building, two
Transfer Fcn blocks appear in the same window. Therefore, Simulink renames the latter
one automatically to Transfer Fcn1 or other names. The block names can also be modified
manually. The specific method is that, click the block name tag, then modify its name.
Make sure that the block name is unique in the model, otherwise it is not accepted.
(2) Nonlinearities. Two nonlinear element blocks are needed in the model, Saturation and
Dead Zone. They should be copied into the model window from the Discontinuities group.
The parameters of the two blocks can be modified accordingly.
(3) Input and output blocks. The step input block describes the input signal, which can be
represented by the Step block in the Sources group. The scope or output port blocks can be
used as the output blocks. Copy Scope or Out1 blocks from the Sinks group into the model
window.
(4) The sum block. The Sum block from the Math Operations group can be copied into the
model window.
With these blocks ready, the parameters of the blocks can be modified, and then they can
be connected in the way described in . Fig. 13.6. The simulation model for the feedback
control system model is created. In the model, the default input ports are on the left, and
the output ports are on the right. It is not a simple task to construct the feedback path.
The Dead-Zone block should be flipped first, then connected. Of course, a simpler method
presented below can be used. Connect the second input port of the Sum block backward
to the system output, then drag the Dead-Zone block on top of the signal line, and release
mouse button, the block can then be embedded into the line, without using the manual
flipping step. In this way, the simulation model shown in . Fig. 13.7 can be constructed.


 Example 13.3
Consider parabolic problem in physics. The equation is v(t) = v0 +gt, where t is the time,
v(t) is the instantaneous speed of the object, v0 = 1 m/s is the initial speed, g = 9.81 m/s2 is
13 the gravity acceleration. Study the relationship between time t and displacement x(t).
Solutions The relationship between the speed v(t) and displacement x(t) is v(t) = x (t).
Therefore, the original equation can be rewritten as x (t) = v0 + gt. Introducing an inte-
grator block, and assume that its output signal is x(t), the input signal is then x (t). The
two signals are referred to as the key signals.

. Fig. 13.7 Simulink model of the nonlinear system (file name: c13mmod1.slx)
13.3 · Simulink Parameters Settings
399 13

. Fig. 13.8 Parabolic system description with Simulink (file name: c13mmove.slx)

With the key signals, the Simulink model in . Fig. 13.8 can be constructed, where the
initial speed v0 = 1 is provided with the Constant block. Time t is generated by the Clock
block, and it is fed into the Gain block, with gain g = 9.81 to yield gt signals. The two
signals can be added up, to construct the expression on the right of the equation. Since the
left side of the equation is the key signal x (t), the right side signal obtained above can be
fed into the input port of the integrator, such that the Simulink model of the differential
equation can be constructed.
Assign the value to variable g, and then invoke the simulation process, the simulation results
can be obtained directly. Since the output port block is used, a structured variable out is
by default returned to MATLAB workspace automatically. All the simulation information
is included in the structured variable out. To draw the curve of the simulation results, the
following commands should be issued.
>> plot(out.tout, out.yout{1}.Values.Data)
It is seen that, although modeling and simulation process are simple, it is rather tedious
to extract simulation results. Better methods should be introduced to extract simulation
results. 

Since the structured data is too complicated to retrieve simulation result, the fol-
lowing MATLAB function can be written to draw the simulation curves or extract
simulation data. The syntax of the function is [t, y]=sl_polt(out,v), where out
is the structured variable, v is the vector, indicating which of the output signals are
handled. If v is not provided, all the output signals are handled. If no returned argu-
ments are specified, the simulation results are drawn directly; if returned arguments
are specified, no plot is drawn.
function [t0,yy0]=sl_plot(out,varargin)
t=out.tout; y=out.yout; sigs=1:length(y); yy=[];
if nargin==2, sigs=varargin{2}; end
for i=sigs, yy=[yy, out.yout{i}.Values.Data]; end
if nargout>0, t0=t; yy0=yy; else, plot(t,yy), end
end

13.3 Simulink Parameters Settings


For better use Simulink in modeling and simulation, it is recommended to modify
some default necessary control parameters in Simulink environment. These include
400 Chapter 13 · Modeling and Simulation with Simulink

the solver parameters setting and input and output parameters setting and so on. In
this section, the settings of these parameters are demonstrated, and also an introduc-
tion is made on presetting of the variables in the models.

13.3.1 Solver Settings


Since ODEs are the essential form of continuous dynamic systems, and in the illustra-
tion to ODE solutions in 7 Chap. 10, the numerical algorithms and control param-
eters are discussed. Click the icon in the Simulink toolbar, the dialog box in
. Fig. 13.9 is opened, allowing the user to specify control parameters.
It is seen from the list on the left of the dialog box that the specification of the
parameters is about the Solver, that the ones on the right are the solver parameters.
The start time and stop time of simulation can be specified. Also the user is allowed
to select an algorithm from the Solver listbox, with the default one Auto, indicating
that ode45 is the default one. Besides, relative and absolute error tolerances can be
specified. According to the introductions in 7 Chap. 10, the relative error tolerance
can be set to 3 × 10−14 , while the absolute one should be eps. Therefore, the most
accurate solutions can be found under double precision framework.

13

. Fig. 13.9 Solver parameter setting dialog box


13.3 · Simulink Parameters Settings
401 13
13.3.2 Input and Output Parameter Settings
Click the icon in Simulink toolbar, and select the Data Import/Outport pane in
the listbox on the right of . Fig. 13.9, the relevant part in the dialog box shown in
. Fig. 13.10 is displayed, allowing the user to specify the input and output settings.
Note the checkbox Single simulation output at the bottom. It is checked by default.
The default setting is not quite handy in actual use, sometimes, since when the sim-
ulation process is completed, a structured variable out is returned automatically to
MATLAB workspace. The structured variable is rather complicated to use to draw
simulation results. For instance, the commands in Example 13.4 must be used.
It is recommended to uncheck the option. Meanwhile, set the Format listbox
item from the default Dataset into Array. Therefore, when the simulation process
is completed, two variables tout and yout are generated automatically in MATLAB
workspace. Simple command like plot(tout,yout) draws directly the simulation
results. If the internal state signals are expected, the States option can be checked.
After simulation, an extra variable xout is then generated in MATLAB workspace,
storing all the state information.

13.3.3 Pre-processing of Model Parameters


In Simulink modeling and simulation, variable names can be used in the parameters
of the blocks. However their values must be assigned in MATLAB workspace, before
the simulation process is invoked, otherwise the simulation process cannot be carried
out. Since there may exist many such variables, it is rather complicated to assign them
one by one. Therefore, presetting methods should be used to assign the variable values
automatically each time when the model is opened.
Click the button to the right of the Model Settings button in the toolbar
(. Fig. 13.4), the setting toolbar is expanded, as shown in . Fig. 13.11. Select

. Fig. 13.10 Input and output parameter setting dialog box


402 Chapter 13 · Modeling and Simulation with Simulink

. Fig. 13.11 Model setting menu

13

. Fig. 13.12 Model parameters presetting dialog box

the Model Properties tool, a parameter preset dialog box is opened, as shown in
. Fig. 13.12. In the Callbacks pane, select the PreLoadFcn item, then fill in the assign-
ment commands in the Model pre-load function edit box. Therefore, each time the
model is opened, the parameters are assigned automatically. This makes the modeling
and simulation process more concise.
13.4 · Modeling and Solutions of ODEs with Simulink
403 13

 Example 13.4
Consider the Simulink model in Example 13.3. Since before the model is opened each time,
the parameter g should be assigned. It is rather complicated. Set the parameter automati-
cally before the model is opened.
Solutions Open the dialog box in . Fig. 13.11, and fill in the command g = 9.81 in the
Model pre-load function edit box, then save the model. In this way, each time the model is
opened, the value of g is assigned automatically, such that the model can be used normally.


13.4 Modeling and Solutions of ODEs with Simulink


Ordinary differential equations are the essential mathematical foundations of con-
tinuous dynamic systems. Therefore, the Simulink modeling and numerical solutions
of ODEs are very important. In 7 Chap. 10, numerical solution methods are dis-
cussed, where the ODEs must be converted into the first-order explicit ODEs first.
The conversion is sometimes impossible for certain complicated ODEs. Therefore,
Simulink modeling methods can be introduced, such that the block diagram model-
ing technique can be adopted to describe ODEs, so as to solve them. In this section,
general rules in Simulink modeling of ODEs are summarized first. Examples are used
to demonstrate the modeling and simulation procedures. The modeling patterns of
ODE sets, implicit ODEs and delay differential equations are presented.

13.4.1 Suggested Simulink Modeling Rules


There are rules in Simulink modeling for ODEs. In the real modeling process, the
following rules are summarized to draw block diagrams of the systems.
(1) To define signals x(t) and x (t), an Integrator block should be introduced. The
output signal can be regarded as the signal x(t), the input is then x (t) signal. In this
way, the key signals in the ODEs can be defined.
(2) If two signals are equal, they can be connected together directly with signal
lines. In this way, the simulation loop can be closed.
(3) Assume that the signal u(t) is connected to a Gain block, and double click the
block to specify the gain value of k, the output of the block is ku(t).
(4) Nonlinear algebraic operations can be made to the signal v(t). For instance,
to compute the signal (v(t) + v 3 (t)/3) sin v(t), signal v(t) can be fed into the Fcn or
MATLAB Function blocks. Double click the blocks, fill in the command (u+u^3/3)
*sin(u) in the parameter dialog box, the output signal is the expected nonlinear
signal. Note that no matter what is the input signal, it should be denoted as u in the
parameter dialog box of the Fcn block.
(5) Several signals can be fed into the Mux block, such that a vector signal can be
composed; if the vectorized signal is fed into the Demux block, it can be decomposed
into scalar or smaller vector signals.
404 Chapter 13 · Modeling and Simulation with Simulink

(6) To generate the delay signal u(t − d) from u(t), signal u(t) can be fed into the
Transport Delay block. Double click the block, the parameter d can be specified in the
parameter dialog box. The output signal of the block is the expected delay signal.
(7) To acquire a signal, it can be connected to a Scope block or an Out block, such
that the signal can be displayed or further manipulated.
With the above modeling rules, it is easy to establish the simulation model for the
ODEs. It is not necessary to convert the ODEs first into standard forms. Graphical
method can be used to draw the Simulink models directly for the ODEs. Then the
simulation facilities in Simulink can be used to find the numerical solutions of the
ODEs.

13.4.2 Low-Level Modeling Schemes


With the rules in Simulink modeling presented earlier, the simulation model can be
established. The modeling methods are referred to as low-level modeling methods.
An example is presented next to demonstrate low-level modeling methods for ODEs.

 Example 13.5
Set up a Simulink model for the following Lorenz equation:
⎧ 
⎨ x1 (t) = −βx1 (t) + x2 (t)x3 (t)
x (t) = −ρx2 (t) + ρx3 (t)
⎩ 2
x3 (t) = −x1 (t)x2 (t) + σ x2 (t) − x3 (t),

where β = 8/3, ρ = 10 and σ = 28. The initial states are x1 (0) = x2 (0) = 0 and x3 (0) = ,
 is a small constant on the machine, for instance,  = 10−10 .
Solutions To set up a Simulink model for the ODE, the above-mentioned rules can be used.
Three integrators can be set up in the model window, to define the key signals. For this
13 particular example, assume that the outputs of the three integrators are, respectively, x1 (t),
x2 (t) and x3 (t), as shown in . Fig. 13.13a, their input signals are then, respectively, x1 (t),

key signals

. Fig. 13.13 Simulink modeling process (file names: c13mlor1a.slx and c13mlor1b.slx)
13.4 · Modeling and Solutions of ODEs with Simulink
405 13
x2 (t) and x3 (t). Double click the integrator blocks, the initial values of the states can be
accordingly written into the parameter dialog boxes.
Feed the x1 (t) signal to a Gain block, and assign the value of −β into the block, the output
signal of the gain block is then the −βx1 (t) signal. Feed x2 (t) and x3 (t) signals into a
Product block, the signal x2 (t)x3 (t) can be obtained. Adding up the two signals with a Sum
block, the right side of the first equation can be constructed. Since x1 (t) signal is the input
signal of the first integrator block, the previously constructed signal can be fed into the first
integrator, such that the first equation can be established, as shown in . Fig. 13.13b.
With similar methods, the other two equations can also be constructed. The Simulink model
in . Fig. 13.14 can be constructed. It can be seen that the entire ODE can be modeled with
the low-level modeling strategy. The methods in 7 Sect. 13.3 can be used to set the solver
parameters, and the input and output parameters.
Invoke the simulation process, two variables tout and yout can be established automati-
cally in MATLAB workspace. The former one is a column vector, and the latter is a matrix
of three columns, corresponding to the three output ports. The following commands draw
the time responses and phase space trajectory, as shown in . Fig. 13.15.
>> plot(tout,yout), figure, plot3(yout(:,1),yout(:,2),yout(:,3))


13.4.3 Vectorized Modeling Approach


It is seen from . Fig. 13.14 that the low-level Simulink modeling method is rather
tedious and complicated. It is much more complicated than the anonymous function
description method in the command-driven solvers presented in 7 Chap. 10. Is there
a simpler and more straightforward modeling method in Simulink?

. Fig. 13.14 Simulink model of the Lorenz equation (file name: c13mlor2.slx)
406 Chapter 13 · Modeling and Simulation with Simulink

40

20

-20

-40

-60

-80

-100

-120

-140
0 5 10 15 20 25 30

(a) time domain response

(b) phase space trajectory

. Fig. 13.15 Lorenz equation solutions

13 In Example 13.5, three integrators are recommended to describe the three states.
If only one Integrator block is used, and define its output signal as the state vector
x(t), the input signal is the x  (t) vector. Such a modeling method is referred to as the
vectorized modeling method. Vectorized modeling method is a more concise modeling
method for ODEs. In this section, vectorized modeling method is presented.

 Example 13.6
Build again the simulation model to describe Lorenz equations.
Solutions An integrator block is used to represent the state variable vector. Double click
the integrator block, and set its initial values to a vector [0;0;1e-10]. Then the key signals
are defined. To compute signal x  (t) directly from the given states, the MATLAB Function
block in the User-Defined Functions group can be used, such that the simulation model in
. Fig. 13.16a can be constructed. Double click the MATLAB Function block, a MATLAB
editor can be opened automatically. The following commands can be written into the editor.
13.4 · Modeling and Solutions of ODEs with Simulink
407 13

(a) function block (b) interpreted function

. Fig. 13.16 Vectorized Simulink model (file name: c13mlor3a.slx and c13mlor3b.slx)

function y = fcn(u)
y=[-8*u(1)/3+u(2)*u(3); -10*u(2)+10*u(3); -u(1)*u(2)+28*u(2)-u(3)];
end
Then the function is embedded into the Simulink model automatically. Compared with the
Fcn block provided in the earlier versions, vector output is supported directly in the block.
Unfortunately, the contents of the function are not displayed in the block diagram. The
readability of the model is not very satisfactory.
If the block MATLAB Function is substituted with the Interpreted MATLAB Function block,
the following M-function should be written.
function y=c13mlor0(u)
y=[-8*u(1)/3+u(2)*u(3); -10*u(2)+10*u(3); -u(1)*u(2)+28*u(2)-u(3)];
end
then the file name c13mlor0 can be written into the Interpreted MATLAB Function block,
through its parameter dialog box. The simulation model in . Fig. 13.16b can be estab-
lished. It can be seen that the two modeling methods are similar in complexity, and the
simulation results are identical. 

13.4.4 Standard Framework for ODEs


It can be seen from the vectorized framework in Example 13.4 that the modeling
method is quite standardized, and concise. The complexity in modeling is similar to
the command-driven method in 7 Chap. 10. There are however two deficiencies:
(1) Only constants can be used, rather than other parameters. If parameters such
as β are used, the source file must be written to assign them to constants. This is rather
complicated in modeling. To solve this kind of problem, S-functions should be used.
This will be demonstrated later.
(2) The signal t cannot be explicitly contained in the ODE.
If t is explicitly contained in the ODEs, t and the states can be grouped into a
vector signal, known as the augmented state vector. Since the number of augmented
states is different from the number of the derivative of the states, the MATLAB Function
block in Example 13.4 cannot be used, the Interpreted MATLAB Function block can be
used instead to describe the function. An example is presented next to demonstrate
408 Chapter 13 · Modeling and Simulation with Simulink

the modeling method. A unified modeling framework of ODE x  (t) = f (t, x(t)) is
then proposed.

 Example 13.7
Find the numerical solution of the following ODE [4]:

y (x) = −2xy(x) ln z(x)


z (x) = 2xz(x) ln y(x),

with initial conditions y(0) = e and z(0) = 1. The analytical solutions of the ODEs are
2 2
y(x) = ecos x and z(x) = esin x . Solve the ODE with Simulink.
Solutions It can be seen from the ODEs that the independent variable is x, while in Simulink
modeling, the system is a time-driven one, with independent variable of t. Therefore, the
independent variable should be substituted to t. The original ODE can then be rewritten as

y (t) = −2ty(t) ln z(t)


z (t) = 2tz(t) ln y(t).

Introducing the vector u(t) = [y(t), z(t), t], the function on the right is written as

−2u3 (t)u1 (t) ln u2 (t)


f (u(t)) = .
2u3 (t)u2 (t) ln u1 (t)

13

. Fig. 13.17 Simulation model (file name: c13m2d.slx)

. Fig. 13.18 Parameter dialog box


13.4 · Modeling and Solutions of ODEs with Simulink
409 13
The following MATLAB function can be written to describe the function expression above.
function y=c13m2d0(u)
y=[-2*u(3)*u(1)*log(u(2)); 2*u(3)*u(2)*log(u(1))];
end
Integrators can be used to define the key signals, then feed the signals into the Mux block
to form the augmented state vector signal u(t), such that the model in . Fig. 13.17 can
be constructed. Note that since the numbers of inputs and outputs are different in the
f (u) function, therefore, double click the Interpreted MATLAB Fc block, specify the Output
dimension edit box to 2, as shown in . Fig. 13.18.
Invoke the simulation process, the simulation results in . Fig. 13.19 can be found. The
following commands compare simulation results and the exact ones. It is found that the
maximum error is 3.9608×10−12 , indicating that the simulation results are accurate.
>> y0=[exp(cos(tout.^2)), exp(sin(tout.^2))]; % compute theoretical results
plot(tout,yout(:,1:2),tout,y0,'--') % draw ODE solutions, exact ones
yy=y0-yout(:,1:2); max(abs(yy(:))) % find the maximum error


13.4.5 Modeling of ODE Sets


When using Simulink to model ODE sets, it is not necessary to convert it first into
the standard form. As usual, integrators can be used to define the key signals, then
the Interpreted MATLAB Function block describes the ODE sets. Examples are used
to demonstrate the modeling and simulation problems in ODE sets.

 Example 13.8
Create a Simulink model for solving the ODE set describing Apollo satellite movement in
Example 10.14.

2.5

1.5

0.5

0
0 1 2 3 4 5 6 7 8 9 10

. Fig. 13.19 Comparisons of simulation results and exact ones


410 Chapter 13 · Modeling and Simulation with Simulink

Solutions Two sets of integrator chains are used to describe the key signals x(t), x (t), x (t)
and y(t), y (t), y (t). The signals x(t), x (t), y(t) and y (t) can be fed into the Mux block,
such that a vector signal u(t) = [x(t), x (t), y(t), y (t)] is created. Therefore, the following
MATLAB function can be written to describe the right of the ODE.
function y=c13mapol0(u)
mu=1/82.45; mu1=1-mu;
r1=sqrt((u(1)+mu)^2+u(3)^2); r2=sqrt((u(1)-mu1)^2+u(3)^2);
y=[2*u(4)+u(1)-mu1*(u(1)+mu)/r1^3-mu*(u(1)-mu1)/r2^3;
-2*u(2)+u(3)-mu1*u(3)/r1^3-mu*u(3)/r2^3];
end
The function name can be embedded in the Interpreted MATLAB Function block, and the
number of outputs is set to 2. The Simulink model can be created as shown in . Fig. 13.20.
Carry out simulation process, the simulation result obtained is exactly the same as the ones
in Example 10.14. 

13.4.6 Modeling of Implicit ODEs


An Algebraic Constraints block is provided in Simulink, which can be used to solve
directly algebraic equations. The block can be used to create Simulink models in
solving implicit ODEs. An example is given next to demonstrate the modeling and
solution methods in solving implicit ODEs.

 Example 13.9
Solve the following implicit differential equation:

(y (t))3 + 3y (t) sin y(t) + 3y (t) sin y (t) = e−3t , y(0) = 1, y (0) = −1.

13 Solutions In the earlier examples, the explicit form of the signal y (t) is given, while in this
example, the explicit expression of y (t) cannot be found. Therefore, if represented in an
integrator chain, the input to the left most integrator cannot be constructed, such that the
simulation loop cannot be formed. This brings difficulties in Simulink modeling process.

. Fig. 13.20 Simulink model for Apollo satellite (file name: c13mapol.slx)
13.4 · Modeling and Solutions of ODEs with Simulink
411 13
To solve the equation, two integrators are used to form the chain, so as to define the key
signals y(t), y (t) and y (t). Denote p(t) = y (t), an algebraic equation on signal p(t) is
formulated.
p3 (t) + 3p(t) sin y(t) + 3y (t) sin p(t) − e−3t = 0.
Constructing the vector u(t) = [y(t), y (t), y (t), t], the above equation can be converted to

u33 (t) + 3u3 (t) sin u1 (t) + 3u2 (t) sin u3 (t) − e−3u4 (t) = 0.

Write a MATLAB function, and embed it into the Interpreted MATLAB Fc block.
function y=c13mimp0(u)
y=u(3)^3+3*u(3)*sin(u(1))+3*u(2)*sin(u(3))-exp(-3*u(4));
end
The output of the block can be fed into the Algebraic Constraint block. The output signal of
the latter block can be connected to the input terminal of the left most integrator, such that
the simulation loop is closed. The Simulink model shown in . Fig. 13.21 is constructed.
Invoke the simulation process, and compare the results with the theoretical one, it is found
that the maximum error is 5.8071×10−13 . Therefore, this method can be used to solve the
implicit ODEs.

. Fig. 13.21 Simulink model for the implicit ODE (file name: c13mimp.slx)

. Fig. 13.22 The new Simulink model (file name: c13mimp2.slx)


412 Chapter 13 · Modeling and Simulation with Simulink

>> err=max(abs(yout-exp(-tout)))
If the Interpreted MATLAB Function block is replaced by the Fcn block, a new Simulink
model in . Fig. 13.22 can be constructed. It can be seen that there is no need to build up
a MATLAB file, and the model is more readable. 

13.4.7 Modeling of Delay Differential Equations


Transport Delay block extracts the delay signals in Simulink. With the delay signals,
Simulink models can be constructed for the delay differential equations (DDEs). In
this section, examples are used to demonstrate the modeling and solutions of ordinary
DDEs and neutral-type DDEs.

 Example 13.10
Find again the numerical solution of the DDE studied in Example 10.19, where the delays
are constants. For simplicity, the DDE is rewritten here again.

x (t) = 1 − 3x(t) − y(t − 1) − 0.2x3 (t − 0.5) − x(t − 0.5)


4x(t) = y (t) + 3y (t) + 2y(t),

where, when t  0, x(t) = y(t) = y (t) = 0.


Solutions It can be seen from the second equation that signal y(t) can be generated by
feeding signal x(t) into a transfer function 4/(s2 + 3s + 2) block, while x(t) and y(t) signals
are fed into the Transport Delay blocks to generate delay signals. Based on the first equation.
the signal vector u(t) = [x(t), y(t − 1), x(t − 0.5)] is composed. Therefore, the Fcn block
describes the right side of the first equation. The output signal can be fed into the input
port of the integrator, such that the model in . Fig. 13.23 can be constructed. Carry out
simulation process, the simulation result obtained is identical to the one in Example 10.19.
It can be seen that the complexity in modeling is similar to those in the command-line-driven
solutions. 
13

. Fig. 13.23 Simulink model of the DDE (file name: c13mdde1.slx)


13.5 · Exercises
413 13

 Example 13.11
Set up a Simulink model for the neutral-type DDE in Example 10.21. For the simplicity in
presentation, the original DDE is presented again.

x  (t) = A1 x(t − 0.15) + A2 x  (t − 0.5) + Bu(t),

where the input signal is u(t) ≡ 1, with given matrices


⎡ ⎤ ⎡ ⎤ ⎡ ⎤
−13 3 −3 0.02 0 0 0
A1 = ⎣ 106 −116 62 ⎦ , A2 = ⎣ 0 0.03 0 ⎦, B = ⎣1⎦.
207 −207 113 0 0 0.04 2

Solutions With the vectorized integrator block, the key signals x(t) and x  (t) can be defined.
The delay signals x(t − 0.15) and x  (t − 0.5) can be obtained by feeding the two signals into
the Transport Delay blocks. With the signals, the Simulink model shown in . Fig. 13.24
can be constructed. The same results can be obtained with the ones in Example 10.21.
For this specific example, care must be taken in the modeling process:
(1) The default operation in the gain block is dot operations, while matrix multiplications
are required here. Therefore, in the modeling process, double click the gain blocks, and set
the operations to matrix multiplications in the listbox.
(2) Variables A1 , A2 and B must be assigned before invoking the simulation process. A
better way to assign them is to use the method in 7 Sect. 13.3.3, such that they can be
assigned automatically when the model is opened. 

13.5 Exercises
(1) Open a Simulink model, and paste the model into a Microsoft Word document.
(2) Consider the setting methods for the solver parameters and input, output param-
eters discussed in 7 Sect. 13.3. Construct a new Simulink template, implement-
ing all the settings in the section, so that the next time when a model is created,
the template can be adopted.

. Fig. 13.24 Simulink model of neutral-type DDE (file name: c13mdde2.slx)


414 Chapter 13 · Modeling and Simulation with Simulink

(a) model 1 (b) model 2

. Fig. 13.25 The output signals of the two block diagrams

(3) The default Product block has two input ports and one output ports. Modify
the block parameters, such that it has four input ports.
(4) Consider the Constant block. If vector [1,2,3] is filled into the parameter
dialog box, and the block is connected to a scope block, what is its input signal?
(5) Consider the two models in . Fig. 13.25a, b, what are the output signals? Are
there any differences?
(6) Establish the Simulink model for the nonlinear system shown in . Fig. 13.26 [5].
Observe the output and error signals under unit step input signals. Since there
are series connection of two nonlinear blocks, explain with simulation method,
whether the two nonlinearities can be swapped.
(7) Solve the following linear ODE:

y(5) + 13y(4) + 64y (t) + 152y (t) + 176y (t) + 80y(t)


  π 
= e−2t sin 2t + + cos 3t ,
3

where y(0) = 1, y (0) = 3, y (0) = 0, y (0) = 0 and y(4) (0) = −1. Use Simulink
to describe the model and draw the curve of the solution.
(8) Consider the well-known Rössler equation for chemical reactions.
⎧ 
⎨ x (t) = −y(t) − z(t)
y (t) = x(t) + ay(t)
⎩ 
13 z (t) = b + (x(t) − c)z(t).

Select a = b = 0.2, c = 5.7, and x(0) = y(0) = z(0) = 0. Use Simulink to model
the system and draw the 3D phase space trajectories. Also draw its projection
on the xy plane. If a = 0.2, b = 0.5 and c = 10, draw the 2D and 3D plots again.

2
( ) 2 10
0 ( )
− 1 1 ( + 1) 2

. Fig. 13.26 System model for Exercise (6)


13.5 · Exercises
415 13
(9) Use Simulink to build up the seven-body model, and draw their trajectories.
The positions of the seven bodies at (xi (t), yi (t)) satisfying [6]
 mj    mj  
xi (t) = xj (t) − xi (t) , yi (t) = yj (t) − yi (t) ,
rij (t) rij (t)
j=i j=i

where mi = i, i = 1, 2, . . . , 7, and
 3/2
rij (t) = (xi (t) − xj (t))2 + (yi (t) − yj (t))2 .

The initial position and speed of the objects are x1 (0) = 3, x2 (0) = 3,
x3 (0) = −1, x4 (0) = −3, x5 (0) = 2, x6 (0) = −2, x7 (0) = 2, y1 (0) = 3,
y2 (0) = −3, y3 (0) = 2, y4 (0) = 0, y5 (0) = 0, y6 (0) = −4, y7 (0) = 4,
x6 (0) = 1.75, x7 (0) = −1.5, y4 (0) = −1.25, y5 (0) = 1, and the remaining
xi (0) = yi (0) = 0. The interval is t ∈ (0, 3). Solve the differential equation and
draw the trajectories of the objects.
(10) Consider the following ODE sets [7]:
⎧ 

⎪ y (t) = tan φ(t)

g sin φ(t)γ v 2 (t)
v  (t) = −

⎪ v(t) cos φ(t)
⎩ 
φ (t) = −g/v 2 (t),

where g = 0.032, γ = 0.02, and the initial values y(0) = 0, v(0) = 0.5. The
parameter φ(0) can be assigned, respectively, as 0.3782 and 9.7456. Draw the
Simulink model and find the numerical solutions of the ODEs.
(11) The mathematical model of a chemical reaction is [8]
⎧ 

⎪ y (t) = −Ay1 (t) − By1 (t)y3 (t)
⎨ 1
y2 (t) = Ay1 (t) − MCy2 (t)y3 (t)
⎪ y3 (t) = Ay1 (t) − By1 (t)y3 (t) − MCy2 (t)y3 (t) + Cy4 (t)

⎩ 
y4 (t) = By1 (t)y3 (t) − Cy4 (t),

where A = 7.89 × 10−10 , B = 1.1 × 107 , C = 1.13 × 103 , M = 106 ,


y1 (0) = 1.76×10−3 , y2 (0) = y3 (0) = y4 (0) = 0 and t ∈ (0, 1000). Use Simulink to
find the numerical solutions of the stiff ODEs. If the solution interval is further
increased to t ∈ (0, 1013 ), solve the ODE again.
(12) The dimensionless ODE of a Chua circuit is [9]
⎡   ⎤
α x2 (t) − h(x1 (t))
x  (t) = ⎣ x1 (t) − x2 (t) + x3 (t) ⎦ ,
−βx2 (t)

where the nonlinearity is

1    
h(a) = m1 a + (m0 − m1 ) a + 1 − a − 1 .
2
416 Chapter 13 · Modeling and Simulation with Simulink

If the control parameters are selected as α = 9, β = 14.2886, m0 = −1/7 and


m1 = 2/7, use Simulink to simulate the Chua circuit, and draw the phase plane
trajectory of x1 (t) ∼ x2 (t).
(13) For the following time-varying differential−algebraic equation [10]
⎧   
⎨ x1 (t) = α − 1/(2 − t) x1 (t) + (2 − t)αz(t) + (3 − t)/(2 − t)
x (t) = (1 − α)x1 (t)/(t − 2) − x2 (t) + (α − 1)z(t) + 2e−t
⎩ 2
(t + 2)x1 (t) + (t2 − 4)x2 (t) − (t2 + t − 2)et = 0,

if x1 (0) = x2 (0) = 1, and α is a constant. The analytical solution is x1 (t) =


x2 (t) = et , z(t) = −et /(2 − t), use Simulink to solve the differential−algebraic
equation.
(14) Set up a Simulink model to solve the following discontinuous ODE [6]

y (t) + 2Dy (t) + μ sign(y (t)) + y(t) = A cos ωt,

where D = 0.1, μ = 4, A = 2, ω = π, and initial values y(0) = 3, y (0) = 4.


(15) Use Simulink to create the model for the ODE, where y(0) = 2 and y (0) =
y (0) = 0.
y (t) + ty(t)y (t) + t2 y (t)y2 (t) = e−ty(t) .
(16) Use Algebraic Constraint block to solve the polynomial equation t4 + 10t3 +
31t2 + 46t + 24 = 0. Validate the result with symbolic computing.
(17) Solve the simple DDE with state-dependent delays [11] x (t) = −x(t − |x(t)|),
where the history function is a piecewise function as follows, when t ≤ 0. The
solution of the equation is y(t) = t + 1.

⎨ −1, t ≤ −1
y(t) = 3(t + 1)1/3 /2 − 1, −1 < t ≤ −7/8

10 t/7 + 1, −7/8 < t ≤ 0.
13
(18) Solve the switched linear ODE with Simulink.

x1 (t) = f (x1 (t)) + x2 (t)


x2 (t) = −x1 (t),

where x1 (0) = x2 (0) = 5, and f (x1 (t)) is a piecewise function



⎨ −4x1 (t), x1 (t) > 0
f (x1 (t)) = 2x1 (t), −1 ≤ x1 (t) ≤ 0

−x1 (t) − 3, x1 (t) < −1.

(19) Use Simulink to solve the following discontinuous ODE [6], with initial value
of y(0) = 0.3.
  2
 t2 + 2y2 (t), (t + 0.05)2 + y(t) + 0.15 ≤ 1
y (t) =  2
2t2 + 3y2 (t) − 2, (t + 0.05)2 + y(t) + 0.15 > 1.
13.6 · A Mini-Project
417 13
(20) Use Simulink to solve the delay differential equation [7], where, when t ≤ 0,
y1 (t) = y4 (t) = y5 (t) = et+1 , y2 (t) = et+0.5 , y3 (t) = sin(t + 1), and the solution
interval is t ∈ [0, 1].
⎧ 

⎪ y1 (t) = y5 (t − 1) + y3 (t − 1)


⎨ y2 (t) = y1 (t − 1) + y2 (t − 0.5)
y3 (t) = y3 (t − 1) + y1 (t − 0.5)


⎪ 4 (t) = y5 (t − 1)y4 (t − 1)
⎪ y
⎩ 
y5 (t) = y1 (t − 1).

(21) Assume that the history functions of the state variables are all zero. Solve the
following delay differential equations with variable delays.
⎧ 
⎨ x1 (t) = −2x2 (t) − 3x1 (t − 0.2| sin t|)
x (t) = −0.05x1 (t)x3 (t) − 2x2 (t − 0.8) + 2
⎩ 2
x3 (t) = 0.3x1 (t)x2 (t)x3 (t) + cos(x1 (t)x2 (t)) + 2 sin 0.1t2 .

(22) If the discrete state space model is described below, and x T (0) = [1, −1], find
the step response of the system with Simulink.
0 1 1
(1) x(t + 1) = x(t) + u(t),
−0.16 −1 1
⎡ ⎤ ⎡ ⎤
11/6 −1/4 25/24 −2 2
⎢ 1 1 −1 −1 ⎥ ⎢ ⎥
(2) x(t + 1) = ⎢ ⎥ x(t) + ⎢ 1/2 ⎥ u(t).
⎣ 0 1 −1 0⎦ ⎣ −3/8 ⎦
0 1 −3/4 0 1/4

13.6 A Mini-Project
Before the emergence of tools like Simulink, some of the benchmark problems were
proposed to assess the modeling capabilities of computer modeling tools. F-14 air-
craft model [12] is one of them. The block diagram of the system model is shown in
. Fig. 13.27. There are two input signals, with vector form u = [n(t), αc (t)]T , where
n(t) is the white noise signal with unity variance, and αc (t) = K β(e−γ t −e−βt )/(β −γ )
generates the angle of attack, with K = αcmax eγ tm , and αcmax = 0.0349, tm = 0.025,
β = 426.4352, γ = 0.01. There are three output signals, y(t) = [NZp (t), α(t), q(t)]T ,
and NZp (t) signal is defined as

1
NZp (t) = [−ẇ(t) + U0 q(t) + 22.8q̇(t)].
32.2

The parameters of the system are given by


τa = 0.05, σwG = 3.0, a = 2.5348, b = 64.13, σα = 5.236×10−3 ,
Vτ0 = 690.4, Zb = −63.9979, Mb = −6.8847, U0 = 689.4, Zw = −0.6385,
Mq = −0.6571, Mw = −5.92×10−3 , ω1 = 2.971, ω2 = 4.144, τs = 0.10,
τα = 0.3959, KQ = 0.8156, Kα = 0.6770, Kf = −3.864, KF = −1.745.
418 Chapter 13 · Modeling and Simulation with Simulink

( ) subsystem 2

b
wG √3 +1
( ) 2 G( ) − 1 ( )
√ 3 1 w

+ w

0
1
w
a +1
w
π G( )
− 1
4 π 0 q
+ − q
4
b
subsystem 1

1 + 1 ( )
F c( ) Q
+
s +1 2

f 1 ( ) 1
− +1 0
subsystem 3

. Fig. 13.27 System model of F-14 aircraft

The original problem is to compute all the closed-loop poles of the system with
the computer tools to be assessed. Another problem is, when the loop is broken at
the  point, what are the open-loop poles.
The original problems can be solved easily with today’s leading-edge software
systems. The new problem now is how to design the controllers for the system, such
that the attack angle α(t) can follow the given command signal αc (t) as fast as possible,
with minimum error. Besides, how to design the relevant controller to reduce the
impact of the noise signal n(t)?

13
References
1. Li BH (2012) System simulation is becoming the third research methodology (in Chinese)[J]. Sci
Chinese 1(5):47
2. Xue DY, Chen YQ (2013) Modeling, analysis and design of control systems in MATLAB and
Simulink[M]. World Scientific, Singapore
3. Munro N (1989) Multivariable control 1: the inverse Nyquist array design method[C]// In: Lecture
notes of SERC vacation school on control system design. UMIST, Manchester
4. Felhberg E (1969) Low-order classical Runge−Kutta formulas with stepsize control and their appli-
cations to some heat transfer problems[R]. NASA Technical Report TR R-315, Washington DC
5. Wang WL (2001) Automatic control principles (in Chinese)[M]. Science Press, Beijing
6. Hairer E, Nørsett SP, Wanner G (1993) Solving ordinary differential equations I: Nonstiff prob-
lems[M], 2nd edn. Springer-Verlag, Berlin
7. Shampine LF, Gladwell I, Thompson S (2003) Solving ODEs with MATLAB[M]. Cambridge Uni-
versity Press, Cambridge
8. Hairer E, Wanner G (1996) Solving ordinary differential equations II: Stiff and differential−algebraic
problems[M], 2nd edn. Springer-Verlag, Berlin
9. Fortuna L, Frasca M (2009) Chua’s circuit implementations−Yesterday, today and tomorrow[M].
World Scientific, Singapore
References
419 13
10. Ascher UM, Petzold LR (1998) Computer methods for ordinary differential equations and differential-
algebraic equations[M]. SIAM Press, Philadelphia
11. Hartung F, Krisztin T, Walther H-O et al (2006) Functional differential equations with state-dependent
delays: Theory and applications[M]. In: Cañada A, Drábek P, Fonda A (eds) Handbook of differential
equations−Ordinary differential equations, vol 3. Elsevier, Amsterdam
12. Frederick DK, Rimer M (1988) Benchmark problem for CACSD packages [C]. Beijing, Computer
Aided Design in Control Systems 1988, Selected Papers from the 4th IFAC Symposium
421 14

More on Simulink Modeling


and Simulation
Contents

14.1 Command-Line Methods in Simulation – 423


14.1.1 Simulation Parameter Settings – 423
14.1.2 Invoke Simulation Process with MATLAB – 425
14.1.3 Input and Output Data Structures in Simulink – 425
14.1.4 Parallel Simulation – 427

14.2 Accurate and Fast Simulation – 428


14.2.1 Zero-Crossing Detection – 428
14.2.2 Algebraic Loop Processing – 430
14.2.3 Fast Restart Mode in Simulink Models – 433

14.3 Subsystems and Block Masking – 435


14.3.1 Subsystems – 435
14.3.2 Icon Design of Masked Blocks – 436
14.3.3 Block Masking – 438

14.4 S-Function Programming and Applications – 440


14.4.1 State Space Descriptions – 441
14.4.2 S-Function Structures – 441
14.4.3 S-Function Mechanism – 443
14.4.4 S-Function Response Functions – 443
14.4.5 S-Function Examples – 444
14.4.6 S-Function Block Masking – 450

© The Author(s), under exclusive license to Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9_14
14.5 Exercises – 451

14.6 A Mini-Project – 454


References – 455
14.1 · Command-Line Methods in Simulation
423 14
Fundamental knowledge on modeling and simulation with Simulink is presented in
the previous chapter. With this knowledge, simple modeling and simulation tasks
can be implemented in Simulink. In this chapter, further information on Simulink
applications is illustrated, aiming at promoting the readers’ capabilities of modeling
and simulation skills in real applications. The important topics in this chapter are
command-based Simulink manipulations, subsystems, system masking, as well as
S-function programming.
In 7 Sect. 14.1, MATLAB command-based modeling and simulation are pre-
sented first, followed by the facilities such as parallel simulation approaches. Some
important concepts on modeling and simulation, such as zero-crossing detection, alge-
braic loop avoidance and so on, are presented in 7 Sect. 14.2. The fast restart mode
in Simulink is also addressed, to increase the efficiency in simulation processes. In
7 Sect. 14.3, the concept on subsystems is illustrated, and subsystem masking facilities
are presented, enabling the users to create reusable Simulink blocks. In 7 Sect. 14.4,
the fundamental structure and programming skills on S-functions are presented. The-
oretically speaking, S-functions can be used to handle the modeling problems for
systems of any complexity.

14.1 Command-Line Methods in Simulation


In the earlier presentations, the setting of model and block parameters can be made
with the use of dialog boxes. The simulation process of Simulink models can also be
invoked with the facilities provided in the interface. Apart from that, many functions
are provided in, which are used to set model parameters and to initiate simulation
processes. The syntaxes and use of related commands are addressed in this section,
and the concept of parallel simulation is also illustrated.

14.1.1 Simulation Parameter Settings


The commonly used modeling and simulation functions are provided in MATLAB,
as shown in . Table 14.1. The modeling commands are not demonstrated in this
book, and the interested readers may refer to Reference [1]. In this section, examples
are used to demonstrate the use of set_param() function.
Function set_param() assigns model and block parameters. Model parameter
refers to the parameters for the entire Simulink model, while block parameters are
those for a block. The parameters for different blocks are different. Commonly used
model parameters and values are presented in . Table 14.2.

 Example 14.1
The method for pre-assigning variable parameters is discussed in Example 13.4. Use MAT-
LAB commands to implement the same setting. Also set the relative and absolute error
tolerances to 3 × 10−14 and eps, respectively.
Solutions Open the model first, then gcs command acquires the handle of the model. Then,
function set_param() can be called to modify the parameters of the model.
424 Chapter 14 · More on Simulink Modeling and Simulation

. Table 14.1 Commonly used Simulink model manipulating functions

Function Function syntaxes and explanation

new_system() Command new_system(model name) creates a logical model. Function h


=gcs is used to acquire the current model handle

open_system() Functions open_system(h) and open_system(model name) are used to


open models

close_system() close_system(h) or close_system(model name) to close models

add_block() Command h=add_block(prototype block,target block name) to add a


block

add_line() Link two blocks together with h=add_line(start block/port,end


block/port)

set_param() set_param(h, parameter1,parametervalue1,parameter2,parameter


value 2,· · · ) sets parameters in the model or block, parameter values are
described in strings

. Table 14.2 Commonly used parameters in Simulink models

Parameters Parameter values and explanation

AbsTol Absolute error tolerance, with default value set to 'auto', the actual
value is 10−6 , while recommended to set it to eps

RelTol Relative error tolerance, with default of 10−3 . The default value is usually
too big, which may lead to large errors. It is recommended to set it to
3 × 10−14

FixedStep Fixed-step simulation mode, with default 'auto'

InitialState Initial states


14 StopTime Stop time, with default of 10, and can be assigned to other values; another
parameter, StartTime, with default 0

SaveFormat Return argument data type, with default 'Dataset', recommend to use
'Array'

OutputVariables Output variable signals, with default 'ty', meaning to return time vector
and output port signals. If states are also expected, set to 'txy'

PreLoadFcn When the model is opened, call this function automatically; Function
PostLoadFcn for post-processing tasks

Solver The default algorithm of 'VariableStepAuto', for automatically


selected algorithm. It can be set to other algorithms such as 'ode45',
'ode15s' and so on
14.1 · Command-Line Methods in Simulation
425 14
>> open_system('c13mmove'); % open model, or the parameters cannot be assessed
set_param(gcs,'PreLoadFcn','g=9.81;','RelTol','3e-14','AbsTol','eps');


14.1.2 Invoke Simulation Process with MATLAB


In the previous presented topics, the simulation process can be initiated by pressing
the Run button, in the Simulink toolbar. This method is simple and straightforward,
while there are also limitations. For instance, if the simulation process is embedded
into the optimization task, it is not a good choice to initiate the process each time by
pressing the button. Command-driven simulation processes are expected instead.
If the input and output data type setting in 7 Sect. 13.3.2 is used, the sim()
function in MATLAB invokes Simulink process, and to obtain simulation results.
The syntax of the function is
[t,x, y]=sim( model name,tspan,model parameters)
where tspan is used to specify simulation interval, which is the same as the one in
ode45() function. Normally it can be assigned to [t0 ,tn ] or tn , with default at t0 = 0.
Unfortunately, t0 > tn is not supported in sim() function call. The returned t is the
time vector, x is the matrix composed of internal state variable signals, while y is the
matrix composed of the signals in the output port blocks. The returned variables t
and y are the same as the variables tout and yout in the earlier presentation.

 Example 14.2
Solve again the differential equation in Example 13.5 with MATLAB commands.
Solutions A Simulink model file c13mlor2.slx for an ODE is constructed in Example
13.5. The following commands can be used to solve the ODE, and the results are identical
to those in Example 13.5.

>> [t,~,y]=sim('c13mlor2',[0,30]); % use ~ for uninterested returned arguments


plot(t,y), figure, plot3(y(:,1),y(:,2),y(:,3))


14.1.3 Input and Output Data Structures in Simulink


In 7 Sect. 13.3.2, the Single simulation output option was discussed. If it is checked,
sim() function returns only one argument. The data structure of this argument is
Simulink.SimulationOutput. Under specific circumstances, such as the case in par-
allel simulation to be presented next, this data structure is the only supported one.
Similarly, the input information can also be provided in the variable in Simulink.
SimulationInput data structure. The data structures were initially proposed in
MATLAB version R2017a. In the new versions, the default setting is to use these
data structures. In this section, the data structures and their applications are pre-
sented.
426 Chapter 14 · More on Simulink Modeling and Simulation

Simulink.SimulationInput data structure describes all the simulation para-


meters in one variable. A simulation input object can be set up directly with
the commands. Examples are used next to demonstrate the creations of such an
object.

 Example 14.3
For the Simulink model in Example 13.3, display the input object.
Solutions Call function Simulink.SimulationInput() directly, the input object in can
be obtained. When calling such a function, there is even no need to open the c13mmove.slx
model.

>> in=Simulink.SimulationInput('c13mmove') % create an object for the input


When the input object is established, the in variable is displayed as follows:

SimulationInput - with properties:


ModelName: 'c13mmove1'
InitialState: [0x0 Simulink.op.ModelOperatingPoint]
ExternalInput: []
ModelParameters: [0x0 Simulink.Simulation.ModelParameter]
BlockParameters: [0x0 Simulink.Simulation.BlockParameter]
Variables: [0x0 Simulink.Simulation.Variable]
PreSimFcn: []
PostSimFcn: []
UserString: ''
It can be seen from the above display that the input object includes the adjustable block
parameters BlockParameters and the model parameters ModelParameters. 

The model parameters and variable parameter values can be directly modified by
the functions setModelParameter() and setVariable(). These functions may only
modify one parameter at a time. The variables are the actually used variable names
in the model. For instance, the variable g in the model in Example 13.3. The model
14 parameters are those in the Simulink model. The commonly used model parameters
may refer to . Table 14.2.
With the in variable, the command out=sim(in) initiates the simulation process.
The returned argument out is the output object. Even though the Single simulation
output option is unchecked, the output data structure is still returned.

 Example 14.4
Consider the simulation problem in Example 13.3. The gravity acceleration on the Moon
surface is 1.63 m/s2 . If the stop time is set to 20 s. Solve the parabolic problem on the Moon
surface.
Solutions Function setVariable() can be used to set the value of the variable g to 1.63.
Function setModelParameter() can then be used to set StopTime. Note that in the current
version, the former function specifies the value, while the latter one specifies the values in
strings. It seems that the formats are not unified. After parameter setting, function sim()
14.1 · Command-Line Methods in Simulation
427 14
can be called to initiate the simulation process, and the results can finally be represented in
curves.

>> in=Simulink.SimulationInput('c13mmove'); % create the input object


in=in.setVariable('g',1.63); % set variables in values
in=in.setModelParameter('StopTime','20'); % set stop time in a string
in=in.setModelParameter('SaveFormat','Array'); % set the data type for yout
out=sim(in); plot(out.tout,out.yout) % start simulation, draw the curve


14.1.4 Parallel Simulation


Function parsim() provided in MATLAB can be used to carry out simulation pro-
cesses of several models in a parallel way. If in is a vector of several models, the
out=parsim(in) command initiates parallel simulation mechanism directly, and
the results of the models are returned in the vector out. An example is given next to
demonstrate the parallel simulation method, and the efficiency of parallel simulation
is assessed.

 Example 14.5
Consider again the parabolic problem in Example 13.3. The gravity accelerations on dif-
ferent planets are provided in . Table 14.3. Use parallel simulation method to find out
the displacement of the object on different planets, in 20 s. Assess the efficiency of par-
allel simulation. The computational load is deliberately increased, where fixed-step simu-
lation algorithm is selected, with step size of h = 0.00001. The model is saved in the file
c14mmove.slx.
Solutions The gravity accelerations in the above table can be expressed in a vector g 0 .
Then nine models can be established in a loop structure. The in model vector can then
be created. Initiate the simulation process, the parallel simulation mechanism is invoked
automatically. The total execution time for the simulation process is 14.75 s.

>> g0=[9.81,1.63,3.7,8.87,3.69,20.87,7.21,8.43,10.71]; % gravity accel.


for i=1:length(g0) % set up the model vector in in a loop
in1=Simulink.SimulationInput('c14mmove'); % create the model objects
in1=in1.setVariable('g',g0(i)); in(i)=in1; % modify the variable values
end
tic, out=parsim(in); toc % parallel simulation

. Table 14.3 The gravity accelerations on different planets

Planet Earth Moon Mercury Venus Mars Jupiter Saturn Uranus Neptune

Gravity 9.81 1.63 3.7 8.87 3.69 20.87 7.21 8.43 10.71
acceleration
(m·s−2 )
428 Chapter 14 · More on Simulink Modeling and Simulation

If ordinary simulation is carried out in the loop structure, the time elapse is increased to
21.97 s. It can be seen that for simulation problems with heavy computational load, parallel
simulation method can be adopted.

>> tic, for i=1:length(g0), out(i)=sim(in(i)); end, toc




14.2 Accurate and Fast Simulation


In this section, some theoretical issues in simulation are presented, including the
detections of zero-crossing points and algebraic loops. Solution methods are also
illustrated. Besides, fast restart simulation mode is introduced, such that the sim-
ulation efficiency can be boosted for repeated executions for the same Simulink
model.

14.2.1 Zero-Crossing Detection


Zero-crossing is an important concept in system simulation and many other areas.
Consider a signal u(t), if at the kth time instance tk , the signal value u(tk ) > 0, while
at the next time instance tk+1 , u(tk+1 ) < 0, then in the time interval (tk , tk+1 ), u(t)
signal crosses zero at least once. The point tξ at which the curve travels through zero
is known as the zero-crossing point. In order to perform accurate simulation, the
zero-crossing point tξ must be found first, otherwise inevitable errors may occur. An
example is given next to demonstrate the zero-crossing behavior, and the necessity
and cost in zero-crossing detection are illustrated.

 Example 14.6
Draw the curve for the function y = | sin t2 |, where t ∈ (0, π).
Solutions Select a step size T = 0.02, the following MATLAB commands draw the function
curve, as shown in . Fig. 14.1a:
14
>> t=0:0.02:pi; y=abs(sin(t.^2)); plot(t,y)
It is found obviously that the curve at certain points is wrong. For instance, at points
A, B and C near zero, the function should travel to zero first, then increases from zero.
The converting point should not be at the suspended A. If the time at which the function
value reaches 0 is found first, then insert it into the t vector, the problem can be solved
successfully. The method for finding point A is the so-called zero-crossing detection.
If there is a mechanism to find the zero-crossing points, for instance, with the following
statements to find the zero-crossing points first, they can be inserted into the time vector,
and the curve shown in . Fig. 14.1b can be found. It can be seen that if the zero-crossing
detection problem is solved relatively well, the curve obtained is correct.

>> f=@(x)abs(sin(x^2)); more_sols(f,zeros(1,1,0),[0,pi])


t0=X(:); t0=t0(t0>0 & t0<pi); % zero-crossing points in the interested region
t=sort([t,t0']); y=abs(sin(t.^2)); plot(t,y) % detect then draw the plot
14.2 · Accurate and Fast Simulation
429 14

1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3
(a) without zero-crossing detection
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3
(b) with zero-crossing detection

. Fig. 14.1 The zero-crossing demonstration for function y = | sin t2 |

In the variable-step algorithms in solving ODEs, if the error tolerance is set small
enough, the zero-crossing points can be equivalently detected. However with fixed-step
algorithms, the zero-crossing points are not ensured, therefore the problem demonstrated
in . Fig. 14.1a may occur. It can be seen that, variable-step algorithms with small error
tolerance are essential in solving exactly simulation problems. 

Under default setting, most of the Simulink blocks carry out zero-crossing detec-
tion facilities automatically. Therefore it is not recommended to alter such settings.
The cost of invoking zero-crossing detection facilities is that the simulation speed
may be reduced. This is because that near the zero-crossing points, algebraic equa-
tions may be solved automatically in each simulation step, which in turn slow down
the simulation process. If the requirement for simulation accuracy is not very high,
only approximate simulation is expected, the zero-crossing detection facilities can be
disabled, so as to speed up simulation process.
430 Chapter 14 · More on Simulink Modeling and Simulation

14.2.2 Algebraic Loop Processing


An algebraic loop indicates the phenomenon that, within a simulation loop, if the
output signal of one block or a group of blocks depends upon its input signal, at the
same time, the input signal depends also upon its output signal. It means that within
each simulation step, the algebraic equation involved should be solved once. Since the
algebraic equation solution is time-consuming, the computational load in the simu-
lation models with algebraic loops is significantly increased. In this section, algebraic
loop phenomenon is demonstrated through examples, and an effective method of
algebraic loop avoidance is proposed.

 Example 14.7
Consider the simple linear feedback system model shown in . Fig. 14.2a, set up its Simulink
model, and observe the algebraic loop in the model.
Solutions For this particular model, if the orders of numerator and denominator are equal,
each time when computing signal y(t), the input signal u(t) to the block must be used,
while when computing u(t) = r(t) − y(t), signal y(t) must be known first. This may lead
to a paradox. The paradox is the so-called algebraic loop phenomenon. In real simulation
processes, if algebraic loops are encountered, the related algebraic equation should be
solved once, in each simulation steps, to determine the consistent signals u(t) and y(t).
The Simulink model for the given system can be established with low-level blocks, as
shown in . Fig. 14.2b. Start the simulation process, a warning message appears in the
command window “Block diagram 'c14malg1' contains an algebraic loop. Use com-
mand Simulink.BlockDiagram.getAlgebraicLoops('c14malg1') to check the alge-
braic loop information, or use sldebug('c14malg1') for debugging. To suppress the
warning message, the Algebraic loop option should be set to none”.
Although there exists an algebraic loop, and the warning message is displayed, it can
be ignored, since it is not an error message. The Simulink mechanism calls the embedded
algebraic equation solver in the simulation process, and the solutions can be found. The
total time elapse is relatively high. 

For this particular example, the formula G1 (s) = G(s)/(1 + G(s)) computes the
equivalent model, and the result is G1 (s) = (s+3)/(2s+4). If block G1 (s) is used in the
14 Simulink model itself, the algebraic loop is completely eliminated. Unfortunately, the
algebraic loops in most systems cannot be eliminated in this way. Simulink mechanism
is recommended to execute the simulation process. If only warning messages are
displayed, it can be ignored. If error messages in Simulink are displayed, and the
simulation process cannot be completed, approximate methods should be introduced
instead to eliminate algebraic loops.

( ) ( ) +3 ( )
− +1

(a) feedback system (b) simulation c14malg1.slx)

. Fig. 14.2 A simple feedback system model


14.2 · Accurate and Fast Simulation
431 14
Consider again why the model in . Fig. 14.2a may lead to an algebraic loop, then
discussions are made on how to eliminate approximately the algebraic loops. In the
computing process in . Fig. 14.2a, since the computation of y(t) needs the known
signal u(t), while compute u(t) also needs the known signal y(t). Algebraic loop is the
involved. If the simultaneous relationship is involved, when computing signal u(t),
the signal y(t) can be approximated, such that the algebraic loops can usually be
eliminated. How to generate approximate y(t) signal? Add a tiny delay to y(t) is an
obvious choice. Unfortunately, experiment shows that this may lead to even larger
errors [1]. An alternative is to append a low-pass filter 1/(Ts + 1) to the y(t) signal,
to generate signal y1 (t). When computing u(t), signal y1 (t) is used rather than y(t).
The algebraic loop can be eliminated. If the value of T is much smaller than the time
constant in the system, the actions in the algebraic loop can be completely ignored.

 Example 14.8
Introduce a low-pass filter to eliminate the algebraic loop in Example 14.7, and assess the
approximation results.
Solutions The differential equation can be derived from the equivalent transfer function
model.
2y (t) + 4y(t) = u (t) + 3u(t), y(0) = 0.5,
where u(t) is a step function or a Heaviside function. In this way, the analytical solution to
the ODE can be found directly with the following statements:

>> syms t y(t); u=heaviside(t);


y0=simplify(dsolve(2*diff(y)+4*y==diff(u)+3*u, y(0)==0.5))
and the analytical solution of the output signal is

1 −2t 3 3 3
y0 (t) = e + sign (t) − e−2t sign (t) + .
8 8 8 8

Appending a transfer function block to the system in . Fig. 14.2b, with numerator 1
and denominator [T ,1], the Simulink model in . Fig. 14.3 is constructed.
If the filter constant is set to T = 10−6 and invoke the simulation process, the simula-
tion result can be obtained. Theoretical values are also superimposed in . Fig. 14.4. It is
apparent that the two curves are almost identical, albeit there exists discrepancy at the very
beginning.

>> T=1e-6; tic, [t,~,y1]=sim('c14malg2'); toc % try different filter constants


y0=exp(-2*t)/8+3*sign(t)/8-3*exp(-2*t).*sign(t)/8+3/8; % exact value
plot(t,[y1 y0]) % compare theoretical and simulation result

. Fig. 14.3 The new model with low-pass filter (file name: c14malg2.slx)
432 Chapter 14 · More on Simulink Modeling and Simulation

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0
0 1 2 3 4 5 6 7 8 9 10

. Fig. 14.4 Comparisons in time responses

Due to the existence of direct feedthrough effect in the original model, the input signal
takes action at t = 0, the initial output of the system is 0.5. With low-pass filter, the
direct feedthrough effect is deliberately avoided. The output signal is changed from 0 to 0.5
gradually within a very short period, t < 10−5 . The subsequent responses are very close to
the theoretical value. The period is very short. If T is small enough, the discrepancies can
be neglected. Apart from the short period, the maximum error obtained is 4.5985 × 10−8 ,
and the total paces in simulation is 1358.

>> ii=t>1e-5; max(abs(y0(ii)-y1(ii))), length(t)


If different values of T are tried, the comparisons are made in . Table 14.4. It can
be seen that although there exists algebraic loop in the direct feedthrough, without low-
pass filter, the solutions are the best, albeit the time elapse is slightly larger. In ordinary
cases, the algebraic loops can be ignored, and let Simulink to handle algebraic equation
problems automatically. At certain circumstances, when there exist difficulties in Simulink
such that the simulation processes cannot be carried out, low-pass filters can be introduced
to eliminate the algebraic loops. It can be seen that if T is small enough, the approximation
result is satisfactory. 

14
. Table 14.4 Comparisons under different values of T

T -values Direct 10-5 10-6 10-8 10-10


feedthrough

Maximum error 1.688 × 10−14 0.067 4.599 × 10−8 4.978 × 10−10 4.497 × 10−12

Number of points 823 1501 1358 1219 1128

Time elapse 0.7232 0.3253 0.3112 0.3044 0.3245


14.2 · Accurate and Fast Simulation
433 14
14.2.3 Fast Restart Mode in Simulink Models
When the simulation process is initiated, no matter from interface actions or simula-
tion commands, it is noticed that “Compiling” is displayed on the status bar of the
model window. This is a normal phenomenon. Under default settings, the simulation
model needs compilation each time. In certain problems, the simulation process is
required to be executed repeatedly for many times. If model compilation is needed
each time, the entire time elapse may be very long. How to avoid the compilation
process each time? Fast restart mode is provided in Simulink. If there are no changes
in the structure and unadjustable parameters in the Simulink model, there is no need
to run the compilation process. Assign the adjustable parameters or variables, the
simulation process can be initiated directly, without recompilations. The assignment
of the adjustable parameters and variables is carried out in the model workspace,
rather than in MATLAB workspace.
For ordinary simulation problems, it is not worthy to pay too much attention
in the fast restart mode. It can be activated or ignored. However, if the simulation
process to be invoked repeated for a huge amount of time, for instance, if Simulink
model is embedded in an optimization or equation solution process, it is necessary to
assign the fast restart mode, such that the optimization or equation solution process
speed can be boosted significantly.

 Example 14.9
Consider the PID control system model in . Fig. 14.5a. The plant model is described
as G(s) = 1/(s + 1)5 , and the controller Gc (s) has three adjustable parameters x =
[Kp , Ki , Kd ], and the controller has actuator saturation such that |u(t)| ≤ 5. Design a
PID controller such that the following objective function is minimized:
 30
J = min t|e(t)|dt.
x 0

( ) ( ) PID ( ) plant ( )
controller model

(a) PID control system

(b) simulation c14mpid0.slx)

. Fig. 14.5 PID control system and simulation model


434 Chapter 14 · More on Simulink Modeling and Simulation

Solutions Since nonlinear behavior is involved in the controller design problem in this exam-
ple, classical optimal control strategies cannot be utilized. The controller design problem
can be converted into a numerical optimization problem. With the powerful facilities in
simulation and optimization provided in MATLAB, the problem can be solved directly.
A Simulink model in . Fig. 14.5b can be established, and the integral performance index
can be described in the model, where the controller parameters and actuator saturation are
assigned in the PID Controller block. With the simulation model, the following M-function
can be written to describe the objective function:

function y=c14mpid(x)
W=get_param(gcs,'ModelWorkspace'); assignin(W,'Kp',x(1))
assignin(W,'Ki',x(2)); assignin(W,'Kd',x(3)); % model parameters
txy=sim('c14mpid0'); y=txy.yout(end,1); % objective function evaluation
end
With the above objective function, function fminsearch() can be called, to find the
optimal PID controller parameters. Note that the fast restart mode should be activated
first, before the optimization process is invoked.

>> open_system('c14mpid0'); % open PID control system model


set_param(gcs,'FastRestart','on') % start the fast restart mode
tic, [x,f0,key,c]=fminsearch(@c14mpid,rand(3,1)), toc
txy=sim('c14mpid0'); plot(txy.tout,txy.yout(:,2))
After 11.23 s of waiting, the optimal PID controller parameters can be obtained as
Kp = 1.3363, Ki = 0.2752 and Kd = 1.8133. The closed-loop step response is shown
in . Fig. 14.6. It can be seen that the control behavior is satisfactory. It can be measured
that altogether there are 344 runs of the simulation model. When the compilation time is
bypassed each time, the total execution speed is boosted.
If no fast restart mode is not invoked, the optimization process is rather time-consuming,
and the total time elapse is 105.08 s. The designed controller is identical to the one obtained
earlier. Therefore, if fast restart mode is activated, the efficiency for dealing with such
problems can be significantly increased. 

14
1.2

0.8

0.6

0.4

0.2

0
0 5 10 15 20 25 30

. Fig. 14.6 Closed-loop step responses


14.3 · Subsystems and Block Masking
435 14
This example is a typical case study, in converting optimal controller design prob-
lem into numerical optimization problems. With such ideas, many practical problems
can be converted directly into numerical optimization problems.

14.3 Subsystems and Block Masking


In actual system modeling and simulation, complicated system structures are usually
encountered. Sometimes it may be very hard to describe the entire system within a sin-
gle low-level block diagram model. Usually it is necessary to divide the whole system
into several interconnected subsystems with independent functions. Such subsystem
structures are fully supported in Simulink. Besides, some subsystems can be masked
into reusable blocks, such that they can be used in the same way as other ordinary
Simulink blocks. Furthermore, the users may develop his own blocksets. In this sec-
tion, the construction and applications of subsystems are illustrated, and the block
masking techniques are also presented.

14.3.1 Subsystems
To create a new subsystem, the input and output ports should be assigned first.
The input ports can be represented by the In block in the Sources group, while the
output port can be described by the Out block in the Sinks group. These blocks
are also available in the Ports & Subsystems group, and the blocks are identical.
The internal structure of the subsystem can be designed arbitrarily in between the
input and output ports. Besides, subsystem models can also be extracted from an
existing complicated model. In this section, the subsystem construction and extraction
methods are demonstrated with examples in this section.

 Example 14.10
PID controllers are the most widely used controller type in industrial control systems [2].
The mathematical form of a PID controller is

Ki Kd s
Gc (s) = Kp + + . (14.1)
s Kd s/N + 1

Set up a low-level PID controller model and build it into a subsystem block.
Solutions There is one input port and one output port in a PID controller. The model in
between the two ports is the transfer function Gc (s). Therefore the low-level PID controller
model can be established, as shown in . Fig. 14.7a.
To select all the blocks in the model, or press Ctrl+A keys, and select Create Subsystem
from Selection from shortcut menu, a subsystem block can be established, as shown in
. Fig. 14.7b. It can be seen that on the icon of the subsystem block, the internal structures
are depicted in shallow color. The prompts are helpful in Simulink modeling and model
maintaining.
Double click the subsystem block, a new model window is displayed, showing the internal
structures in . Fig. 14.7a. The user may edit or modify the subsystem model within the
model window. 
436 Chapter 14 · More on Simulink Modeling and Simulation

. Fig. 14.7 PID controller and its subsystem

14.3.2 Icon Design of Masked Blocks


The creation and manipulation of subsystem blocks have been presented earlier. In
normal cases, the commonly used parts in a large-scale system can be built into
subsystems, such that the modeling structure looks simple and neat. The maintaining
of the system models thus built is made simpler.
To mask a block, it means to hide all the internal structure of the subsystem. If the
masked block is double clicked, a parameter dialog box is displayed instead, allowing
the user to specify parameters independently in the masked block.
If you want to mask a model, the first thing to do is to convert it into a subsystem
block. Select the subsystem block, click the right mouse button to open the shortcut
14 menu, the Mask menu items are listed as shown in . Fig. 14.8.
Select Create Mask item from the menu, the mask editor window is opened, as
shown in . Fig. 14.9. In the editor window, there are four panes, labeled as Icon &
Port, Parameter & Dialog, Initialization and Documentation. Each pane corresponds
to a labeled page. The current page is used to design the icon for the masked block.

. Fig. 14.8 Block masking menu items


14.3 · Subsystems and Block Masking
437 14

. Fig. 14.9 Mask editor window

The commands for designing the icon can be specified in the Icon drawing commands
edit box on the left.
Three methods are provided to design icons:
(1) Draw curves. Curves or colored patches can be drawn in the icon. MATLAB
function plot() draws piecewise segments. Note that the plot() command here is
not a genuine MATLAB plot() function. Its syntax is plot(x 1 , y1 ,x 2 , y2 ,· · · ), which
is not the same as the plot() function in MATLAB, because line-type specifications
and many other settings are not allowed.
Besides, function patch() draws colored patches, with the syntax
patch([x1 ,x2 ,· · · ,xn ,x1 ],[y1 ,y2 ,· · · ,yn ,y1 ], color)
where the closed path is specified with the two vectors, while color is set to reserved
color such as 'red', or in vectors such as [r,g,b], whose components are within [0, 1]
interval.
When drawing plots or text, the foreground color can be specified with color
(color). The subsequent drawing commands use the specified color.
(2) Text description. Command disp() superimposes text on the icon. Multiple-
line format for text is allowed, where line breaks are indicated by \n options. In the
new versions, text() function allows the user to specify the location to write the
strings, with the syntax text(x,y,strings), where (x, y) is the location coordinates,
whose scale is the same as the ones in plot() commands.
(3) Image file. Command W = imread(file name) provided in MATLAB allows
the user to load an image file into MATLAB workspace. Function image() can then
be used to display the image as the icon.

 Example 14.11
Try different methods to design the icon for the masked PID controller block.
Solutions To draw a “smiling face” as the icon, the following MATLAB commands draw
the four curves, where the unit circle describes the face, and two smaller ones with radius
0.1 for eyes. They are centered, respectively, at (−0.4,0.2) and (0.4,0.2). A semi-oval on the
bottom for mouth. The right eye is depicted by patch() function in red. The designed icon
is shown in . Fig. 14.10a.

t=linspace(0,2*pi,30); t1=linspace(0,pi,30);
plot(cos(t),sin(t),-0.4+0.1*cos(t),0.2+0.1*sin(t))
438 Chapter 14 · More on Simulink Modeling and Simulation

. Fig. 14.10 Implementation of the icon drawing commands

patch(0.4+0.1*cos(t),0.2+0.1*sin(t),[1,0,0]) % fill in red


plot(0.6*cos(t1),-0.1-0.4*sin(t1)) % default black curve
Note that, if the commands are specified in the Icon drawing commands edit box in the
earlier versions, error messages may be displayed, since the assignment commands are not
supported. It can be normally executed in the new versions.
If the following command is issued, a straight line is added to the smiling face:

plot([-1,1],[1,-1]), plot(-1.5,-1.5), plot(1.5,1.5)


A straight line is added to the original smiling face. Besides, with the last two statements,
the range of the axis is set to −1.5 ≤ x, y ≤ 1.5, and the icon is shown in . Fig. 14.10b.
Note that, in the icon design environment, hold on and line() commands cannot be used,
otherwise there is no plot displayed. Function plot() command here superimposes new
plots on the icon.
If disp('PID\nController') command is specified, the text string is superimposed
to the icon, as shown in . Fig. 14.10c. If command image(imread('tiantan.jpg'))
is issued, the tiantan.jpg file in loaded, and the image is displayed directly on the icon,
covering all other plots and text, as shown in . Fig. 14.10d. 

14.3.3 Block Masking


The icon design commands only alter the appearance of the masked block. The design
of parameter dialog box for the masked block is more important. The aim in masking
subsystem blocks is to make the block an independent one, with adjustable parame-
14 ters, without affecting other blocks. The parameter dialog box design can be carried
out in the mask edit dialog box. Consider the Transfer Fcn block studied earlier. Dou-
ble click the block icon, a parameter dialog box is opened, prompting the user to
provide numerator and denominator edit boxes. The purpose of parameter dialog
box design is to set up the relationship between parameter dialog box and the inter-
nal variables in the block. Parameter dialog box design is the major technique in
the masked block design. In this section, the parameter dialog box design method is
presented first, and then examples are used to illustrate the design methods.
Selecting the Parameter & Dialog pane in mask editor in . Fig. 14.9, the new mask
editor is displayed as shown in . Fig. 14.11. The window is divided into left, middle
and right zones, referred to as Controls, Dialog Box and Property Editor zones. Various
controls are provided in the Controls zone, including Edit, Popup, ListBox and so on.
The selected controls can be dragged into the middle zone, to complete parameter
dialog design. The design method is illustrated next in the example.
14.3 · Subsystems and Block Masking
439 14

. Fig. 14.11 Parameter dialog box design and zones

 Example 14.12
Design a parameter dialog box for the PID controller block in Example 14.11.
Solutions Before the design of the dialog box, the essential parameters are needed. It can
be seen from (14.1) that, PID controller has four parameters, Kp , Ki , Kd and N. The first
three parameters can be specified by edit boxes, while the last one by a listbox. Drag the
Edit control on the left to the Parameters column in the middle zone, and edit box is added
to the parameter list. In this way, three edit boxes and one listbox can be created in the
middle zone, as shown in . Fig. 14.12.
Select the first parameter #1, on the right zone, click the Name edit box, the variable
name can be specified. In the Prompt edit box, prompt information should be entered. In
the Value edit box, the default value of the variable should be filled in. The design for the
first parameter is then completed. The other three parameters can be designed in a similar
way, as shown in . Fig. 14.13. When designing the listbox, click the button, the list
options can be specified in the edit box.
Some commands which are to be executed when the model is opened can be specified in
the Initialization pane. In commands in the icon design, when the initial variables are used,

. Fig. 14.12 Prototype in the parameter dialog design


440 Chapter 14 · More on Simulink Modeling and Simulation

. Fig. 14.13 Parameter dialog box design

the Run Initialization listbox on the lower left corner in the dialog box shown in . Fig. 14.9
should be set from the default Off to On, otherwise the initial variables cannot be recognized
in the icon design commands.
After specifying all the items, click OK button in the mask editor window, the design pro-
cess is completed. Click the icon of the masked block, a parameter dialog box in . Fig. 14.14
is opened, allowing the user to specify PID controller parameters in the block. 

14.4 S-Function Programming and Applications


In the Simulink modeling process, the user may find that some complicated math-
ematical models cannot be expressed easily with low-level blocks, especially for the
mathematical models which need flow control or piecewise functions, programming
must be introduced in describing the entire simulation model.
In fact, the MATLAB Function and Interpreted MATLAB Function blocks discussed
earlier can only be used to describe the mathematical formula like y = f (u),
which is referred to as static functions. To describe the dynamic relationship, such
as differential or difference equations, S-function programming should be adopted.
Besides, since additional parameters are not allowed in the static function modeling
method discussed earlier, S-functions can be used instead. In this section, state space
14

. Fig. 14.14 Parameter dialog box of a block


14.4 · S-Function Programming and Applications
441 14
mathematical models are presented first, followed by the fundamental structures of
S-function programming. Examples are used to demonstrate the programming of
S-function blocks.

14.4.1 State Space Descriptions


The classical state space expressions are either in continuous or in discrete form. In
many applications, the states may include not only continuous states, but also discrete
ones. Such system models are referred to as hybrid systems.
Assume that the state vector of the system is x(t) = [x c (t), x d (t)], where x c (t) is
a collection of continuous states, while x d (t) contains discrete states.
The continuous state space model of the hybrid system is

x c (t) = f (t, x(t), u(t)), (14.2)

while the discrete state space model is

x d (t + 1) = g(t, x(t), u(t)), (14.3)

The output of the system can be written as

y(t) = h(t, x(t), u(t)). (14.4)

14.4.2 S-Function Structures


The complicated blocks can be described in the format of S-functions using MAT-
LAB. If the original system model can be described by state space expressions, it is
recommended to describe it with S-functions.
The introductory statement of S-function is
function [sys,x 0 ,str,ts,SSC]=function name(t,x,u,flag,p1 ,p2 ,· · · )
where function name is also the name of S-function file. The input arguments t,
x and u are, respectively, time, states and input signals. The argument flag is an
indicator, described in . Table 14.5. The values 4 and 9 are seldom used for flag.
The returned arguments for different values of flag are also presented in the table.
Additional parameters p1 , p2 , · · · can be used in S-functions. These parameters should
be assigned in the parameter dialog box of S-function blocks. Argument SSC describes
the creation and saving methods of the states, and it is recommended to set it to
DefaultSimState, or ignore the argument. The other returned argument values are
also presented in . Table 14.5.
It can be seen from . Table 14.5 that the tasks of S-functions are to call relevant
response functions according to the values of flag argument. The tasks are suitable
to be implemented with switch structure. The main framework of S-function is a
universal one as follows:
442 Chapter 14 · More on Simulink Modeling and Simulation

. Table 14.5 The flag values and response functions

Values Description Recommended function name Returned arguments

0 Initialization mdlInitializeSizes sys returns initialization


parameters, x 0 , str, ts as their
definitions

1 Continuous mdlDerivatives sys returns the derivative of the


states continuous states

2 Discrete states mdlUpdate sys returns the discrete states


at the next time instance

3 Compute output mdlOutputs sys returns the output

4 Next time hit mdlGetTimeOfNextVarHit sys returns the next time hit

9 Stop simulation mdlTerminate sys is an empty matrix

function [sys,x0,str,ts,SSC]=function name(t,x,u,flag,p1,p2,...)


switch flag
case 0 % call the initialization function
[sys,x0,str,ts,SSC]=mdlInitializeSizes(input arguments);
case 1 % compute the derivatives of the continuous states
sys=mdlDerivatives(t,x,u,input arguments);
case 2 % compute the discrete states at the next time instance
sys=mdlUpdate(t,x,u,input arguments);
case 3 % compute the output signals of the block
sys=mdlOutputs(t,x,u,input arguments);
case 4 % the simulation time at the next hit
sys=GetTimeOfNextVarHit(t,x,u,input arguments);
case 9 % process of terminating simulation
sys=mdlTerminate(t,x,u,input arguments);
otherwise % handling possible errors
14 error(['Unhandled flag = ',num2str(flag)]);
end
It should be pointed out that the input arguments for each response function are
assigned accordingly. Besides, the given function names are just recommendations, it
can be assigned to other names. The users may select arbitrary names, as long as the
names are consistent in the caller and in the response functions. For simple problems,
it is even not necessary to write response functions. The response commands can be
embedded in the main framework of the S-function. Examples are given next for
demonstrations.
14.4 · S-Function Programming and Applications
443 14
14.4.3 S-Function Mechanism
The execution of the S-function block in a Simulink model is as follows. At the
beginning of simulation process, flag is set to 0, to initiate simulation process. Then,
flag is set to 3 to compute the output signals. After that, flag is set to 2 and 1,
respectively, to update the discrete and continuous states. In the next simulation step,
the flag is set in turn to 3→2→1 again. Repeat the simulation in each simulation
step like this, until the end of the simulation process.

14.4.4 S-Function Response Functions


Since S-function is written to respond to the changes of the flag values, switch struc-
ture is the most suitable one, which is the main framework in the S-function. The
framework for the S-function responses is demonstrated first. An introductory pre-
sentation is given here first. Later, examples are given to illustrate the S-function
programming methods.

1. Initialization Parameters
Command sizes=simsizes can be called first to load the default initialization tem-
plate sizes. The returned sizes is in fact a structured variable, whose commonly
used members are given in . Table 14.6. The members in sizes should be assigned
due to actual applications.
With the assigned sizes, function sys=simsizes(sizes) assigns it to sys. Apart
from sys, other initialization variables such as the initial state x 0 , description variable
str and sample time variable ts can be returned, where ts is a matrix with two
columns. The sample time for continuous system is 0, and for discrete systems with
one sample time, it is set to [t1 ,t2 ], where t1 is the sample time and t2 is the offset,
normally set to 0. If t1 = −1, it means that the sample time of the block inherits that
of its input signal.

. Table 14.6 Commonly used initialization parameters

Member names Descriptions

NumContStates Number of continuous states

NumDiscStates Number of discrete states

NumInputs Number of input signals

NumOutputs Number of output signal

DirFeedthrough Indicator whether direct feedthrough is involved. This parameter is


important in determining the orders the blocks are executed. If input u is
explicitly contained in output, it is set to 1, otherwise it is zero

NumSampleTimes Number of sample times, and S-function support multiple sample time
cases
444 Chapter 14 · More on Simulink Modeling and Simulation

2. Update States
The derivatives of the continuous states are evaluated from the mdlDerivatives func-
tion, while the discrete states at the next time instance are computed from mdlUpdates
function. The results of these two functions are returned with sys argument. If hybrid
systems are simulated, the two functions should be written for continuous and discrete
states, respectively.

3. Compute the Output Signals


The output signals can be computed in the mdlOutputs function, and the results are
still returned in the argument sys.

14.4.5 S-Function Examples


A template file sfuntmpl.m is provided in Simulink. If necessary, it can be copied
into your working folder, and start writing S-functions from it.
In fact, the structure of S-functions is very simple and normalized. The block
parameters can be assigned accordingly, if the numbers of inputs, outputs, continuous
states and discrete states are known. The additional parameters to the block can also
be decided according to the actual need. Examples are given next to illustrate the
S-function programming methods.

 Example 14.13
Consider the given continuous state space model
 
x (t) = Ax(t) + Bu(t)
y(t) = C x(t) + Du(t),

where A, B, C and D are constant matrices whose sizes are, respectively, n × n, n × p, q × n


and q × p. It is known that the numbers of inputs and outputs are p and q, respectively.
Design a universal continuous state space block in an S-function.

14 Solutions Continuous state space equation can be directly implemented with the State-Space
block in the Continuous group. Here we just want to use it as an example to illustrate the
S-function programming problem. It is known from the given model that the additional
parameters can be selected as A, B, C, D matrices, and the initial state vector x 0 . Therefore,
the main framework of the S-function can be written as

function [sys,x0,str,ts,SSC]=c14mss(t,x,u,flag,A,B,C,D,x0)
switch flag
case 0, [sys,str,ts,SSC]=mdlInitializeSizes(A,B,C,D);
case 1, sys=A*x+B*u; % for simple problems no need for response function
case 3, sys=C*x+D*u; % compute the output signal directly
case {2,4,9}, sys=[]; % unused flag values
otherwise, error(['Unhandled flag = ',num2str(flag)]);
end, end
Since the system is a continuous one, there is no need to write a response function for
case 2. Besides, since the state derivatives and output signals can be computed directly
14.4 · S-Function Programming and Applications
445 14
with very simple command, there is no need to write dedicated response functions as well.
Just embed the statements into the main framework.
Now, let us consider initialization response function programming problem. The number
of continuous state is n, and when A matrix is known, the number can be extracted with
size() function. The number of discrete states is zero. The numbers of inputs and outputs
are, respectively, p and q, which can be extracted with size() function. In the initialization
process, the decision for the direct feedthrough value is crucial. It is known from the output
equation y = C x + Du that, if D is a nonzero matrix, which means that y depends upon
u explicitly. The value of direct feedthrough can be set to 1, otherwise it is 0. Therefore the
following initialization function can be written:

% when flag is 0, start the initialization problem


function [sys,str,ts,SSC]=mdlInitializeSizes(A,B,C,D)
sizes = simsizes; % load the initialization template
sizes.NumContStates=size(A,1); % number of continuous states
sizes.NumDiscStates=0; % number of discrete states
sizes.NumOutputs=size(C,1); % number of outputs
sizes.NumInputs=size(B,2); % number of inputs
sizes.DirFeedthrough=any(D(:)~=0); % set the identifier for direct feedthrough
sizes.NumSampleTimes = 1; % single sample time
sys = simsizes(sizes); % set up the initialization parameters
str = []; % set str to an empty one
ts = [0 0]; % set sample time to 0, continuous system
SSC='DefaultSimState'; % set as the default string
end


 Example 14.14
Construct the fractal tree model in Example 5.3 with Simulink. For simplicity, the fractal
tree model is given below:


⎪ x = 0, y1 = y0 /2, γi < 0.05
⎨ 1
x1 = 0.42(x0 −y0 ), y1 = 0.2 + 0.42(x0 +y0 ), 0.05 ≤ γi < 0.45

⎪ x = 0.42(x0 +y0 ), y1 = 0.2 − 0.42(x0 −y0 ), 0.45 ≤ γi < 0.85
⎩ 1
x1 = 0.1x0 , y1 = 0.2 + 0.1y0 , otherwise,

where γi is the pseudorandom number, uniformly distributed in the interval [0, 1]. This
signal can be regarded as the input signal of the block.
Solutions If S-function is needed in the modeling, the discrete state variables can be selected
as z1 (k) = x0 and z2 (k) = y0 . In the recursive model, it is regarded that z1 (k + 1) = x1 and
z2 (k + 1) = y1 . Therefore the original expression is in fact the discrete state space model.
The state space model is a piecewise one. Depending on the four cases, four different state
space models can be established. For instance, under the third condition, the discrete state
space model is written as
 
z1 (k + 1) 0.42(z1 (k) − z2 (k))
= .
z2 (k + 1) 0.2 + 0.42(z1 (k) + z2 (k))
446 Chapter 14 · More on Simulink Modeling and Simulation

For simplicity, it is not necessary to list all the other state space models, since in real
programming, the discrete state space models are not actually needed. It can be seen that
the low-level modeling for such a system is rather complicated. It is especially suitable to
use MATLAB language to implement the equations, with the if-elseif control structure.
To use S-function format, the numbers of inputs, outputs, continuous states and discrete
states must be obtained. For this particular model, the number of discrete states is 2, while
the number of continuous states is 0. The input signal is γi , which means that there is one
input signal. The outputs are the states, thus there are two outputs. Besides, since input is
not explicitly contained in the output equation, the direct feedthrough indicator is 0. It can
be seen that since the initial states are assigned by the user, z 0 can be used as the additional
parameter. Therefore the universal framework of the S-function can be written as

function [sys,z0,str,ts,SSC]=c14mtree(t,z,u,flag,z0)
switch flag
case 0, [sys,str,ts,SSC]=mdlInitializeSizes;
case 2, sys=mdlUpdates(z,u); % response function for discrete state updates
case 3, sys=z; % compute the output, no need for a function
case {1, 4, 9}, sys = []; % unused values of flag
otherwise, error(['Unhandled flag = ',num2str(flag)]);
end, end
Note that since the output is y = z, there is no need to write a separate response function
for it. The code can be embedded in case 3. Since there are no continuous state variables,
there is no need to write response function for case 1.
With the main framework, the user should write response functions for initialization
and discrete state updates, respectively. Since the initial state vector is passed into the block
through additional parameter z 0 , there is no need to write it into the initialization function.
Therefore the initialization function can be written.

% when flag is 0, start the initialization process


function [sys,str,ts,SSC]=mdlInitializeSizes
sizes = simsizes; % load the initialization template
sizes.NumContStates=0; sizes.NumDiscStates=2; % numbers of states
sizes.NumOutputs=2; sizes.NumInputs=1; sizes.DirFeedthrough=0;
% set initial parameters
14
sizes.NumSampleTimes=1; sys=simsizes(sizes);
str=[]; ts=[-1 0]; SSC='DefaultSimState'; % inherits the sample time
end
Note that, at the beginning of the initialization function, simsizes() function should be
called first to load the initialization template. Then the members of the template should
be assigned accordingly. After modification, function simsizes() should be called again
to pass the results back to sys. The sample time can be set to −1, meaning to inherit the
sample time of its input signal.
The function below is the discrete state update response function. For simplicity, the
current states can be extracted in variables x0 and y0 . Depending on the values of the input
signal u, that is, γi , conditional statements compute directly the updated state variables,
and the vector is returned in variable sys. It can be seen that the programming here is more
straightforward. It is not necessary to write out the standard form of the discrete state space
equations.

function sys=mdlUpdates(z,u)
x0=z(1); y0=z(2); % get the current state variables
14.4 · S-Function Programming and Applications
447 14
if u<0.05, sys=[0; 0.5*y0];
elseif u<0.45, sys=[0.42*(x0-y0); 0.2+0.42*(x0+y0)];
elseif u<0.85, sys=[0.42*(x0+y0); 0.2-0.42*(x0-y0)];
else, sys=[0.1*x0; 0.1*y0+0.2]; end
end
S-function file c14mtree.m can be created, a simulation model shown in . Fig. 14.15a
can be established, where, in the Uniform Random Number block, the lower and upper
bounds can be set to 0 and 1, respectively. The sample time can be assigned arbitrarily,
since for this particular example, the simulation results are independent of the sample time.
Double click the S-Function block, the parameter dialog box shown in . Fig. 14.15b is
displayed. The S-function file name can be filled in the dialog box, and the initial state
vector can be assigned into the S-function parameters edit box. Simulation studies can be
carried out for the fractal tree problem.
Initiate simulation process, the command plot(yout(:,1),yout(:,2),’.’) draws the
simulation results, and the plot obtained is identical to the one in Example 5.3. 

 Example 14.15
The mathematical model of tracking differentiator is [3]

x1 (k + 1) = x1 (k) + Tx2 (k)
(14.5)
x2 (k + 1) = x2 (k) + T fst(x1 (k), x2 (k), u(k), r, h),

where T is the sample time, u(k) is the input signal at the kth time instance, r is the
parameter determining the tracking speed and h is the parameter regarding the filtering
capacities. Function fst() can be evaluated from the following formulas:

δ = rh, δ0 = δh, y0 = x1 (k) − u + hx2 (k), a0 = δ 2 + 8r|y0 |, (14.6)



x2 (k) + y0 /h, |y0 | ≤ δ0
a= (14.7)
x2 (k) + 0.5(a0 − δ) sign(y0 ), |y0 | > δ0 ,

(a) simulation model

(b) S-function dialog box

. Fig. 14.15 Simulink model for the fractal tree problem (file name: c14mtree1.slx)
448 Chapter 14 · More on Simulink Modeling and Simulation


−ra/δ, |a| ≤ δ
fst = (14.8)
−r sign(a), |a| > δ.
If low-level modeling method is used, the modeling may be very complicated and error-
prone [1]. Set up a simulation model with S-function.
Solutions To compute the updated discrete state variables, the variables δ, δ0 , y0 and
a0 should be evaluated in turn, and then compute a and fst. Since piecewise functions are
involved, low-level block diagram modeling is extremely complicated. With MATLAB pro-
gramming, piecewise function evaluations are very simple and straightforward. Therefore,
S-functions should be used to implement this type of models.
It can be seen from the original equations that the block has two discrete states, and
with no continuous states. There is one input signal u(k) and two output signals, which are
the states. There is one sample time T and there is no direct feedthrough. Three additional
parameters r, h and T are needed. Based on the mathematical model, it is not hard to write
the following S-function:

function [sys,x0,str,ts,SSC]=han_td(t,x,u,flag,r,h,T)
switch flag
case 0, [sys,x0,str,ts,SSC] = mdlInitializeSizes(T);
case 2, sys = mdlUpdates(x,u,r,h,T);
case 3, sys = x; % compute directly the output signal
case {1, 4, 9}, sys = []; % unused flag values
otherwise, error(['Unhandled flag = ',num2str(flag)]);
end, end
% when flag is 0, start initialization process
function [sys,x0,str,ts,SSC] = mdlInitializeSizes(T)
sizes = simsizes; % load the initialization template
sizes.NumContStates=0; sizes.NumDiscStates=2; % number of states
sizes.NumOutputs=2; sizes.NumInputs=1; sizes.DirFeedthrough=0;
sizes.NumSampleTimes=1; sys=simsizes(sizes); % initial parameters
x0=[0; 0]; str=[]; ts=[T 0]; SSC='DefaultSimState'; % default arguments
end
% when flag is 2, update the discrete states

14 function sys = mdlUpdates(x,u,r,h,T)


sys = [x(1)+T*x(2); x(2)+T*fst(x,u,r,h)];
end
function f=fst(x,u,r,h)
delta=r*h; delta0=delta*h; b=x(1)-u+h*x(2);
a0=sqrt(delta*delta+8*r*abs(b));
a=x(2)+b/h*(abs(b)<=delta0)+0.5*(a0-delta)*sign(b)*(abs(b)>delta0);
f=-r*a/delta*(abs(a)<=delta)-r*sign(a)*(abs(a)>delta);
end
Since the output signal is easy to compute, it is embedded into the main framework,
instead of write for it a response function. The piecewise functions can also be implemented
with if structure, since it is easier to understand.
The test signal is composed of two segments, that is, in (0, 2π) interval, the input
is sinusoidal signal, while in (2π, 4π) interval, triangular wave is used. The following
M-function block generates the test signal:
14.4 · S-Function Programming and Applications
449 14
function y=c14han_fun(x)
if x<=2*pi, y=sin(x); % the first segment, the sine function
elseif x<=2.5*pi, y=2*(x-2*pi)/pi; % first portion of the triangular function
elseif x<=3.5*pi, y=1-2*(x-2.5*pi)/pi;
elseif x<=4*pi, y=-2+2*(x-3*pi)/pi; end
end
Therefore, the Simulink model for the tracking differentiator is constructed, as shown in
. Fig. 14.16. Simulation results from the model can be obtained as shown in . Fig. 14.17.
The tracking signal to the original input is returned, as well as its derivative signal. It can
be seen that the tracking signal follows the input very well, and the derivative signal thus
obtained is also satisfactory. 

S-functions have natural advantages in implementing complicated state space


models. The convenience and reliability of such a modeling method is much higher
than the low-level modeling methods. It is recommended to use S-function modeling
method widely in real applications.

(a) simulation model

(b) S-function parameter dialog box

. Fig. 14.16 Tracking differentiator Simulink model (file name: c14mtd.slx)

1
0.8 tracking
signal
ative

0.6
0.4
deriv

0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0 2 4 6 8 10 12

. Fig. 14.17 Tracking and first-order derivative signals


450 Chapter 14 · More on Simulink Modeling and Simulation

 Example 14.16
Construct a staircase signal generator with an S-function.
Solutions There is no need to use any input signal for such a signal generator block. There
is no continuous nor discrete states, nor direct feedthrough. There is one output signal in
the block. There are two additional parameters: vectors tTime and yStep, to describe the
turning points of the staircase signals. The S-function should be written as follows.

function [sys,x0,str,ts,SSC]=multi_step(t,x,u,flag,tTime,yStep)
switch flag
case 0, [sys,x0,str,ts,SSC]=mdlInitializeSizes; % initialization
case 3, sys=mdlOutputs(t,tTime,yStep); % compute the output
case {1,2,4,9}, sys = []; % unused flag values
otherwise, error(['Unhandled flag = ',num2str(flag)]);
end, end
% when flag is 0, start initialization process
function [sys,x0,str,ts,SSC] = mdlInitializeSizes
S=simsizes; % load the initialization template
S.NumContStates=0; S.NumDiscStates=0; % no continuous and discrete states
S.NumOutputs=1; S.NumInputs=0; % input and output numbers
S.DirFeedthrough=0; S.NumSampleTimes=1; sys=simsizes(S); % initialization
x0 = []; str = []; ts = [0 0]; SSC='DefaultSimState';
end
% when flag is 3, compute the output signals
function sys = mdlOutputs(t,tTime,yStep)
i=find(tTime<=t); sys=yStep(i(end));
end
Since there are no states, there is no need to write response functions for case 1 and case
2. These can be treated in the same way as in case 4,9, such that the empty matrix is
written to the sys argument.


14
14.4.6 S-Function Block Masking
S-function blocks can be masked into reusable blocks. In normal cases, select the
S-function block icon, click the right mouse button, the shortcut menu appears.
Select Mask menu, the masking method discussed earlier can be used to mask the
S-function block. Since S-function contains additional parameters, the parameters
can be assigned in designing the dialog box. The block masking method for S-function
block is illustrated next through a simple example.

 Example 14.17
Mask the staircase signal generator block in Example 14.16, and design the icon for the
block.
Solutions It is known from the S-function in Example 14.16 that the block has two additional
parameters: tTime and yStep. Therefore, when designing the parameter dialog box, two
14.5 · Exercises
451 14
edit boxes are needed for the two parameters. The design of masking parameter dialog box
is illustrated in . Fig. 14.18.
Under the Initialization pane in the mask edit interface, the following commands can be
entered, to prepare the data for the icon:

ee=1e-5; n=length(tTime); tt=tTime(2:n)+ee;


y0=[yStep(1) yStep(1:n-1) yStep(2:n)];
[t0,ii]=sort([tTime,tt]); y0=y0(ii);
T=diff(t0); if isempty(T), T=10; else, T=T(end-1); end
t0=[t0 t0(end)+T]; y0=[y0 y0(end)];
where t 0 and y0 vectors can be used directly to draw the staircase plots. In the Icon & Ports
pane, the Run Initialization list box must be set to On. In the Icon drawing commands edit
box, the following commands can be specified, for drawing the staircase waveform on the
icon:

plot(t0,y0), dX=max(t0)-min(t0); dY=max(y0)-min(y0); % add certain margins


plot(min(t0)-0.08*dX,min(y0)-0.08*dY)
plot(max(t0)+0.08*dX,max(y0)+0.08*dY)
The Simulink model in . Fig. 14.19a can be created. Double click the Multi-staircase
Signal Generator block, and fill in parameters for the staircase signal parameters, as shown
in . Fig. 14.19b, the expected icon can be displayed automatically. 

14.5 Exercises
(1) Consider the van der Pol equation, with a parameter μ. Select different μ values
and carry out simulation processes. Draw the phase plane trajectory. Compare
conventional and parallel simulation proficiency.
(2) The relationship between Celsius degree c and Fahrenheit degree f is

5 9
c= (f − 32), f = c + 32.
9 5

Set up a unit conversion block, with a parameter dialog box. In the dialog box,
there is an edit box, and the listbox displays the current system. Change the
selection in the listbox, the system in the edit box can be converted from the
current system into the new system.

. Fig. 14.18 Parameter dialog box design


452 Chapter 14 · More on Simulink Modeling and Simulation

(a) simulation model

(b) parameter dialog box

. Fig. 14.19 Masked staircase signal generator block and mask edit interface (file: c14mmstep.slx)

(3) For the van der Pol differential equation y (t)+μ(y2 (t)−1)y (t)+y(t) = 0, if μ
and x(0) are selected as additional parameters, write an S-function to describe
the differential equation. Mask the block to construct a reusable Simulink block.
(4) For the Lorenz differential equation model
⎧ 
⎨ x1 (t) = −βx1 (t) + x2 (t)x3 (t)
x (t) = −ρx2 (t) + ρx3 (t)
⎩ 2
x3 (t) = −x1 (t)x2 (t) + σ x2 (t) − x3 (t),

14 if β, ρ, σ and x(0) are selected as the additional parameters, write an S-function


and mask the block. Construct a reusable Simulink block.
(5) For piecewise linear nonlinearities, assume that in the ith segment, that is, ei ≤
x < ei+1 , output signal is y(x) = ki x+bi . If the breaks e1 , e2 , · · · , eN+1 are known,
and the slops and intercepts are known as k1 , b1 , · · · , kN , bN . Use S-function
format to describe piecewise linear nonlinearities, and mask the block.
(6) Assume that for a programmable logical device (PLD) block, there are six input
signals, labeled as A, B, W1 , W2 , W3 and W4 , where Wi are the encoding signals,
whose combinations determine the logical expression of the output signal Y .
The logical relationship is presented in . Table 14.7. Write an S-function block
to implement the PLD.
(7) For the linear discrete state space model

x(k + 1) = Fx(k) + Gu(k)
y(k) = C x(k) + Du(k),
14.5 · Exercises
453 14

. Table 14.7 Logical relationship table in Exercise (6)

W1 W2 W3 W4 Y W1 W2 W3 W4 Y

0 0 0 0 0 1 0 0 0 AB

0 0 0 1 AB 1 0 0 1 A

0 0 1 0 A+B 1 0 1 0 B

0 0 1 1 AB + AB = A  B 1 0 1 1 A+B

0 1 0 0 AB 1 1 0 0 AB+AB = A⊕B

0 1 0 1 B 1 1 0 1 A+B

0 1 1 0 A 1 1 1 0 A + B = AB

0 1 1 1 A+B 1 1 1 1 1

with sample time T , write a universal S-function block. If


⎡ ⎤ ⎡ ⎤
0.2769 0.8235 0.9502 0.3816
F = ⎣ 0.0462 0.6948 0.0345 ⎦ , G = ⎣ 0.7655 ⎦ , C = [1, 0, 0], D = 0.3,
0.0971 0.3171 0.4387 0.7952

draw its step response. In the design of the S-function, if DirectFeedthrough


is set to 0, observe whether the model can still be simulated. Why? Use the
discrete state space block provided in Simulink and validate the results.
(8) Consider the discrete state space expression of Hénon attraction model, with
initial states x0 = 0, y0 = 0.

xk+1 = 1 + yk − 1.4xk2
yk+1 = 0.3xk .

Use S-function format to describe the model and draw the Hénon attraction
plot.
(9) The mathematical model of the third-order extended state observer is [3]

⎨ v1 (k + 1) = v1 (k) + T [v2 (k) − β01 e(k)]
v2 (k + 1) = v2 (k) + T [v3 (k) − β02 fal(e(k), 1/2, δ) + bu(k)]

v3 (k + 1) = v3 (k) − T β03 fal(e(k), 1/4, δ),

where e(k) = v1 (k) − y(k), and



e(k)δ a−1 , |e(k)| ≤ δ
fal(e(k), a, δ) =
|e(k)|a sign(e(k)), |e(k)| > δ.

Select states and write an S-function for the model.


(10) The mathematical model of active disturbance rejection controller is [3]
454 Chapter 14 · More on Simulink Modeling and Simulation



⎪ e1 (k) = v1 (k) − x1 (k)

e2 (k) = v2 (k) − x2 (k)
(14.9)

⎪ u0 (k) = β1 fal(e1 (k), a1 , δ) + β2 fal(e2 (k), a2 , δ)

u(k) = u0 (k) − v3 (k)/b.

Write an S-function to describe the controller.


(11) The continuous versions of the tracking differentiator are [4]
(a) second-order model
⎧ 
⎨ x1 (t) = x2 (t)  
|x2 (t)|x2 (t) (14.10)
⎩ x2 (t) = −R sat x1 (t) − u(t) + ,δ ,
2R

where 
sign(A), |A| > δ
sat(A, δ) = (14.11)
A/δ, |A| ≤ δ, δ > 0,
(b) third-order model
⎧ 

⎪ x1 (t) = x2 (t)

⎨ x (t) = x3 (t)
2     
x32 (t) x (t) A (14.12)

⎪  3
⎩ x3 (t) = −R sat x1 (t) − u(t) − 6R2 + A

R
+S
R
,δ ,

where
 
|x3 (t)|x3 (t) x2 (t)
S = sign x2 (t) + , A = Sx2 (t) + 3 . (14.13)
2R 2R

Write M-functions for the two tracking differentiators and mask the blocks.

14.6 A Mini-Project
14
Active disturbance rejection control (ADRC) is an attractive control strategy [5]. The
block diagram of ADRC is shown in . Fig. 14.20. The tracking differentiator is the
S-function block established in Example 14.15, while the extended state observer and
the ADRC controller are the blocks you have completed in Exercises (9) and (10).
Compose the overall ADRC controller in the bash box in . Fig. 14.20 and mask it
as a reusable block.
If the plant model is a nonlinear continuous model defined as

ẋ1 (t) = x2 (t)
ẋ2 (t) = sign(sin t) + u(t)

and assume that the reference parameters of the ADRC controller are r = 30, h =
0.01, T = 0.01, β = [100, 65, 80], β 1 = [100, 10], a = [0.75, 1.25], δ = δ1 = 0, b = 1,
References
455 14

external tracking ( )
input ˆ( ) ADRC ( ) ( )
plant
controller
( )

( )
expended state
observer

. Fig. 14.20 ADRC system structure

study the system response when it is driven by a square wave. Can you improve the
control results by adjusting the controller parameters?

References
1. Xue DY (2022) Modeling and simulation with Simulink[M]. De Gruyter, Berlin
2. Åström KJ, Hägglund T (1995) PID controllers: theory, design and tuning [M]. Instrument Society of
America, Research Triangle Park
3. Han JQ, Yuan LL (1999) Discrete form of tracking differentiators (in Chinese)[J]. J Syst Sci Math
19(3):268−273
4. Han JQ, Wang W (1994) Nonlinear tracking differentiators (in Chinese)[J]. J Syst Sci Math 14(2):177−
183
5. Han JQ (2009). From PID to active disturbance rejection control [J]. IEEE Trans Ind Electron 56(3):
900−906
457

Supplementary
Information
MATLAB Functions Index – 458

Subject Index – 463

© The Editor(s) (if applicable) and The Author(s), under exclusive license to
Springer Nature Singapore Pte Ltd. 2024
D. Y. Xue and F. Pan, MATLAB and Simulink in Action,
https://doi.org/10.1007/978-981-99-1176-9
458 MATLAB Functions Index

MATLAB Functions Index


c4mmfun*, 79, 89−91
Symbols c5excirc*, 82
abs, 37, 46, 63, 64, 84, 119, 121, 147, 194, 356, c6mapp*.mlapp*, 153
357, 359, 376, 377, 428, 432, 448 c6mbrown.mlapp*, 154
add_block, 424 c9mfun*, 270
add_line, 424 cd, 92
angle, 37, 121 cdf, 369
annotation, 111 ceil, 37
anova1, 378, 379 char, 44, 56
anova2, 380, 381 charpoly, 224, 228, 229
any, 81, 84 chol, 234, 238, 238
apolloeq*, 297, 298 cholsym*, 239
appdesigner, 151, 153 class, 32, 66
arguments, 82, 82, 84, 89, 146, 175, 176, 184, 272 classdef, 140
asin, 40 clc, 20
assignin, 90, 90, 434 clear, 11, 24, 25, 28, 328, 330, 335, 337, 343
assume, 29 clearvars, 24
assumeAlso, 29 clf, 111
assumptions, 28, 29 close, 128, 155
atan, 167, 193, 360 close_system, 424
axis, 120, 128, 135, 155 collect, 46, 228
bar, 116 collect*, 143, 145, 147
bar3, 122 color, 437
blkdiag, 223 colormap, 135
bode, 139 comet, 112, 120
boxplot, 372, 373, 377 comet3, 122
break, 62, 65, 225, 235 compan, 220
bsxfun, 144 compass, 112
bvp5c, 310, 311, 313 cond, 224, 240
bvpinit, 310, 311, 313 conj, 37
c11mnls*, 336, 337, 343 continue, 253
c11mopt*, 325 contour, 173, 174
c13m2d.slx*, 408 conv, 87−89
c13m2d0*, 409 convs*, 87, 88
c13mapol.slx*, 410 cos, 40, 41, 109, 122, 123, 127, 129−131, 175, 178,
c13mapol0*, 410 194, 195, 242, 243, 264, 274, 340, 409, 437
c13mdde*.slx*, 412 cosd, 41
c13mimp*.slx*, 411 cosh, 40
c13mimp0*, 411 cot, 40
c13mlor*.slx*, 404, 405, 425 cputime, 25
c13mlor0*, 407 csapi, 358, 358, 359
c13mmod1.slx*, 398 csc, 40
c13mmove.slx*, 399, 426, 427 cumulative distribution function, 367
c14han_fun*, 449 dde23, 305, 307
c14malg*.slx*, 430, 431 ddensd, 308, 309
c14mmove.slx*, 427 ddesd, 307, 308
c14mmstep.slx*, 452 ddeset, 306, 308, 309
c14mpid*, 434 deblank, 44
c14mpid*.slx*, 434 decic, 304, 305
c14mss*, 444 det, 224, 225−227
c14mtd.slx*, 449 diag, 220, 222, 223, 309
c14mtree*, 446 diff, 5, 163, 171, 172, 173, 173−177, 193,
c14mtree1.slx*, 447 285−290, 298, 299, 311, 360, 431, 451
c4excirc*, 81 disp, 23, 45, 48, 56, 58, 142, 253, 437, 438
c4mexlive.mlx*, 77 display*, 141
459
MATLAB Functions Index

doc, 174 fnval, 358, 359, 361


double, 27, 44, 66, 166, 169, 170, 173, 178, 193, fopen, 48, 48, 58
195−197, 228, 269, 287, 360 for, 7, 54, 55, 56, 58−62, 67, 70, 80, 83, 85, 88,
drawnow, 120, 128, 155 105, 128, 141, 146, 147, 155, 175, 176, 182, 187,
dsolve, 285−290, 431 253, 269, 339−343, 399, 427
eig, 33, 224, 229, 232, 233, 236 format, 22, 22, 23, 55, 58, 194
else, 451 fourier, 204, 204
elseif, 62, 449 fplot, 105, 106−109, 167, 182, 185, 263, 285, 287,
eps, 26, 58, 84, 147, 195, 197, 199, 294, 296, 303, 289, 358, 360
304, 306, 308, 311, 313, 326, 329, 335, 363, 425 fplot3, 123, 123
eq*, 156 fprintf, 48
error, 81, 84, 141, 146, 260, 442, 444, 446, 448, fread, 48
450 frewind, 48
errorbar, 112 fscanf, 48
errordlg, 149 fseek, 48
eval, 44, 149, 269 fseries*, 181, 184, 185, 185
evalin, 90, 90 fsolve, 270, 270, 272
exist, 26, 79 fsurf, 124, 124, 125, 126, 126, 127, 170
exp, 11, 12, 14, 29, 38, 40, 40, 64, 114, 122−124, ftell, 48
126, 129, 130, 169, 173, 174, 179, 180, 189, funm, 97, 242, 242, 275
195−199, 201, 205, 243, 264, 274, 287, 288, 361, funmsym*, 242, 243
431 fwrite, 48
expand, 32, 45, 46, 46 ga, 337, 338, 338, 340, 341, 343
expm, 241, 242, 275 gamma, 190
extract_sols*, 269 gca, 111
eye, 220, 220, 226, 230, 231, 259, 260 gcd, 93
ezplot, 106, 129 gcf, 111
ezsurf, 127 gco, 111
factor, 46, 46 gcs, 424, 425, 434
factorial, 84, 166 get, 23, 111
false, 26, 57 get_param, 434
fclose, 48, 48, 58 getframe, 127, 128, 155
feather, 112 global, 89
feof, 48, 48, 58 grid, 122
ferror, 48 griddata, 356, 357
feval, 44 gtext, 111
fgetl, 48, 48, 58 guide, 151
figure, 113, 114, 120, 128, 425 hadamard, 220, 223
fill, 112, 117, 118, 178, 195 han_td*, 448
fill3, 122 hankel, 220, 228, 229
fimplicit, 14, 129, 129, 130, 263−265, 274 heaviside, 431
fimplicit3, 131, 131, 132 help, 22, 81
find, 61, 70, 147, 450 hilb, 220, 227
findstr, 43, 44 hist, 112
fitnet, 11, 365, 366 histogram, 116, 116
fix, 37 hold, 111, 118, 120, 128, 167, 174, 182, 358, 360,
fliplr, 37 438
flipud, 37, 135 icdf, 369, 376, 377
floor, 37, 84, 146 if, 7, 61, 62, 62, 64, 83, 84, 105, 141, 142, 146, 147,
fmincon, 333, 335, 337, 342 190, 225, 339, 342, 343, 399, 447−449, 451
fmincon_global*, 342, 343 ifourier, 204, 204
fminsearch, 325, 326, 434 ilaplace, 201, 201, 206
fminunc, 325, 326, 339 imag, 36, 37, 135, 272
fminunc_global*, 339, 340−342 image, 135, 438
fnder, 358, 360, 361 impldiff*, 163, 175, 175
fnint, 358 imread, 247, 437, 438
fnplt, 358, 358−360
460 MATLAB Functions Index

inf, 26, 163−165, 167, 169, 178, 185−190, 196, lyapsym*, 260−262
329, 339 magic, 49, 67, 220, 225, 227−231, 235, 237, 240
input, 35, 35, 65 max, 37, 193, 269, 296, 359, 362, 409, 412, 432, 451
inputdlg, 149, 149 mean, 340, 341, 370, 371, 377, 379
int, 163, 177, 177, 178, 178−180, 196−199 median, 371, 371
int2str, 44, 269 menu, 35, 35, 65
integral, 194, 195, 196 mesh, 124
integral2, 197, 197, 198 meshgrid, 60, 61, 64, 86, 124, 128, 135, 169, 170,
integral3, 198, 199 173, 356, 357, 367
interp1, 354, 355, 358, 359 methods, 140
interp2, 355, 356 min, 37, 299, 301, 377, 451
INVLAP_new*, 202, 203 minus*, 143, 144
INVLAP‡, 202 more_sols*, 273, 274−276, 428
inv, 33, 38, 39, 224, 229, 230, 235−237, 258 moutlier1‡, 373, 374
inverse distribution, 368 movie, 127, 128
isa, 32, 141 mpower*, 143, 146
isconverge*, 181, 190, 191 msgbox, 149
isempty, 451 mtimes*, 143, 145
isfinite, 32 multi_step*, 450
ishold, 111 mustBeGreaterThan, 82, 184
isinteger, 50 mustBeInteger, 82, 84, 175, 176, 184
isnan, 32 mustBeMember, 82
isnumber*, 66 mustBeNonnegative, 82, 84
isnumeric, 82 mustBeNumeric, 89
isreal, 81 mustBePositive, 82, 84, 175, 176, 184, 273
isscalar, 272 my_fact*, 83, 84
isstruct, 339, 342 my_fibo*, 84
iztrans, 205 myhilb*, 80, 83
jet, 135 NaN, 26, 112−114, 134
jordan, 234, 235, 236 nargin, 80, 83, 88, 89, 141, 260, 269
kron, 144, 145, 226, 258−260 nargout, 80, 142, 399
kronsum*, 144, 145 nchoosek, 51
laplace, 201 ndgrid, 359, 361
lasterr, 66 neshgrid, 366
latex, 201 new_system, 424
lcm, 93 newrbe, 366, 367
legend, 111 nnz, 69, 221, 340, 341
length, 43, 44, 56, 59, 70, 81, 105, 128, 135, 141, norm, 5, 38, 193, 224, 228, 233, 253, 256, 259−261,
146, 147, 155, 269, 293, 294, 296, 298, 305, 377, 267, 269, 270, 272, 274, 276, 311, 370
399, 427, 432, 451 norminv, 376
limit, 163, 164−171, 188, 190 null, 224, 254
line, 111, 116, 263, 438 num_diff*, 192, 193
linprog, 11, 327, 328−330 num_integral*, 194, 194
linspace, 34, 128, 135, 194, 310, 311, 313, 359, num2str, 44, 44, 141, 442, 444, 446, 448, 450
437 numden, 46
listdlg, 149 numel, 221
load, 24, 47, 364, 373, 374 ode113, 291, 301
log, 40, 40, 179, 193, 311, 360, 409 ode15i, 304, 305
log10, 40, 119, 121 ode15s, 291, 301
log2, 40 ode23, 291, 301
logical, 31 ode23s, 291
loglog, 112 ode23t, 301
logspace, 119, 121 ode23tb, 291
lookfor, 22 ode45, 291, 293, 294, 296, 298, 303
lsqcurvefit, 363, 363, 364 ode87‡, 291, 301
lu, 234, 237, 237 odeplot, 294
lyap, 259, 260, 260 odeset, 293, 294, 296, 298, 301, 303, 304, 311, 313
461
MATLAB Functions Index

ones, 220, 221, 226, 305, 340, 341 reshape, 37, 144, 258−260, 366, 367
open_system, 390, 424, 425, 434 return, 190
opt_con*, 335 rewrite, 45, 46, 46
optimoptions, 343 rgb2gray, 247
optimproblem, 330, 331−333 rng, 370, 370
optimset, 11, 272, 273, 326, 329, 335, 337, 343, roots, 229, 266
363 rot90, 37
optimvar, 331, 331−333 round, 37, 39, 155
outliers‡, 373, 373 rref, 224, 230, 231, 253, 255, 280
paradiff*, 163, 176, 176 save, 24, 47
parsim, 427, 427 sec, 40
particleswarm, 337, 338, 339−341 semilogx, 112, 119, 121
pascal, 220, 223 set_param, 424, 425, 434
patch, 437, 438 semilogy, 112
path_integral*, 162 setModelParameter, 427
pathtool, 21 setVariable, 427
patternsearch, 337, 338, 340, 341 sign, 63, 64, 431, 448
pcode, 92, 92 sim, 365, 425, 425, 426, 427, 428, 431, 434
pdf, 369, 369 simplify, 45, 47, 172, 173, 175−177, 188, 189,
pi, 22, 25, 26, 29, 34, 38, 40, 41, 45, 56, 59, 65, 82, 201, 226, 243, 285, 288−290, 431
101, 102, 106, 112−114, 120−123, 127, 128, 167, simsizes, 443, 445, 446, 448, 450
185, 194−196, 264, 265, 428, 437, 449 simulannealbnd, 337, 339, 340, 341
pie, 117, 117 simulink, 390
piecewise, 46, 63, 64, 129, 165, 196 Simulink.SimulationInput, 426, 427
pinv, 224, 231, 232, 254, 256 sin, 5, 11, 12, 14, 40, 41, 45, 101, 102, 106, 107,
plot, 12, 101, 101, 102, 103, 103, 104, 105, 109, 109, 112−115, 120, 122, 123, 127−131, 164, 169,
118, 120, 128, 155, 164, 167, 193, 196, 203, 293, 171, 196, 204, 264, 274, 409, 428, 437, 438, 449
294, 298, 299, 301, 305, 307−309, 311, 313, 355, sind, 40, 41
362, 375, 399, 427, 428, 431, 434, 437, 438, 451 single, 27
plot3, 122, 122, 375, 405, 425 sinh, 40, 180, 198, 203
plotyy, 109 size, 5, 70, 144, 220, 221, 267, 274
plus*, 143 sl_plot*, 399, 399
polar, 112 sldebug, 430
polarplot, 112, 112−114 solve, 266, 267, 300, 331, 331−333
poly, 224, 228 sort, 37, 141, 147, 428, 451
polyfit, 362, 362 spapi, 358, 358−361
ppoly*, 140, 140, 142−147 sprintf, 44, 45
pretty, 201 sqrt, 26, 28, 38, 41, 55, 58, 66, 119, 121, 167, 169,
printdlg, 150 179, 180, 187, 191, 193, 197−199, 201, 203, 263,
prod, 46, 70, 84, 221, 341, 342 276, 297, 298, 360, 376
profile, 21 stairs, 112, 115
properties, 140 std, 343, 370, 371, 377
qr, 234 stem, 112, 115, 166
quadprog, 330, 330 stem3, 122
quantile, 371, 373 str2mat, 43
questdlg, 149 str2num, 149
quiver, 112, 174 strcmp, 44
rand, 69, 105, 220, 221, 253, 311, 313, 337, strrep, 43, 44, 141, 142
339−342, 357, 363, 366, 367 strvcat, 43
randi, 69, 220, 222, 225, 235 subplot, 121, 121, 126, 375
randn, 120, 128, 155, 220, 221 subs, 46, 47, 166, 170, 190, 201, 267, 269, 287
random, 369, 370, 371 sum, 55, 57, 60, 187, 333, 341, 342
rank, 224, 227, 232, 235, 254, 256, 260 surf, 124, 124, 128, 169, 170, 173, 356, 357, 361,
raylinv, 118 366, 367
raylpdf, 116, 118 surf_integral*, 162
raylrnd, 116, 117 surfc, 134
real, 36, 37, 135, 272 surfl, 134
462 MATLAB Functions Index

svd, 33, 224, 234, 239, 240 uint8, 31


switch/case, 65, 65, 66, 82, 442, 444, 446, 448, uiputfile, 155
450 uisetcolor, 150
sylvester, 260, 261 uisetfont, 150
sym, 7, 28, 29, 29, 30, 30, 38−41, 66, 80, 85, 179, uminus*, 143, 144
186, 225−231, 233, 235−239, 257, 259, 268, 269 vander, 220
symplify, 262 var, 370, 371
symprod, 181, 188, 189, 191 varargin, 87, 88, 339, 342, 399
syms, 5, 28, 28−30, 32, 45−47, 64, 106, 107, 123, varargout, 87, 89
124, 126, 127, 129, 131, 164−167, 169−180, 182, VideoWriter, 128, 155
185−189, 191, 193, 195, 197−201, 204, 205, 226, view, 11, 125, 126
228, 242, 243, 257, 263, 265, 267, 287−289, 300, vpa, 28, 29, 38, 41, 56, 178−180, 189, 198, 199
360, 431 vpasolve, 5, 267−269
symsum, 181, 185, 186−189 warndlg, 149
symvar, 28 waterfall, 134
tan, 40, 41, 45, 101, 102, 106, 120, 167 which, 22, 26, 79
tand, 41 while, 48, 57, 57, 58, 68, 79, 89, 90, 120, 225, 235,
taylor, 181, 182, 182 272
text, 111, 437 who/whos, 24, 24
tf, 395 wilkinson, 220
tic/toc, 25, 59−61, 84, 85, 172, 180, 194, 195, workspace, 24
198, 199, 253, 268, 269, 298, 301, 305, 311, 343, writeVideo, 128, 155
427, 428, 431 xlabel, 111
tinv, 377 xlsread, 49, 49
title, 111 xlswrite, 49, 49
toeplitz, 220, 223 xor, 42
trace, 224, 226 ylabel, 111
train, 11, 365, 366 ylim, 164
trapz, 194, 194 yyaxis, 109
treeplot, 135 zeros, 70, 135, 220, 220, 272, 273, 275, 276, 306,
true, 26, 57, 196, 394 309, 428
try/catch, 66, 66 zlim, 173
type, 74 zoom, 111
uigetfile, 48, 48, 58, 150 ztrans, 205, 205, 206
463
Subject Index

Subject Index

A C
absolute error tolerance, 195, 294, 423 caller, 74, 78, 87, 89, 90, 442
absolute value, 26, 41, 58, 271, 396 case-sensitive, 26
accumulative variable, 55 cell array, 31, 49, 65, 87−89, 149
active disturbance rejection control, 454 characteristic polynomial, 220, 224, 225, 228−229,
actuator saturation, 433 234
adaptive step size, 194 Chebyshev polynomial, 94
additional parameter, 325, 334, 440, 441, 444, 446, χ 2 distribution, 368
448, 450 chick−rabbit cage problem, 5
algebraic cofactor, 225 Cholesky factorization, 233, 234, 237−239
algebraic constraint, 302, 396 Chua circuit, 415
algebraic loop, 423, 428, 430−433 class, 9, 12, 31, 82, 138−142, 357
analysis of variance, 375, 378−381 clock block, 393, 399
animation, 120, 127, 128 closed-form solution, 190
anonymous function, 70, 74, 85−87, 105−107, closed-loop, 157, 203, 418, 434
123−125, 129, 131, 194, 195, 198, 199, 203, 263, closed-path, 117, 118, 437
270, 271, 273, 275, 291, 292, 297, 298, 303, 304, coin-tossing experiment, 69, 221
306−310, 312, 325, 326, 333−335, 339, 363, 364, colon expression, 19, 32−34, 310
405 comet trajectory, 112, 120
App, 151−157 companion matrix, 220, 234−235
App Designer, 138, 147, 148, 151−155 compass plot, 112
approximate solution, 134 complex conjugate, 37, 41, 266, 268, 271, 272
arc trigonometric function, 40 complex solution, 266, 267, 271−273
artificial neural network, 10−12, 354, 361, 364−367 computational load, 84, 224, 225, 294, 296, 300,
ASCII code, 44, 74, 76, 92 326, 335, 427, 428, 430
augmented state vector, 407, 409 computer math language, 4, 8
axis object, 148, 157 condition number, 224, 239, 240
azimuth, 125 conditional structure, 12, 61−65
constrained optimization, 13, 324, 333, 334, 338,
342−344
B constraint, 327, 329−335, 337, 342
B spline, 357, 359−361 continued fraction, 14
backlash, 396 continuous state, 441−446, 448
bad-conditioned matrix, 239 contour, 173
bar plot, 112, 117 convergent, 55, 58, 68, 162, 163, 181, 187, 188,
basic set of solutions, 253 190−191
Bertrand test, 190 convolution, 247
best known solution, 336 covariance matrix, 383
Beta distribution, 368 cubic root, 38
binomial coefficient, 96 curve fitting, 11, 354, 363−364
binomial distribution, 368
block diagonal matrix, 223
block diagram, 9, 389, 397, 403, 407, 417, 430, 435,
D
448, 454 D’Alembert test, 190
block library, 389−392 data structure, 12, 51, 139−140, 225, 425−427
block masking, 436, 438−440, 450 dead zone, 396, 398
Bode diagram, 118, 119, 121, 122, 139 decision variable, 10, 324, 326−328, 331−333, 335,
Bode magnitude plot, 119 336, 338, 339, 342, 351
boundary condition, 310−313, 320, 351 definite integral, 162, 163, 178, 194−196, 360
boundary value problem, 284, 309−313 delay differential equation, 284, 302, 305−309
breakpoint, 91, 92 demux block, 397, 403
Brownian motion, 120, 128, 154 determinant, 224−227, 234
built-in function, 9, 26, 33
464 Subject Index

diagonal matrix, 219, 220, 222−223, 232, 234, 235, Finkbeiner−Kall quadratic programming problem,
239 346
diagonalization, 235, 236 first-order explicit ODE, 291
differential-algebraic equation, 284, 294, 302−303 fixed-step algorithm, 292, 299, 300, 424, 427, 429
direct assignment, 32 floating point, 27, 44
direct feedthrough, 432, 443, 445, 446, 448, 450 flow control, 54, 62, 64, 440
discrete PID controller, 395 forecasting, 354
discrete signal, 114−115 Fourier coefficient, 184, 185
discrete state, 417, 441−446, 448, 450 Fourier series, 162, 181, 184−185
discrete transfer function, 395 Fourier transform, 204−205
divergent, 135, 187, 190, 191, 271 fractal, 135
dot operation, 37, 39, 42, 60, 63, 65, 86, 106, 107, fractal tree, 104, 105, 445, 447
122, 124, 125, 129, 203, 413 frequency, 107, 115−117, 119, 204, 393
double integral, 180, 197−198 Frobenius norm, 224
double loop, 59−61, 64, 80 full-rank matrix, 234, 235, 238
double precision, 7, 19, 27−29, 31, 32, 38, 44, 55, function approximation, 13, 354
56, 66, 67, 96, 224, 225, 236, 237, 240, 252, 269, function handle, 86, 105, 124, 197, 199, 242, 270,
275, 276, 294, 296, 298, 326, 400 273, 292, 294, 302, 304, 306−308, 310, 338, 339
Duffing equation, 315
dynamic trajectory, 120
G
gain, 399, 403, 405, 413
E Gamma distribution, 368
edge detection, 247, 248 general solution, 269, 284, 285, 287
Eggholder function, 346 general term, 58, 185−189, 191
eigenvalue, 33, 219, 224, 229, 232−236, 383, 384 generalization, 365
EISPACK, 8 generalized eigenvalue, 33
elevation, 125 generalized inverse, 231, 232
equation constraint, 327−329, 334−337 generalized Lyapunov equation, 251, 260
error dialog box, 149 generalized polar equation, 112
error message, 8, 26, 49, 58, 63, 66, 79, 430 generalized Riccati equation, 268, 272, 278
error norm, 38, 193, 228, 232, 256, 261, 268, 270, genetic algorithm, 337−338, 340, 341
272, 274 geometrical distribution, 368
error plot, 112 global optimum solution, 337−344
error tolerance, 88, 96, 97, 270, 271, 293, 296, 307, global variable, 89
308, 400, 424, 429 golden ratio, 55
Euler constant, 181, 190 gradient, 173, 325
Excel file, 19, 47, 49, 51 graphical method, 114, 130, 131, 134, 170, 173,
exclusive or, 42 251, 262−266, 336, 371
explicit function, 101, 128, 162 graphical user interface, 147
exponential distribution, 368 graphical window object, 148
extrapolation, 354 gravity acceleration, 398, 426, 427
extreme value distribution, 368 greatest common divisor, 93
Gröbner base, 266
F
F-distribution, 368 H
factorial, 83, 96 Hadamard matrix, 220, 223
factorization, 46, 219, 233, 234 handle, 148, 150, 153
fast restart mode, 13, 392, 423, 428, 433, 434 Hankel matrix, 220, 228, 229
feasible region, 333 Heaviside function, 46, 205, 431
feasible solution, 29, 330 Hénon attraction, 133
feather plot, 112 Hermitian symmetrical matrix, 231
Fibonacci sequence, 6, 14, 56, 135 Hermitian transpose, 37, 256, 260
field, 120, 138−141, 143 Hilbert matrix, 58−60, 80, 220, 227
file dialog box, 48, 58, 150 histogram, 112, 115, 116, 371
filled plot, 112, 117−118, 122, 178, 195 history function, 306, 307, 416
465
Subject Index

homogeneous equation, 253, 276


hypergeometric distribution, 368 K
hypothesis test, 13, 354, 375−378 key signal, 398, 399, 403, 404, 406, 409−411, 413
Kronecker product, 144, 145, 226, 256−258, 260
I Kronecker sum, 144, 145

identity matrix, 219, 220, 229−232, 239−241


imaginary part, 36, 37 L
implicit function, 9, 12, 101, 128−132, 136, 162, Lagrange interpolation, 70
163, 170, 174−175, 263, 265 Laplace transform, 200−203, 206
implicit ODE, 284, 303−305, 403, 410−411 least common multiple, 93
improper integral, 162, 177, 179, 194, 195 least squares, 354, 361, 363−364
indefinite integral, 162, 163, 177−178 least squares solution, 37, 251, 252, 255, 256
inequality constraint, 10, 327, 328, 334, 335 left division, 37, 252
infinite integral, 162, 177 left limit, 167
infinite loop, 120, 272 like-term collection, 143, 145, 147, 157
infinite number of solutions, 253, 254 limit, 13, 155, 163−171, 188, 190
infinite product, 189 linear combination, 327, 364
infinite series, 162, 181, 182, 185, 187, 188, 190−191 linear equation, 219, 251−262, 327, 328, 337
infinite sum, 186−189 linear programming, 10, 11, 327−332
inherit, 395, 443, 446 Lissajous figure, 107−109
initial search point, 70, 270−272, 325, 333−335, list box, 76, 77, 149, 156, 451
338, 339 live file, 74−77
initial value, 271, 272, 284, 285, 290−304, 309, 310, local optimum solution, 335, 337
312, 313, 320 local variable, 74, 89, 91, 92
input object, 426 logarithmic function, 39, 40, 112
integer programming, 351, 352 logical model, 424
integer rounding, 39, 154 logical variable, 26, 31, 32, 35, 42, 57, 63
integer symbolic variable, 166 lookup table, 368
integerrounding, 37 loop structure, 7, 48, 54−63, 84, 87, 96, 176, 196,
integral surface, 360, 361 234, 427
integral transform, 6, 13, 200−206 Lorenz equation, 404
integrand, 177−179, 193−196, 198, 199 Lotka–Volterra model, 292
integrator block, 394, 398, 399, 403−406, 409 low-pass filter, 431, 432
integrator chain, 410 LU factorization, 219, 234, 236, 237
intelligent solver, 324, 337, 341−343 Lyapunov equation, 258−261
interior interpolation, 354
interpolation, 310, 354−361, 365, 366
interpolation surface, 356, 359, 366 M
interquartile range, 371 M-function, 78−80, 83, 85, 87, 89, 199, 273, 291,
intersection, 130, 131, 136, 263−265, 272 292, 297, 298, 307, 308, 310, 333, 339, 363, 397,
intersection curve, 136, 263 407, 434, 448, 454
inverse Fourier transform, 204, 212 M-script, 74, 92
inverse Laplace transform, 200, 201, 206 machine precision, 26
inverse matrix, 39, 224, 229−231, 252 magic matrix, 49, 220, 225, 227, 228, 235
inverse z transform, 205 magnitude−frequency, 121
isolated solution, 264, 272 Mandelbrot set, 135
iteration, 54, 55, 271, 326, 328, 329, 335 mass matrix, 294, 302, 303
MATLAB workspace, 19, 23, 24, 26, 27, 29, 30,
32, 44, 47, 66, 85, 89, 90, 92, 127, 165, 219, 222,
J 225, 247, 248, 273, 303, 325, 359, 364, 372, 374,
Jacobian matrix, 294 380, 394, 395, 399, 401, 405, 437
joint probability density function, 64 matrix exponential, 219, 240−241
Jordanian block matrix, 236 matrix factorization, 225
Jordanian matrix, 233, 235, 236 matrix function, 13, 41, 96, 97, 240−243
Jordanian transform, 219, 234, 236, 242 matrix multiplication, 254, 396, 413
matrix of ones, 220
466 Subject Index

matrix of zeros, 220


matrix power, 37 O
matrix rotating, 37 object, 31, 76, 77, 111, 125, 138−148, 152, 153, 357,
mean, 370, 371, 376−379 358, 365, 393, 395, 426
measured data, 117, 121, 301, 354, 378, 383 object-oriented programming, 138−155
median, 371 objective function, 10, 324−335, 337−339, 341−343,
member, 31, 116, 138, 140, 144, 150, 293, 306, 310, 433, 434
326−328, 330, 331, 334, 338, 339, 443 one-sided limit, 167−168, 179
memory block, 395 one-way ANOVA, 378−380
mesh grid, 31, 60, 61, 64, 86, 123, 124, 169, 173, online help, 15, 21−22, 48, 51, 80, 352
247, 312, 355−357, 359 open-loop, 203, 418
message box, 149 ordinary differential equation, 284−320
Mittag-Leffler function, 94 orthogonal matrix, 220, 234, 239
mixed integer programming, 338, 351, 352 orthogonal plane, 374, 375
Möbius strip, 127 orthographic views, 125, 126
model window, 389−391, 398, 404, 433, 435 outlier, 371, 382
model workspace, 433 outlier detection, 354, 371−375
Moore−Penrose generalized inverse, 231, 252, 255, output argument, 79, 80, 87, 89, 90, 121
256 output object, 426
multidimensional array, 31, 37, 39, 220, 221, 371 over-fitting, 366
multidimensional interpolation, 354, 355, 357, 359 overload function, 139, 142−147, 153, 156
multiple integral, 163, 177, 180−181
multiple limit, 168−170
multiple solution, 13, 131, 251, 262, 272−274, 281 P
multivariable system, 393, 394 parallel connection, 212
multivariate function, 71, 168, 169, 173, 177, 358, parallel simulation, 423, 425, 427, 428, 451
364 parametric equation, 107, 122−123, 126, 127, 162,
multivariate normal distribution, 368 163, 170, 176, 213
mutual exclusive, 63 partial derivative, 162, 163, 170, 173−175, 358
mux block, 397, 403, 409, 410 particle swarm optimization, 337−341
particular solution, 254
Pascal matrix, 68, 220, 223
N path integral, 213, 214
n-way ANOVA, 378 pattern search, 338, 340, 341
narcissus number, 70 permutation, 225
negative binomial distribution, 368 permutation matrix, 237
nested loop, 58, 59 phase plane trajectory, 292, 293, 315
neuron, 364 phase space trajectory, 405, 414
neutral-type DDE, 308−309, 318, 413 phase−frequency, 121
Newton−Raphson iteration, 94 PID controller, 394, 433−440
node, 12, 366 pie chart, 115, 117
nonlinear constraint, 333, 335, 336 piecewise function, 46, 54, 63−64, 86, 129, 165,
nonlinear equation, 13, 251, 269−276, 333−336 189, 195, 317, 360, 437, 448
nonlinear matrix equation, 251, 272−276, 281 pixel, 31, 247
nonlinear ODE, 284, 289−290 polar equation, 112
nonlinear programming, 324, 333−337, 342 polar plot, 112−114
nonsingular matrix, 37, 227, 229, 234, 258, 260 pole, 33, 394, 418
nonzero F-distribution, 368 polynomial, 32, 46, 47, 87, 88, 138, 139, 181, 228,
norm, 5, 38, 69, 96, 193, 224, 225, 227−228, 255, 266
256, 260, 368, 371, 376 polynomial equation, 262, 266−269, 284
normal distribution, 221, 368, 376 polynomial fitting, 354, 361−363
normal logarithmic distribution, 368 positive-definite, 234, 238, 239, 330
normalized eigenvector, 233, 383 power, 36−39, 143, 146−147, 223
not a number, 26 prime number, 67
null space, 224, 253, 254, 276 primitive color, 150
number of iteration, 58, 270, 271, 325, 326, 335 primitive function, 177, 360
numerical inverse Laplace transform, 202 principal component, 384
467
Subject Index

probability, 221, 367, 379, 381 sample points, 11, 354, 360, 384
probability density function, 116, 118, 367, 369 sample time, 114, 115, 395, 443, 446−448
prototype function, 242, 243, 358, 361, 363, 364 saturation, 63, 396, 434
prototype model, 365 scattered data, 355−357, 365, 366
prototype window, 151, 153, 154 Schwefel function, 346
pseudocode, 92−93 scope block, 394, 398, 404
pseudoinverse, 224, 231, 232, 255 search path, 21, 26, 33, 50
pseudo-polynomial, 138−140, 142−147, 156, 272, seed, 370
275 semi-explicit differential-algebraic equation, 302
pseudo-polynomial equation, 275−276, 280 semi-logarithmic plot, 119
pseudorandom number, 116, 120, 221, 222, 367, sequence product, 181, 189
369−371, 445 sequential limit, 168−170
series connection, 202, 414
series sum, 59, 181, 185−189
Q seven-body model, 415
QR factorization, 234 significance level, 373, 376, 377
quadratic equation, 268 significance test, 376
quadratic form, 268, 360 Similarity transformation, 219, 234
quadratic programming, 330−332, 334 simplex method, 325
quartile, 371, 373 simplification, 45
quasi-analytical solution, 266−269, 275 simulated annealing, 337, 339−341
quasi-Newton algorithm, 325 simultaneous equation, 130, 134, 251, 263−265,
question-answer dialog box, 149 267, 281
quiver plot, 112, 173, 174 singular value, 33, 219, 224, 233, 239, 240
singularity, 179, 195, 200
R Sobel matrix, 247
sorting, 37
Raabe test, 190 special function, 190, 202, 288
rank, 224, 225, 227, 232, 234, 239, 254, 256 sphere, 65, 81, 132
Rastrigin function, 340 spline object, 358−361
Raydan problem, 345 square matrix, 30, 41, 69, 80, 96, 97, 220, 229, 234,
Rayleigh distribution, 116, 118, 368−370 240
real part, 36, 37 staircase plot, 112, 115, 451
recursive formula, 55, 56, 69, 84, 96, 97, 175, 176, staircase signal, 450−452
445 standard deviation, 370, 371, 376, 377
recursive structure, 83, 85 standard normal distribution, 120, 220, 221, 376
reduced row echelon form, 224, 230, 231, 252, 255, standard ODE, 290, 292, 296
280 state space, 8, 139, 394, 440−441, 444−446, 449,
relative error tolerance, 195, 294, 296, 298, 305, 452, 453
306, 310, 423, 424 state variable, 292, 295, 297, 300−302, 304−306,
relay, 396 309, 310, 312, 315, 406, 425, 445, 446, 448
repeated eigenvalue, 235 stem plot, 112, 114, 115, 122, 166
reserved constant, 22, 25−27, 32, 44 step response, 203, 212, 417, 434, 453
response function, 139, 141 step size, 102, 120, 136, 192, 194, 195, 293, 294,
returned argument, 33, 79, 80, 86, 87, 89, 90, 116, 296, 298−301, 427, 428
150, 224, 266, 270, 306, 325, 326, 333, 339, 342, stiff ODE, 284, 291, 300−301, 415
399, 426, 441, 442 stochastic variable, 367
Riccati equation, 268, 278 string, 42−45, 48, 49, 51, 56, 90, 103, 129, 141, 149,
right division, 37 152, 157
root object, 148 structured variable, 31, 150, 270, 292, 293, 305,
Rössler equation, 414 306, 310, 328−331, 334, 335, 337−339, 342, 370,
rounding, 37, 39 399, 401, 443
Runge–Kutta algorithm, 291, 305 submatrix extraction, 19, 32, 33, 49, 236, 239
Runge–Kutta–Felberg algorithm, 291 subsystem, 13, 423, 435−436, 438
surface intersection, 136
S surface plot, 101, 123−128, 131, 132, 136, 169, 173
switch block, 397
S-function, 397, 407, 423, 440−451, 454
468 Subject Index

switch structure, 12, 54, 64−65, 441, 443 unconstrained optimization, 13, 324−326, 331,
Sylvester equation, 256, 260−262 337, 339−342
symbolic function, 30, 32, 47, 105, 106, 164, 165, undetermined coefficient, 177, 285, 310, 312, 313,
171, 177, 285 363, 364
symbolic variable, 28−30, 66, 67, 127, 163−167, undetermined polynomial, 177
170−172, 174, 177, 200, 201, 204, 257 uniform distribution, 220, 221, 368
symmetrical interval, 184 unity negative feedback, 157, 203
symmetrical matrix, 50, 234, 237−239 univariate function, 358

T V
t-distribution, 368 van der Pol equation, 301, 452
table object, 51 Vandermonde matrix, 220, 243
Taylor series expression, 96, 106, 107, 181−184, variable delay, 307, 318
240, 362 variable substitution, 47, 178, 201, 325, 336
terminator block, 394 variance, 354, 367, 370, 371, 417
three-step method, 4, 10−12 vectorized modeling, 406
threshold, 248, 364 vectorized programming, 12, 59−61, 70, 86
time-varying ODE, 288, 295 vectorized signal, 403
Toeplitz matrix, 220, 223 video file, 128
trace, 224−226, 234 viewpoint, 125
tracking differentiator, 447, 449, 454, 455
training, 11, 365
transcendental function, 35, 39−41, 242
W
transfer function, 119, 139, 148, 202, 203, 364, 393, warning box, 149
394, 398, 412, 431, 435 Weibull distribution, 368
transfer function matrix, 393 weight, 364, 365
transformation matrix, 234−236, 384 white noise, 417
transport delay, 394, 404, 412, 413 Wilkinson matrix, 220, 223, 243, 244
transpose, 37, 88, 256, 260, 292, 306 window object, 148
trial structure, 12, 54, 66 working folder, 21
triangular factorization, 233, 236
trigonometric function, 39−41, 46, 51, 219, 240, 246 Z
trigonometric matrix function, 242
triple integral, 180, 198−199 z transform, 162, 200, 205−206
truncation, 28 zero initial value, 57
trust region algorithm, 325 zero−pole, 394, 395
two-way ANOVA, 378, 380−381 zero-crossing point, 178, 423, 428
zero-order hold, 114, 395

U
unconditional loop, 56, 57

You might also like