MATLAB and Simulink in Action Programming, Scientific Computing and Simulation
MATLAB and Simulink in Action Programming, Scientific Computing and Simulation
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
© 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
My wife, Wu Wei
daughter, Pan Feiyu, and son, Pan Pengyu
—Pan Feng
Xue Dingyü
Shenyang, China
April 2023
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
II Scientific Computing
MATLAB Programming
3 1
Introduction to MATLAB
Contents
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
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
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.
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.
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.
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.
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
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
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
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
© 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.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.
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.
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
Formats Descriptions
loose Loose format, with an extra blank line before and after display
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 .
(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.
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
Constants Description
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
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
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)
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
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
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:
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
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
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
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
Transpose A . Hermitian transpose of a complex matrix, that is, transpose then take
conjugate. If direct transpose is needed, use A.
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
Expansion A(:). Expand A matrix in a column-wise format into a column vector. The
command applies also 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
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
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)
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
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 &&
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
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
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
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
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
46 Chapter 2 · Essentials in MATLAB Programming
Functions Descriptions
2
[n,d]=numden(s) Extracts from symbolic expression s the numerator n and denominator d
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
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
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
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
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
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
2.7 Mini-Projects
Name of planet Relative Relative Semimajor Orbital Orbital Rotation Confirmed Rings
diameter mass axis period eccentricity period moons
Earth 1 1 1 1 0.017 1 1 No
Reference
1. Xue DY (2020) MATLAB programming—mathematical problem solutions[M]. De Gruyter, Berlin
53 3
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
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.
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, · · · .
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
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
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
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
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
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.
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 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);
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
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.
⎡ ⎤
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
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
∞
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.
(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
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
let = 100
. Fig. 3.1 Flow chart for finding global optimal problems with random initial values
73 4
MATLAB Functions
Programming
Contents
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.
Example 4.1
4.1 · MATLAB Script Files
75 4
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.
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
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
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.
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.
(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.
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
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
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.
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
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
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
>> 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
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.
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.
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.
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
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.
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.
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
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
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
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.
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
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.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
√ √ √
2 2 2+ 2 2+ 2+ 2
≈ · · ··· .
π 2 2 2
∞
xk
Eα (x) = ,
(αk + 1)
k=0
T (n) = T (n − 1) + T (n − 2) + T (n − 3),
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)!
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
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
© 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
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.
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.
-1
-2
5 -3
-3 -2 -1 0 1 2 3
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
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
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
Options Meaning Options Meaning Options Meaning Options Meaning Options Meaning
'--' Dash 'g' Green 'k' Black '.' Dots 'o' Circle
'>' '<'
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]
(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.
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
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.
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
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.
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
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
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.
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
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,'--')
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
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
title() title(str). Adds a title to the plot, with the title string str
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
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.
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°
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.
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°
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°
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
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.
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
>> 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.
< 1% 3%
12% < 1%
9%
19%
28%
28%
'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.
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
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
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.
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.
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.
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
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
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.
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
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.
axis viewpoint
axis
elevation
axis
azimuth
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.
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
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.
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
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.
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.
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.
-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
Example 5.28
Use graphical method to find all the solutions in the range −2π ≤ x, y ≤ 2π, for the following
simultaneous equations.
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).
-2
-4
-6
-6 -4 -2 0 2 4 6
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,
5 (a) 3D surface
>> 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.
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.
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
(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
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.
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:
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.
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.
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:
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
It can be seen that coefficient and order vectors of the sum can be obtained by catenating
the vectors of the two pseudo-polynomials
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
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
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.
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:
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:
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.
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
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
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
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'
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).
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.
. 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.
. 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:
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:
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
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]
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
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.
Operations Descriptions
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
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
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
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
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
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
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
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
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
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
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
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
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
∂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
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
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
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.
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)
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
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)
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.
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
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
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
a0 nπ
∞
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
nπ
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
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
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
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
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))
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.
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
#
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().
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
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,'--')
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.
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)
Options Descriptions
'RelTol' Relative error tolerance, which specifies the accuracy. It can be set to eps
for the most accurate precisions
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
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
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
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
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
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.
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
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 ( )
( )
π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
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
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
∞
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
(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
(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
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
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
(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
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.
(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
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
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π.
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
© 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.
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
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
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
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.
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.
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.
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
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
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:
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.
224 Chapter 8 · Linear Algebra and Matrix Analysis
Condition number c = cond( A) computes the condition number, defined as the ratio
of maximum singular value to the minimum one
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)
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.
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:
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 .
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.
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.
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
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.
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 .
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].
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.
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.
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.
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.
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.
⎡ ⎤
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.
Ax = λx, (8.5)
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 .
X = T −1 AT , (8.6)
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.
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.
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
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.
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:
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.
⎡ ⎤⎡ ⎤
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.
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.
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 .
⎡ ⎤
−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.
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.
⎤
−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
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
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:
ψ1,1 = 3e−5 cos 5t − 2e−2 cos 2t + 2 cos 5te−5 cos 5t − 10t sin 5te−5 cos 5t .
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.
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.
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
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
(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
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
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
© 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
Ax = B, (9.2)
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.
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.
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
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).
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.
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)
X = A−1 C B −1 . (9.12)
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.
AX + X AH = −C, (9.14)
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
AX + X B = −C, (9.16)
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
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.
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.
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
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
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
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.
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
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
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;
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
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)
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)
-2
-4
-6
-6 -4 -2 0 2 4 6
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
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
(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
⎡ ⎤ ⎡ ⎤
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
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.
(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,
y cos(x + y2 ) + x2 ex+y = 0.
2
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].
(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
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 .
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
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.
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 ==.
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.
3.5
2.5
1.5
0.5
0 1 2 3 4 5 6
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.
0.9
0.8
0.7
0.6
0.5
0 1 2 3 4 5 6
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:
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:
10 Example 10.6
Consider the second-order time-varying linear ODE.
Solutions Describe the ODE with symbolic expression, the following commands can be
used.
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.
-1
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.
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().
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.
Solvers Descriptions
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
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
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
3.5
2.5
1.5
1
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5
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
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.
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,
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 .
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),
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
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.
>> 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
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
-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
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.
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:
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.
Time elapse None 19.044 0.634 27.873 69.092 3.84 (failed) 61.446
3 ode15s()
0
0 500 1000 1500 2000 2500 3000
-4
10
3
ode45()
2
0
0 500 1000 1500 2000 2500 3000
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
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
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 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
where τi 0 are constant delays of the state variables x(t). Furthermore, the delays
can be functions of t and x(t).
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),
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).
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
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
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.
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:
3( )
4
2 2( )
0
1( )
-1
0 5 10 15
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)
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.
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.
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
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),
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.
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
(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.
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).
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 .
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
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.
(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 − τ )
(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 .
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
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).
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
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.
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
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].
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
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
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
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.
. Table 11.1 Members for the structured variable for linear programming problems
Members Descriptions
Aeq, beq Matrix Aeq and vector beq in the linear equation constraints
Options Control options, the members of this variable can be modified first, then
passed to options
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.
Example 11.5
Solve the following linear programming problem.
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
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.
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.
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.
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.
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.
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
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.
Example 11.9
Solve the following constrained optimization problem.
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
Members Descriptions
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
options control options; the user may modify the control potions, and then set to
options members
nonlcon handle of the functions of the nonlinear constraints, which returns two
arguments, that is c and ceq
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.
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.
Members Descriptions
fitnessfcn the function handle for the fitness function, equivalent to the objective
functions in other optimization problems
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.
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.
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
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
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.
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.
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
Number x1 x2 x3 x4 x5 f (x )
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.
p
J = min |xi |0.8 + 5 sin3 xi + 3.5828,
x
i=1
n/2
2
f (x) = − 13 + x2i−1 + ((5 − x2i )x2i − 2)x2i
i=1
2
+ − 29 + x2i−1 + ((x2i + 1)x2i − 14)x2i .
n/2
2
2
f (x) = 100 x2i − x2i−1 + (1 − x2i−1 )2 ,
i=1
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 ) ,
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
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
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
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
d = [10, 10, 10]T , c = [−20, −80, −20, −50, −60, −90, 0]T .
max
⎧ x + y.
⎪
⎨ y2x −8x +8x +2
4 3 2
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
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].
(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
6Pl 6P(2l)
2
− σmax 0, − σmax 0,
x9 x10 x7 x82
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
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
pool mixer 1
splitter mixer 2
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
© 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.
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.
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
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.
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.
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.
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
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 , . . . ]
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.
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.
Interpolation interp1() cubic 3rd order B 4th order B 5th order B 6th order B
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
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.
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
Degrees 3 4 5 6 7 8 9
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.
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.
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
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.
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.
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
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
chi2 χ 2 distribution k
f F-distribution p, q
t t-distribution k
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.
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.
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
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.
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
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.
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.
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
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
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.
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
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.
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:
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
A 1.9 0.8 1.1 0.1 −0.1 4.4 5.5 1.6 4.6 3.4
-1
1 2
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.
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
Total 94.9667 29
380 Chapter 12 · Data Processing and Statistics
10
3
1 2 3 4 5
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].
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
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
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.
A 1.9 0.8 1.1 0.1 −0.1 4.4 5.5 1.6 4.6 3.4
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
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
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
© 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
model window, or using “copy−paste” method. The blocks can then be connected
accordingly so as to set up the simulation model.
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.
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
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
STOP simulation Stop block, which terminates the simulation process if its input
signal is true
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
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
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
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.
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
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
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
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.
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
(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
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
13
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.
(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.
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))
. 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
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
. 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.
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]:
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
Introducing the vector u(t) = [y(t), z(t), t], the function on the right is written as
13
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
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.
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)
>> 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.
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.
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.
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.
(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:
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
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),
1
h(a) = m1 a + (m0 − m1 ) a + 1 − a − 1 .
2
416 Chapter 13 · Modeling and Simulation with Simulink
(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
( ) 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
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
© 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
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
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
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
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.
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.
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.
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.
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.
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.
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
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
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
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:
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.
. 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
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.
14
. Table 14.4 Comparisons under different values of T
Maximum error 1.688 × 10−14 0.067 4.599 × 10−8 4.978 × 10−10 4.497 × 10−12
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
−
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.
14
1.2
0.8
0.6
0.4
0.2
0
0 5 10 15 20 25 30
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
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
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,
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.
4 Next time hit mdlGetTimeOfNextVarHit sys returns the next time hit
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.
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.
Example 14.13
Consider the given continuous state space model
x (t) = Ax(t) + Bu(t)
y(t) = C x(t) + Du(t),
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:
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.
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:
. 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
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
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:
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.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),
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
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, δ),
⎧
⎪
⎪ 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.
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
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
© 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
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
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
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