Matlab Primary Things
Matlab Primary Things
Matlab Primary Things
2009-2010
5 Differential equations 51
5.1 Differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Solving differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.2.1 Solving differential equations numerically . . . . . . . . . . . . . . . . 54
5.2.2 Sets of differential equations . . . . . . . . . . . . . . . . . . . . . . . . 55
5.2.3 The direction field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.2.4 Plotting of integral curves . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.2.5 Example of numerical solution . . . . . . . . . . . . . . . . . . . . . . 57
5.3 Solving differential equations symbolically . . . . . . . . . . . . . . . . . . . . 59
5.3.1 First order differential equations . . . . . . . . . . . . . . . . . . . . . 59
5.3.2 Sets of first order differential equations . . . . . . . . . . . . . . . . . . 61
5.3.3 Higher order differential equations . . . . . . . . . . . . . . . . . . . . 61
6 Programming in MATLAB 62
6.1 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.2 Some remarks about variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6.3 Writing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.4 Programming language constructs . . . . . . . . . . . . . . . . . . . . . . . . 65
6.4.1 For-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.4.2 If statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.4.3 While-loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.5 Creating programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
2
Chapter 1
MATLAB is a computer program designed for technical calculations. Its name is an abbre-
viation of ”Matrix Laboratory”. In this program, matrix computations are implemented in
a straightforward manner. However, many other pre-programmed routines are available. In
addition, it is possible to implement user-defined calculation routines. MATLAB allows users
to implement calculations in relatively short programming time. When these calculations
have been performed, they can be visualised by means of several plot-routines.
MATLAB can be extended with so called toolboxes. In general, these are collections of MAT-
LAB functions that are tailored for special classes of problems. The ‘(Extended) Symbolic
Math Toolbox’ is an exception. To a great extent, this toolbox consists of ingredients from the
computer algebra package MuPAD. MATLAB performs calculations with the aid of matrices.
These are rectangular schemes of numbers, which are also called arrays. The ‘Symbolic Math
Toolbox’ is quite different from MATLAB itself, since symbolic calculations hardly make any
use of arrays. For this reason it is important to know whether a function used is a MATLAB
function or a ‘Symbolic Math Toolbox’ function. This will not be completely clear at the
outset, but it will become clearer after regular use of MATLAB.
MATLAB can be started by clicking on the selecting the ”MATLAB” option in your startup
tree or possible on your Windows desktop. When MATLAB is started, a window similar to
the one below should appear:
The main window in MATLAB is the command window, positioned at the center, in which
commands can be typed after the MATLAB prompt:
>>
Commands are entered with the ‘return’ key. The command is then executed by MATLAB.
If MATLAB is ready, after possible outputs a new prompt appears.
4
>> b = 2*a + a/3
b =
14
In MATLAB, variables are introduced by assigning a value. Note, that the value can be
numerical values, matrices (called arrays), or other types. You can use the variable, and later
possibly assign a new value to the variable. It is not possible to perform calculations with
variables that have not been assigned a value.
A command does not need to start with an assignment of the form variable =. In such a
case, the result is automatically assigned to the variable ans. You can then use ans further.
>> 4*a + 1
ans =
25
>> ans*ans
ans =
625
If you now want to know what the value of a is, the following command suffices:
>> a
a =
6
Normally, MATLAB displays the output below the command. The output is suppressed by
ending the command with a semicolon. After having entered the command s = 1 + 2, the
screen looks as follows
>> s = 1 + 2;
The value 3 has been assigned to the variable s. If you want to know the value of this variable,
you can either look in the ” Workspace” window on the top left of your MATLAB window,
or request the value of s as follows
>> s
s =
3
If a command is longer than one line, you can end the line with three dots, and then press the
‘return’ key. You can then continue on the following line. After completing the command,
the screen looks as follows:
>> s = 1 + 2 + ...
3 + 4
s =
10
6
Variable Explanation
ans This variable contains the result of the last calculation that has
not been assigned to another variable.
eps The value of this variable is approximately 2.2204 · 10−16 and is
being used internally by MATLAB. This number is the default
computation accuracy of MATLAB which is used to round of all
numbers for storage in the computer memory. Do not confuse eps
with the number e, because e = exp(1) = 2.7182...
i or j The complex number i with the property that i2 = −1.
pi 3.1415...
Inf This is the value infinity. When one divides 1 by 0, 1/0, the result
will be Inf.
NaN This variable is a representation of ‘Not a Number’. A calculation
with NaN always results in NaN. The command 0/0 produces
NaN.
Interruption
A (long) MATLAB calculation can be interrupted with ‘ctrl-c’. After this, a new prompt
appears and new commands can be entered. This interruption is especially useful when a
programmed loop is running that is corrupt.
Incomplete commands
If a command is incomplete or invalid and you press the ‘return’ key, there are two possibilities:
• An error message and a new MATLAB prompt appear. You can start over again.
• The flickering cursor is at the left of the line below the command. In this case there are
two possibilities.
Variables
The name of a variable in MATLAB has to start with a letter. After that, the name can
consist of an arbitrary number of letters, numbers or symbols like ’ ’ and ’-’. MATLAB does
distinguish between upper and lower case letters.
MATLAB uses some special variables, shown in Table 1.3.
Warning: in principle, it is possible to assign a value to the internal MATLAB variables
presented in Table 1.3. This can influence your calculations. Therefore, it is wise never to
assign a value to an internal MATLAB variable. Commands like >>pi=10 should be avoided
at all times! If by accident you have given a different value to an internal MATLAB variable,
you can remove this value by using clear or the workspace browser.
8
Use of the Help Browser
You can use the ”Help Browser” to look for documents and to have a look at MATLAB
documents and other Mathworks products. The ”Help Browser” is a html viewer that is in-
tegrated in the MATLAB desktop. With this browser you can look at the HTML documents
belonging to MATLAB.
When the ”Help Browser” is opened, a window similar as the one below will appear:
The Help Browser consists of two parts. The left half, also called the Help Navigator, can be
used to find information. In the right half you can look at the documentation. Below, the
different tabs of the navigator are listed:
• Contents - Within this tab you can browse a list (arranged in a tree structure) with the
contents of the documentation.
• Search results - Above the different tabs, you can enter a search word. Results of your
search will be shown in this tab. Results found in the documentation will be listed
separately from results found in the demos.
• Demos - Within this tab, you can browse through the demos that are present.
10
MATLAB command Result
a(1,2) Gives the element on the first row and second col-
umn of a.
a(1,:) Gives the first row of a.
a(:,3) Gives the third column of a.
a(:,2)=[10;10;10] Changes the second column of a into a column with
10’s only. Only works if aa is a n × 3 array, n ≥ 2
b(1) the first element of b in case b contains either one
row or one column.
a(1,[3,1]) an array consisting of the 3rd and 1st elements of
the first row of a.
• Between ‘[’ and ‘]’ the elements are separated by spaces or commas, and the rows are
separated by a semicolon. The commands are:
or
>> a = [1,2,3;4,5,6;7,8,9]
• Between ‘[’ and ‘]’ where the elements are separated by spaces or commas, and each
row is entered on a new line by using the ‘return’ key. The command now is
>> a = [1 2 3
4 5 6
7 8 9]
a =
1 2 3
4 5 6
7 8 9
Elements of arrays can be indicated by means of their index. In the case of row and column
vectors, one index suffices. This can be used according to the Table 1.5.
Arrays (both matrices and vectors) can be concatenated into new arrays. If the arrays are
arranged in a row, the number of rows in the arrays have to be equal. If the arrays are arranged
in column, the number
of columns
in the arrays have to be equal. The concatenation of the
arrays a = 2 3 4 and b = 6 5 proceeds as follows:
12
For all these operations, the following conventions hold:
Examples:
>> 2.^b
ans =
64 32 16
>> [2 2 2].^b
ans =
64 32 16
>> a./2
ans =
0.5000 1.0000 1.5000
>> 3*a
ans =
3 6 9
Detailed information about these operations can be obtained with the command help arith.
>> x = 0:0.2:2
x =
Columns 1 through 7
Columns 8 through 11
14
Operation Meaning
> greater than
>= greater than or equal to
< lower than
<= lower than or equal to
== equal to
~= not equal to
The relational operations are given in the Table 1.6. Relational operations are often used in
combination with the function find. Look at the result of the command help find.
>> a = [1 2 3];
>> sin(a)
ans =
0.8415 0.9093 0.1411
>> sqrt(a)
ans =
1.0000 1.4142 1.7321
Consider the function f (x) = x sin(x). A row of function values can be generated with the
following command:
>> x = 0:0.25:4*pi;
>> y = x.*sin(x)
The result gives the size of A, i.e., the number of rows nr and the number of columns nc.
The function
>> sum(A)
calculates the column sums in a rectangular array A and gives the sums in a row vector. (A
column sum is the sum of the elements of a column.) If A is a row vector, then the sum of
the elements of A is calculated. The function
16
>> figure
>> plot(v)
where v is a row vector containing the numbers v1 until vn , generates a plot where the points
(1,v1 ), (2,v2 ) until (n,vn ) are connected by straight lines. The command
>> plot(v,w)
with v and w two row vectors with the same number of elements, plots the points (vi ,wi ),
and connects them by straight lines. The command
>> plot(v,w,x,y)
plots the points (vi ,wi ) and (xi ,yi ) in the same figure.
To determine the appearance of your graph, after plotting a vector you can add the color and
linestyle of graph. For example, the command
>> plot(x,y,’r--’)
will plot y versus x, with a red dashed line. Type help plot to see other line, marker and
color options.
Suppose that we want to draw the graph of the function f (x) = sin(x)+2x
1+x2
on the interval
[0, 2π] consisting of 100 linearly spaced points. Note that the smoothness of the graph is of
course determined by the number of point. The graph can be plotted by using the following
commands:
>> x = 0:2*pi/99:2*pi;
>> y = (sin(x)+2*x)./(1+x.^2);
>> figure
>> plot(x,y)
When drawing a graph, the axes are chosen automatically. You can choose the lengths of the
axes yourself with
which takes care that the graph is drawn in the rectangle XMIN ≤ x ≤ XMAX and YMIN
≤ y ≤ YMAX.
After each new plot command, the old plot will in general disappear. If you want to draw
different plots with different plot commands in the same figure, you have to give the following
command after the first plot command
18
bar(x(1:10)) plot3(x,y,z)
1.4
1.2
20
1 15
0.8 10
z
x
0.6 5
0.4 0
2
0.2 2
0
0
0
1 2 3 4 5 6 7 8 910 y −2 −2 x
position
mesh(X,Y,Z) contour(X,Y,Z)
3
0 2
−5 1
−10
z
0
y
−15
−1
−20
5
5 −2
0
0
−3
y −5 −5 x −2 0 2
x
• mesh(X,Y,Z) produces a three-dimensional surface between the grid points, whose co-
ordinates are given in the matrices X, Y , and Z.
• contour(X,Y,Z) produces level curves in x, y plane, such that all points on a line have
the same value for z. Since the inputs in this functions are gridpoints, the inputs X, Y ,
and Z should be matrices.
You can save a figure by selecting ”File\Save as” and select the required file directory, filename
and file type. An other option is to use the print command. Type help print for additional
information. When you want to be able to open and modify your figures again in MATLAB,
you should save your figure as a .fig file.
If you have to execute a series of commands repeatedly, it might be better to write the com-
mands in a so called ‘script file’. The file should have a name with the extension ‘.m’.
As an example, let us consider the drawing of the function f (x) = |x sin(2πx)| on the interval
[0,2] by using a ‘script file’: Through the menu ‘File\New\M-file’ the ‘MATLAB Editor/De-
bugger’ is opened. Type the following lines:
20
Always test the functions you have defined yourself !
You can change the definition of f (x) by typing the command edit f in the command prompt.
Warning: m-files should not be given the name of existing variables or MATLAB func-
tions. Conversely, after you have defined a function yourself, you should not give variables
the same name as your function, otherwise the function will not work any more (see Exercise
1.25).
Anonymous functions
Sometimes it is more convenient to define your function at the command line. MATLAB func-
tions produced at the command line are called anonymous functions. For example, consider
again the function f (x) = x2 + ex . We can create the anonymous function as follows:
>> f = @(x)(x.^2+exp(x))
Here, f is the name of the function, @ is the function handle, x is the input argument and
x.^2+exp(x) is the function.
Anonymous functions can have multiple input arguments. The general structure of anony-
mous functions is name = @(input arguments) (functions).
The anonymous function will be evaluated in the same way as the function m-files. Thus the
value of f (1.2) will be obtained by the command
>> f(1.2)
ans =
4.7601
Very often, results of MATLAB calculations need to be reused elsewhere. The values of
variables can be saved in a ‘.mat file’. This can be done with the command
which results in all variables in use being saved in the file with the name ‘filename.mat’. The
extension ‘.mat’ does not necessary need to be given. If only a few variables need to be saved,
these variable should be specified after the file name, e.g. only the variables x and y are saved
in the file filename.mat with the command
A saved ‘.mat’ file can be read into MATLAB with the command load
22
Chapter 2
2.1 Introduction
The MATLAB package itself is the numerical toolbox. We will make some general remarks and
treat some important commands. Look at the help information of all commands mentioned.
The number of digits of numbers that are displayed on the screen can be changed with
the commands format long or format short. The calculations themselves do not change.
Internally, MATLAB performs calculations with 16 decimal points.
In this chapter, we are going to investigate the function f (x) = x3 − x2 − 3 arctan(x) + 1 on
the interval [-2,3]. In what follows we will assume that an function m-file of the function is
available.
A possible way to draw the graph of f (x) is using the command plot. You should draw
the graph using that command when the function f (x) is described by an array of function
values. However, when you have a function file, for instance ‘f.m’, which describes the specific
function f (x) there is an alternative way. It is based on the command ezplot. For example,
The command ezplot stands for easy-to-use function plotter. It plots the function f (x) over
a specific domain. The expression f (x) has to be put between quotes (’). The plotting interval
is given as a row vector consisting of the left endpoint and the right endpoint. The advantage
of using this command is that it is easy (‘ez’) to change the interval to investigate the graph
of f (x) in more detail.
2.3 Zeroes
In general it is hard to determine the zeroes of functions exactly. However, they can be
approximated numerically. The function f (x) = x3 − x2 − 3 arctan(x) + 1 has three zeroes on
24
ans =
-1.3784
So the function f (x) has a minimum at x = 1.0878 with value -1.3784. Again, it is possible
to use ‘f’ or ‘f(x)’.
The function f (x) has a maximum on the interval [-1,0]. Unfortunately, MATLAB does not
have a function that can give the location of the maximum directly. However, the location of
a maximum of f (x) is the same as the location of a minimum of −f (x).
The following commands will now be clear.
>> x2 = fminbnd(@(x)-f(x),-1,0)
x2 =
-0.5902
>> f(x2)
ans =
2.0456
There are different commands to approximate an integral numerically. Also refer to the
help facilities. We will use the command quad (which is an abbreviation of quadrature) and
let the result appear with 15 digits.
ans =
6.02456548407172
It is not possible to use ‘f(x)’ as the first argument. The approximation already differs from
the exact value above after the fifth digit. In principle, quad tries to give the first four decimal
points correctly. The precision of the approximation can be improved by using some extra
26
results in a linear approximation a0 x + a1 of the function y(x), with coefficients:
>> a0 = coeff(1)
>> a1 = coeff(2).
To evaluate this data fitting, you can use the command polyval again. For example, calculate
some points of the line for x ∈ [0, 7] in steps of ∆x = 0.1, i.e. x = [0, 0.1, 0.2, . . . 6.9, 7.0]:
xp = 0:0.1:7;
yp = polyval(coeff,xp);
28
3.2 Expressions with variables
In MATLAB, you can work with variables that have been given a value. In principle, in
MATLAB you get an error message when you work with a variable that has not been given
a value.
>> clear x
>> exp(-x)+sin(x)
The ‘value’ given to a variable does not need to be a numerical value. For example, the ‘value’
of a variable could also be a ‘string’. This is an expression between quotes (’). In fact, we
have already been using this with ezplot, fzero en fminbnd. Consider the result of
>> f=’exp(-x)+sin(x)’
f =
exp(-x)+sin(x)
The variable f has now been introduced, and has been given a string as its value. However,
the variable x is still unknown to MATLAB, since it has not been given a value.
The function f has a zero in the interval [3,4] and a minimum in the interval [4,5].
>> fzero(f,[3,4])
Zero found in the interval: [3, 4].
ans =
3.1831
>> fminbnd(f,4,5)
ans =
4.7213
These commands do not give an error message, because of the fact that by specifying the
search interval we have temporarily given x a value (or rather, a range of values). Another
possibility is to give a variable a symbolic ‘value’. This goes as follows.
>> x = sym(’x’)
x =
x
30
Substitution of the value 2 for a and the value 5 for b can also be done at one sweep in the
following way:
>> y = 3*sin(a)+cos(b)
y =
3*sin(a)+cos(b)
>> subs(y,{a,b},{2,5})
ans =
3.0116
In MATLAB, you can differentiate and integrate symbolic expressions. We illustrate these
commands by means of an example:
>> syms x y
>> y = atan(x)
>> diff(y,x)
ans =
1/(1+x^2)
>> diff(y,x,3)
ans =
8/(1+x^2)^3*x^2-2/(1+x^2)^2
R
The indefinite integral arctan(x)dx:
>> int(y,x)
ans =
x*atan(x)-1/2*log(x^2+1)
R7
The definite integral 2 arctan(x)dx:
>> int(y,x,2,7)
ans =
7*atan(7)-1/2*log(2)-1/2*log(5)-2*atan(2)
32
Matlab Meaning of the command
expand((a+b)^3) Get rid of the brackets.
factor(a^3+3*a^2*b+3*a*b^2+b^3) Factorise.
[n d] = numden(a/b+c/d) Reduce to a common denominator.
simplify((x\^2+2*x+1)/(x+1)) Simplify the expression.
Several manipulations of symbolic expression can be performed, stated in Table 3.3. If you
want to write the expression ‘x/(1 + x/(1 + x))’ as a numerator divided by a denominator,
you can proceed as follows:
>> syms x
>> y = x/(1+x/(1+x));
>> [n d] = numden(y)
n =
x*(1+x)
d =
1+2*x
We will investigate the function ‘f (x) = 2xex − sin(x)’ on the interval [0,π] with MATLAB.
Execute the following commands.
>> syms x
>> y = 2*x*exp(-x)-sin(x)
Now the variables x en y are defined as symbols in MATLAB. You can draw the function
f (x) in MATLAB with the command
>> ezplot(y,[0,pi])
From the graph you can immediately see that f has a maximum, a minimum and two zeroes on
the interval [0,π]. The locations of the extrema and zeroes cannot be determined exactly, but
have to be approximated numerically. However, the MATLAB functions fminbnd and fzero
operate on strings, i.e., expressions between quotes (’). The expressions can be expressions in
the variable x. You can simply convert a symbolic expression into a string with the function
char.
>> fzero(char(y),[0.5,1])
Zero found in the interval: [0.5, 1].
34
ans =
-4.5951 -1.6219 -0.2899 0.1288 0.0939 -0.1057
>> syms x
>> subs(y,x,0.6)
ans =
0.0939
The interrelationship of symbols, strings and numbers may make using MATLAB difficult.
You can only get a feeling for this by practising a lot. We give one more example.
>> syms x
>> 2.3456 + x
ans =
1466/625+x
The fact that the numerical value 2.3456 has been converted into the exact fraction 1466/625,
raises the suspicion that the last result has become a symbolic value, because in MATLAB
itself every exact fraction is immediately converted into a numerical value. A check with
class confirms this suspicion.
36
is briefly referred to as A, or alternatively as aij . Essentially, MATLAB only knows one
calculation unit, namely an m × n matrix. In MATLAB, a scalar is interpreted as a 1 × 1
matrix.
1. Between [ and ], where the rows are separated by a semicolon, and the elements are
separated by spaces or commas. For example:
2. Between [ and ], where every row starts on a new line and the elements are separated
by spaces or commas. For example:
>> A = [1 2 3
4 5 6
7 8 9]
3. Via external files in which the values of the variables are stored or are being calculated.
A matrix element can consist of all MATLAB elements. For example, the command:
You can also build a matrix out of other matrices to form a new matrix. For example,
C = [A;a]
produces matrix
A
C= . (4.2)
a
The command sym constructs symbolic numbers, variables and objects. Read what help sym
tells about this command. With the command syms multiple symbolic objects can be con-
structed at the same time. In this case, the names of the objects have to start with a letter.
Symbolic objects can be used as matrix elements.
38
4.2.4 Special matrices
Besides by direct input, some special matrices can also be formed directly with MATLAB
commands. These matrices are:
• An m × n zero matrix, i.e., a matrix in which all elements have the value zero, is formed
with the command zeros(m,n).
• An m × n matrix whose elements all equal one is formed with the command ones(m,n).
• An n × n diagonal matrix, i.e., a matrix in which only the diagonal elements (the
elements with equal row and column indices) have a non-zero value, is formed with the
command diag(v), where v is a vector containing the n diagonal elements.
• An m × n unit matrix, i.e., a diagonal matrix for which all diagonal elements equal one,
is formed with the command eye(n).
If you want to give a matrix the same size as a given matrix A, then you can do this by using
the command size. For example, the command
>> zeros(size(A))
forms a zero matrix with the same size as the matrix A. Of the above commands, only
the command diag accepts a matrix as its argument. The result of the command diag(A),
where A is a matrix, is a column vector consisting of the diagonal elements of A.
4.2.5 Indices
Often it is desirable to work with parts or separate elements of matrices. Hereto, each element
of a matrix can be accessed by means of indices. The command for this has the general form
>> A(m,n). Here A is the matrix of which the element with row index m and column index
n is being specified. If A is a vector, one index suffices. For the matrix A in exercise 4.1,
>> A(3,2) gives the value of this element, namely −2. Among others, this enables you to
change one single element in the matrix. The command:
>> A(3,2) = 3
changes the original value -2 of the element on the third row and second column of A into
the new value 3. All other elements of A remain the same. Instead of indicating one element
of A, you can also indicate more elements of A at the same time. This is done by giving a
vector of indices instead of one single index.
gives the elements a32 and a34 from A arranged as in A, i.e., as a 1 x 2 matrix. Hence,
40
4.3 Matrix operations in MATLAB
With MATLAB it is possible to perform operations and commands on matrices. For this,
MATLAB knows a lot of commands. A number of these operations will be/have been treated
in the course Linear Algebra. At this moment, the following MATLAB operations are of
importance.
Multiplication
The multiplication of two matrices is performed in a special manner. For a m × n matrix
A = aij and a n × p matrix B = bjk , we define the product AB of A and B to be the m × p
matrix C = cik , where
n
X
cik = aij bjk (4.3)
j=1
So,
· · · b1k ···
.. .. .. ..
. . . · · · b2k · · · .
ai1 ai2 · · ·
ain .. ··· cik · · · (4.4)
.. .. .. . ..
. . . ··· bnk · · · .
The product of the matrices A en B can only be formed if the sizes of A and B are com-
patible: the number of columns of A has to be equal to the number of rows of B. If AB
exists, BA does not need to exist. If AB as well as BA exists, we generally do not have that
AB = BA. Within MATLAB, the matrix product of A and B is always defined if either A or
B is a number. Multiplication of a matrix by a number (scalar multiplication) boils down to
multiplication of all matrix elements by that number. The symbol for matrix multiplication
in MATLAB is *, i.e.,
>> A*B
Addition and subtraction
Addition
>> A+B
and subtraction:
>> A-B
of two matrices A and B is performed by addition and subtraction of the separate elements
of the matrix. In MATLAB, these operations are defined if the sizes of the matrices are the
same or if one of the matrices is a scalar. In the latter case the scalar is added to or subtracted
from every element of the matrix.
Raising to a power
42
ans =
2.0000+3.0000i 2.0000
4.0000+5.0000i 3.0000
You need to take this into account when dealing with symbolic matrix elements (or you have
to define your symbolic elements as reals).
>> syms a b
>> A = [a b
1 2]
A =
a, b
1, 2
>> A’
ans =
[ conj(a), 1]
[ conj(b), 2]
>> A.’
ans =
[ a, 1]
[ b, 2]
No division
A division operator is not defined for matrices. However, sometimes one needs to find a
matrix X such that AX = B for given matrices A and B, where A and B are of appropriate
dimensions. This is discussed in Section 4.4.
Matrix functions in MATLAB
In this paragraph we mention some commands that have a matrix as their argument.
The command:
>> inv(A)
44
4.4 Solving sets of linear equations
The most common tasks in numerical linear algebra are solving a set of linear equations of
the form Ax = b.
Several types of linear systems
Ax = b (4.6)
exist:
1. There may exist a unique vector x that solves (4.6). In that case, the system is called
non-singular. An example of such a system is:
1 2 5
x= , (4.7)
3 4 6
−4
which has a unique solution x = .
4.5
2. There may be an infinite number of possible vectors x that solve (4.6). In that case,
the system is called underdetermined. For example, the system
1 2 1
x= , (4.8)
2 4 2
0 1
has solutions x = ,x= and many others.
0.5 0
3. There may not be a vector x that solves (4.6). In that case, the system is called
overdetermined. Examples of such systems are:
1 2 5
3 4 x = 6 (4.9)
5 6 8
and
1 2 1
x= . (4.10)
2 4 3
In MATLAB it is possible to determine the solution of a set of linear equations directly. For
square or rectangular linear systems the method of first resort is the backslash operator. The
solution of Ax = b is implemented directly in MATLAB as:
>> x = A\b
You can find more information about this command with help mldivide.
46
Subtracting three times the upper equation from the lower yields:
x1 = −4, (4.18)
x2 = 4.5, (4.19)
1 0 −4
is obtained. This is represented in the matrix C3 = . Clearly, the solution vector
0 1 4.5
−4
x= can be obtained from both the last set of equations and the matrix C3 .
4.5
The matrix C3 is called the row reduced echelon form of C. When this matrix has an identity
matrix at the lefthand side, the righthandside is the unique solution of the system (4.11). In
this case, the system is nonsingular.
Overdetermined system
The
row reducedecholon
form does not always contain the identity matrix. Suppose A =
1 2 1
and b = . In that case, we find the subsequent matrices
2 4 3
1 2 1
C= , (4.20)
2 4 3
1 2 1
C1 = , (4.21)
0 0 1
1 2 0
C2 = . (4.22)
0 0 1
Here, C2 is the row reduced echelon form. Note, that the last line of this matrix represents
0x1 + 0x2 = 1.Of course,
this
equation cannot be solved, such that there exist no solution
1 2 1
satisfying A = x= . The system is overdetermined.
2 4 3
48
briefly illustrate the last two aspects.
Remark: When calculating numerically within the Symbolic Toolbox, you will make use
of the numerical Maple algorithms instead of the numerical MATLAB algorithms.
Number representations and rounding errors All values with which MATLAB cal-
culates are represented with a finite number of digits. The computer rounds all real numbers
to a number that fits the representation that is employed.
Internally, MATLAB calculates with a bigger precision than is represented on the screen.
The fact that the output representation can give rise to unexpected results, becomes clear
from exercise 4.21: Changing the output representation.
There we see that ‘rounding errors’ can influence the result. Use help format for more
information about the possible representations of MATLAB output. The role played by
rounding errors in calculations can often be reduced by cleverly organising the algorithms.
Data errors Other errors that can occur are ‘data errors’. In exercises 4.22 and 4.23 we will
illustrate that, when solving Ax = b, a small change in the data can have big consequences
for the solution. Here the intrinsic properties of the matrix A play a role.
50
Direction field of differential equation
2
1.5
0.5
0
q2 = ẋ
−0.5
−1
−1.5
−2
−2.5
−2.5 −2 −1.5 −1 −0.5 0 0.5 1 1.5 2
q1 = x
that satisfies the differential equation. For example, in the above example, a system with
initial position x0 = 1.5, ẋ0 = 0 has the solution:
r r !
k c2
x(t) = 1.5e− 2m t cos
c
1− t . (5.3)
m 4km
Plotting this function in time yields the trajectory depicted in Figure 5.2.
This trajectory can also be plotted in the phase plane, such that one obtains Figure 5.3.
As can be seen in this figure, the vector field is always locally tangent to the trajectories
q(t). Therefore, these pictures can be used to visualize many different trajectories. In our
example, according to the phase plane representation, all trajectories apparently encircle the
origin and converge to it. Such dynamics is expected from a weakly damped system.
ẋ = f (x) (5.4)
could be computed analytically. Although this is always possible for linear differential equa-
tions, in general no analytical solution exists. In that case, one has to use numerical solution
techniques to approximate a solution.
Usually, solving a differential equation numerically requires a correct solver to obtain accurate
results. However, a numerical obtained solution will give an engineer less information as an
52
analytical expression. For example, with a complete algebraic expression, it may be possible
to determine the trajectory for different initial conditions or prove stability of a system. In
general, a new numerical solution has to be found, when e.g. the initial conditions change.
The following section explains the use of numerical solvers, and how to interpret the results. In
Section 5.3, the use of MATLAB for analytical solutions of differential equations is discussed.
For the numerical calculation (or rather, approximation) of the solution of a differential
equation, one uses algorithms that are related to the Euler algorithm. Briefly, the Euler
algorithm boils down to the following. Even though one does not know the solution of the
differential equation explicitly, one does know the derivative of the solution in every point
(this is given by the right hand side of the differential equation), or, in other words, one
knows what the direction field of the differential equation is. This direction field is now used
to approximate the solution. From a given initial value, the next point of the solution is
calculated by moving from the initial value in the direction of the direction field. From the
point obtained in this way, one does the same again, etc. So the quality of the approximation
of the solution depends on the initial value, the direction field, and the step size.
In MATLAB, differential equations can be solved numerically with the commands ode45,
ode23 or ode15s. The underlying algorithms of ode45 and ode23 make use of Runge-Kutta-
Fehlberg integration with variable step size, i.e., the algorithm increases the step size when
the solution varies less. ode23 uses the second and third order formulas, while ode45 uses the
fourth and fifth order formulas. The routine ode15s uses another integration routine. This
routine is specialized in problems, that the previous routines have problems to deal with:
so-called stiff differential equations.
The mentioned routines can be applied to sets of first order differential equations of the form:
dy
= f (t, y) (5.5)
dt
Here y is the state vector and f the vector valued function that gives the time-derivative of
the state vector as a function of t and y.
Throughout this Section, extensive use is made of function-files to facilitate numerical solving
of differential equation. For an explanation of these, see Section 1.6, under ”User defined
functions”.
The form in which ode23 is used, is:
Here ‘filename’ is the name of the .m file in which the differential equation is defined, [t0 , t1 ]
the time-interval over which the differential equation is solved, and y0 the vector with initial
values. The algorithm in the program ode23 first determines in a point the derivative y ′ of the
function defined in the function file ’filename’. With this, the next point is determined, etc.
The algorithm itself determines with which time steps it goes through the interval [t0 , t1 ].
54
>> ode23(’deq’,[0,1],[2,8])
the graphs of x1 (t) and x2 (t) are drawn, since by default the ‘OutputFcn’ odeplot is used.
Note that you could also have written the file ‘deq.m’ in the following way:
The solutions of differential equation (5.2) are curves in the [t, x1 , x2 ]-space, which are given
by [t, x1 (t), x2 (t)]. The direction field is given by the tangent vectors to the solution curves,
i.e., by the vectors [1, ẋ1 (t), ẋ2 (t)]. Note that you can derive the direction field by means
of the right hand side of the differential equation, so you do not need to know the solutions
explicitly. In general the explicit dependency on time is omitted and the solutions and the
direction field are only plotted in the [x1 , x2 ]-plane. So, in fact, the projection on the [x1 ,
x2 ]-plane is being drawn. This plane is also called the phase plane or state space (the state
of the system at time t is given by [x1 (t), x2 (t)]). The projected solution is also called an
integral curve. In a given point [x1 (t0 ), x2 (t0 )] of the state space, the direction vector can be
calculated by using the differential equations given. In equation (5.2), the direction vector
for the point [x1 (t0 ), x2 (t0 )] = [1,2] is given by [ẋ1 (t0 ), ẋ2 (t0 )] = [5*1-2*2, 7*1-4*2] = [1,-1].
The direction field is obtained by determining the direction vector in every point of the state
space. To draw a direction field in MATLAB, you first need to indicate the points in the [x1 ,
x2 ]-plane where you want to draw the direction vector. The command:
produces a matrix X for which every row is equal to the vector -1:0.1:1 and a matrix Y
for which every column is equal to the vector -2:0.2:2. By combining these matrices elemen-
twise, you obtain grid points [x,y], where x traverses the vector -1:0.1:1 and y traverses the
vector -2:0.2:2, i.e., the points [Xij ,Yij ]. The matrices X and Y can now be used to perform
calculations in the grid points. For example, U = 5X − 2Y and V = 7X − 4Y calculates
the components [U,V] of the direction field in every grid point for equation 5.2. To draw the
direction field in a number of grid points, you can use the MATLAB command quiver. The
command:
>> quiver(X,Y,U,V)
draws the vectors with components [Uij ,Vij ] in the points [Xij ,Yij ]. The vectors are scaled
automatically. As a consequence of this, sometimes the direction field becomes somewhat
unclear. In that case, reducing the number of grid points often clarifies the direction field.
56
%% script file to analyse duffing equation.
clear all;
close all;
figure(3)
plot(t,Q(:,2))
xlabel(’t’);
ylabel(’q_2’);
58
2
1
q1
−1
−2
0 5 10 15 20
t
0.5
q2
−0.5
−1
0 5 10 15 20
t
0.8
0.6
0.4
0.2
q2 = ẋ
−0.2
−0.4
−0.6
−0.8
−1
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
q1 = x
60
Chapter 6
Programming in MATLAB
6.1 Programming
This chapter introduces programming in MATLAB. The programming language (i.e., the
structure of the commands and the set of commands) in MATLAB is ideally suited to learn
the basic principles of programming, and after that to solve all kinds of problems. In this
course, the emphasis is on learning to read existing programs, and learning to write or change
programs. For this, it is important that you understand the basic principles of programming
and that you are able to apply these principles yourself.
A computer program is nothing else but a series of consecutive commands that are executed
by the computer. The ‘order’ and the number of commands does not need to be decided
beforehand, but can depend upon initial values or the value of intermediate results. This is
achieved by imposing a route (flow) through the commands. This makes a program as flexible
as possible.
• variables or unknowns
• flow constructs like e.g. if... then ... and for... do loops, with which the order and the
number of operations can be controlled
62
1. analyse the problem and determine a solution strategy (on paper)
In this course, we will mainly consider points 3 and 4, and you will learn important elements
and constructs from programming languages that you need to write a good program.
First we recall some parts of Chapter 1. Variables in MATLAB are stored as arrays. You can
access the contents of these arrays elementwise. A colon (:) indicates a whole row or column.
>> A = [1 2;3 4]
A =
1 2
3 4
>> A(2,1)
ans =
3
>> A(:,2)
ans =
2
4
>> A(1,:)
ans =
1 2
• start with a letter (so this is allowed: X51483 while this is not allowed: 1abcd)
64
When step is omitted, a step size of 1 is used by default.
% definition of constant n
n = 10;
% producing an array with n rows
% and 1 column, filled with zeroes
A = zeros(n,1);
% fill this column with values from 1 up to
% n in a FOR loop
for k = 1:n
A(k,1) = k;
end
A % print the result on the screen.
This loop works as follows: after the for command, the loop variable k is given the value 1,
and the program lines until the end are executed. Thus, A(1,1) is given the value 1. After
the end command, MATLAB jumps back to the for line, and the loop variable k is given the
value 2. After this, the program lines are executed again: A(2,1) is given the value 2. This is
repeated until the last step, where the loop variable k is given the value 10. After this, the
program continues with the lines after end, where A is printed on the screen.
for k = 1:n means ‘for k is 1 up to n with steps of 1’. You can also use larger steps to
go from 1 to n, or start with another value: for example, for k = 2:2:10 means ‘for k is 2
up to 10 with steps of 2’ (i.e., 2,4,6,8,10). Of course you are free to choose other loop variables
like, for instance, a and/or b.
Example 6.2
In this loop the value of p is raised by one every time the program goes through the loop.
When the program goes through the loop for the first time, the new value of p becomes equal
to the old value of p (which was 0) plus 1, so p becomes 1. So this is an assignment
statement and not an equation. This kind of assignment construction is convenient to
use to keep track of a counter or a summation within a loop construction.
It is also possible to nest one or more for loops. By using this, you can easily fill an n × m
matrix by going through the matrix element by element:
Example 6.3: Give each element of a matrix a random value between 0 and 1
66
Relational
< lower than
<= lower than or equal to
> greater than
>= greater than or equal to
== equal to
~= not equal to
Logical
& and
| or
~ not
% determine the number of time steps in array t with the command size
n = max(size(t))
Check that, due to the fact that we have initialised f at 0, this if-loop can be simplified.
Example 6.5: Using a for-loop and conditional tests to calculate the inner product of two
vectors.
To this end, we write a new function m-file, i.e., we create our own MATLAB command
to calculate the inner product. We call our new command inprod. To realise this, we write
a new function m-file ‘inprod.m’. We will call the two vectors we want to multiply in this file
a and b. We will call the output argument result.
68
choice = input(’Enter an integer between 1 and 10’)
if choice == n
stop = 1;
disp(’*** ***’)
disp(’You have won!!!!’)
disp(’*** ***’)
else
disp(’Sorry, incorrect: next player please’)
end
end
All programs that have a certain goal to achieve. For example, the goal of a script file may
be, to plot the function f (x) in the interval 0 ≤ x ≤ 10.
Usually, some intermediate steps have to be taken to achieve the goal. In our example, the
following steps are needed:
In addition, it is wise to clear all variables at the beginning of your program. Hereto, the
command clear all can be added.
Of course, the number of steps will increase when obtaining the goal is more difficult.
When you want to write a program achieving a certain goal, it is advisable first to determine
all steps that are needed. This will be done in a list of steps, that are needed. When you
know your sequence of steps will achieve the goal required, you can start writing your m-file
according to your designed sequence of steps.
To make your Matlab files understandable to others, and to make it easier for yourself to use
them later, you should add comments (with a % character in front of it) in your file, that
clarify the step you are programming in a certain part of your code.
In our example, the program design given above will yield the following m-file to plot the
function f (x) = arctan(2x3 ) on 101 points. When a smoother plot is required, more points
should be used.
70
Another, somewhat more intricate option, is to use the MATLAB Debugger. This is built
into the Editor, and allows you to go through the program step by step, so that you can see
where the error occurs. You can also indicate so-called break points. The program then runs
from break point to break point and pauses at these break points. Type doc debug for more
info, the link under ”GUI Alternatives” may be helpful as well.
Example 6.7: Suppose you want to create an 10 × 8 array B, where each element bij is
chosen randomly,√with uniform distribution in [0,1]. Afterwards, create an array C, such that
cij = 1 if bij < B̄, and cij = 0 otherwise, where B̄ represents the mean of the squared
m
1 XX 2
elements of B, i.e. B̄ = bij .
mn
i=1 j=1
Hereto, first the following program is written, where the first two characters of each line
represent the line numbering:
However, running this file in MATLAB yields outputs for B and Bbar and the following error
message:
72
Metal Density Specific heat Melting point Young’s modulus
1. Steel 7.85 g/cm3 486 J/kgK 371 K 209 GPa
2. Gold 19.32 g/cm3 130 J/kgK 1357 K 74,5 GPa
... ... ... ... ... ...
>> metals(1).name=’Steel’;
>> metals(1).density=7.85;
>> metals(1).specific_heat=486;
>> metals(1).melting_point=371;
>> metals(1).youngs_modulus=209;
>> metals(2).name=’Gold’;
>> metals(2).density=19.32;
>> metals(2).specific_heat=130;
>> metals(2).melting_point=1357;
>> metals(2).youngs_modulus=74.5;
In the above example, fields were created by using the dot ‘.’ after the main variable name.
To see the field names of the structure variable, just type the variable name, or alternatively,
use the fieldnames function, e.g.
>> fieldnames(metals)
To access the value of only one field, type the variable name, index, and field name, e.g.
>> metals(1).name
To see the actual content of all fields for one index of the structure (i.e., all properties of one
metal), type the variable name with the appropriate index, e.g.
>> metals(1)
74
7.2 Creating a block diagram
Most dynamical systems can be represented in a block diagram. Thereto, a differential equa-
tion is splitted in simple blocks. Arrows connecting blocks are signals. The most used blocks
are given in the following table:
1 Rt
Integrator x s y y(t) = 0 x(s)ds
Integrator
x z
Sum z =x+y
y
x 2 y
gain
Gain or y = 2x
y 2 x
gain
With these blocks, most differential equations can be described. This is done in four steps:
4. The signals entering the summation are computed by means of gains, multiplying known
signals or are inputs. In block diagrams, inputs are represented by arrows pointing
towards the blocks and outputs as arrows pointing out of the blocks.
In modeling differential equations, one should prefer the use of integrator blocks instead of
differentiation blocks.
Remark: This constructive approach can also be used for more complex systems, for example
systems in the form:
ẋ f (x, y, t)
= (7.2)
ẏ g(x, y, t)
To clarify the steps, a block diagram is constructed for the system (7.1), i.e.
2. Integrating this state once, we obtain ẋ. Integration of ẋ yields x. This is shown in the
figure below. In this figure, ẍ is represented by ddx and ẋ by dx.
76
Hereto, blocks from the Library Browser should be dragged towards the model while holding
your left mouse button.
In the library browser, you will find the integrator block in the category ”Continuous”, the
gain and sum block are part of the category ”Math Operations”. When a block is inserted in
the model, one can flip the block (press the right mouse button on block, select Format>Flip).
To connect two blocks, click on the >> exiting the first block, hold your right-mouse-button
and drag a line towards the >> entering the second block. You can give a name to a signal
by double-clicking on the connection.
Sometimes, you will need to split a signal, for example the signal dx in the example of the
previous section. Hereto, first make one of the connections, click on the >> entering the third
block you want to connect, hold your left-mouse-button and drag a line towards the already
existing connection.
78
example, a gain-block with gain ”k” will work properly, when a scalar ”k” is available in the
MATLAB workspace.
To save your model, press the ”save” button in the toolbar of your model window. Simulink
models will be saved with the extension .mdl. Later, you can open these models by selecting
the file saved.
Please note, that the Library browser contains many more blocks as mentioned in this section.
When you double click on a certain block in the library browser, you will see the purpose and
parameters of the block.
To run a simulation of your Simulink model, you can select the button ”Start Simulation”
on the toolbar of the model. Take care, that the correct initial conditions are used for the
integrator blocks. The simulation will finish when the maximum simulation time is reached.
If this takes to long, you can terminate your simulation in the meantime by pressing the ”Stop
Simulation” button on the toolbar.
When the simulation is stopped, you can double-click on a scope to see the signal over time.
Signals send to ”To Workspace” or ”To file” blocks are created in your workspace, or in the
file in the current directory, respectively.
Simulation parameters
To edit the parameters used by Simulink to simulate the behavior of the system, click on
Simulation>>Configuration Parameters. A screen similar to the one below will open:
Simulation time
In this window, you will be able to set a start and stop time for your simulation. Note, that
these times represent the simulated time, which usually differs from the computation time.
80
Phi 1
Phi 1
−a*x^3+b*x^2+Phi 1*x
u^2 b
x^2 b Phi 2
u^3 a Phi 2 1
gz
y (t )
gy
gy
sum 2
u^2 d
x^.2 d
Phi 3
dy /dt 1
Phi 3
s y (t )
c 1 y(t)
Beta
y (t )
Beta
sum 3
x0 1
s r
dz / dt s z(t )
x0
r z(t)
sum 5
Integrator z (t)
sum 4
z(t )
0.5
−0.5
x(t)
−1
−1.5
−2
−2.5
100 200 300 400 500 600 700 800 900 1000
time [ms]
82
A.1 Exercises chapter 1
Exercise 1.1: Entering commands
You are supposed to perform the following exercises in the specified order. Before entering
each of the commands, think about the output on the screen and the result of each exercise.
a) >> a = 1+2+3+4+5+6
b) >> b = 1+2+3+4+5+6;
c) >> b+3
d) >> 1+2+3+4+5+6
e) >> c = 10*ans
Enter the array 0:900000 and make sure the output appears in the MATLAB Command
Window.
Perform the exercise again and and use the key combination ‘ctrl-c’ quickly. What is the
effect?
a) Enter >> a = [2,3,4 and use the ‘return’ key. Finish the exercise.
b) Enter >> a = [2,3,4 and use the ‘return’ key. Interrupt the input of the exercise.
Define the variables u = [2 3 4] and v = [1 5] and then delete them. Check if the variables
are actually deleted.
>> f = 2
and
>> g = 3 + f
84
Exercise 1.10: Error messages with array operations
x3
Consider the function: f (x) = 1+x2
We want to declare the row vector [f (0), f (0.2), . . . , f (1.8), f (2)] to the variable f . To perform
the exercises below you first have to enter the array x with arguments (0, 0.2, . . . , 1.8, 2.0).
Thus; >> x = 0:0.2:2
REMARK:
IF YOU GET A RESULT, ALWAYS CHECK THAT RESULT!
Make for the following functions f the array [f (0), f (0.1), . . . , f (2)].
a) f (x) = x2 + 2x + 1
3x
b) f (x) = 1+3x
x√
c) f (x) = 1+ x
Perform the exercise: >> a = rand(5,5). This command generates an array with 5 rows and
5 columns where each element is chosen arbitrary between 0 and 1. Make an array with all
elements of a which are smaller than 0.3.
t√
f (t) = 1+ t
Make the row vector [f (0), f (0.1), . . . , f (1)] by using array operations and the function sqrt.
86
Exercise 1.20: Script file
x = 0:0.1:2
y = abs(x.*sin(2*pi*x))
figure
plot(x,y)
title(’f(x) = |x*sin(2*pi*x)| on the interval [0,2]’)
axis([0 2 0 2])
shg
Open the ”MATLAB Editor/Debugger” via the menu ”File\New\M-file” and enter the fol-
lowing function f :
function y=f(x)
y = x.^2+exp(x);
function y=f(x)
y = x.^2+exp(x);
In the definition of the function f , with respect to the previous exercise, the semicolon (;) is
left out. What is the effect?
Make your own function g in MATLAB. For this, use the MATLAB functions max and zeros.
88
Exercise 1.29
Exercise 1.30
1 + 22 + 32 + 42 + · · · + 1992 + 2002
Exercise 1.31
x
f (x) = 1+x
Exercise 1.32
Draw a circle with radius 1 and center (0,0) in a square with −2 < x < 2 and −2 < y < 2.
Make sure that the circle looks round!
HINTS:
First make a list of x-coordinates and a list of y-coordinates. Draw the circle. Change the
shape of the figure by using the command >> axis in different combinations.
Exercise 1.33
2
t ,0 ≤ t ≤ 2
f (t) = f (t − 2) ,2 ≤ t (A.2)
f (t + 2) ,t < 0
Define this function in MATLAB. Make use of the command >> mod. For a number r the
command >> mod(r,2) returns a number s in such a way that 0 < s < 2 and s and r differ
are a multiple of 2 from each other. Thus f (r) = f (s) = s2 .
Make sure that the function is also capable to work with arrays.
90
b) Examine which digits in the different solutions remain the same.
b) Compare the value of the zero you solved numerically with the exact zero.
Determine the zeroes and extrema of the function f (x) = e2x − 4ex + 2.
Hereby, choose a suitable interval to draw the function f with MATLAB. A suitable interval
should give a clear view all zeroes and extrema of the function.
3
1
Z
(x3 + x2 + )dx (A.3)
1 x2
Evaluate the integral for different levels of accuracy. Compare your results with the exact
value of the integral: 88/3.
When you are done, make sure that MATLAB shows 5 digits on the screen again.
Exercise 2.9
b) Why does the function f (x) has a maximum on the interval [0,∞]?
c) Determine the maximum on the interval [0,∞] with the command fminbnd.
d) What is the error between the result found in question c and the real value of the
maximum?
92
A.3 Exercises chapter 3
3
1
Z
(cos(x − 1) + )dx (A.8)
1 x
The boundaries of this interval are not taken into account in this exercise.
Exercise 3.4
arctan(x)
a) f (x) = 1+x2
1+sin(x)
b) f (x) = (1+cos(x))2
Exercise 3.5
Enter the following exercises in order and give an explanation for the output.
a) >> x^1/3
b) >> x^(1/3)
94
Exercise 3.10
In MATLAB plot the function f (x) = 3 + sin(x) on the interval [−1, 2].
Make sure that the origin (0,0) is visible.
Exercise 3.11
>> syms x
>> ezplot(asin(sqrt(x)),[-5,5])
Exercise 3.12
b) Ascribe the value of question a) to n and calculate the integral again. Is the answer
correct this time?
Exercise 3.13
Exercise 3.14
2
log(1+x)+ x
Consider the function f (x) = (1+x)2 2 .
Enter the following MATLAB statements:
>> syms x y
>> y = (log(1+x)+x^2/2)/(1+x)^2
a) Calculate f ′ (x).
b) Calculate f ′ (1).
96
Exercise 3.20
2 √
The function f (x) = e−x (x + x) has a maximum in the neighborhood of x = 0.6.
b) Calculate f ’(x0 )
Exercise 3.21
In MATLAB determine the 10th derivative of the function f , i.e. f (10) (x), x 6= 1.
2 +2x−3
f (x) = sin( x x−1 )
98
Exercise 4.7
Make a column vector initial value a, final value a + 20 and step size 2.
Note that when computing the transpose, MATLAB assumes that the symbolic variables
may have complex values. One can solve this by using the command:
>> x.’
Using the dot ’.’ implies that the operations is performed element-wise on every entry of
the vector.
Another possibility is to declare the variable a as a ‘real’. Look up how you should do
this using the help function. Type help sym or help syms
Exercise 4.8
Enter the following matrices using commands like eye and zeros:
d) A random 5 × 5 matrix
Exercise 4.9
100
Exercise 4.14
Exercise 4.15
Exercise 4.16
Exercise 4.17
102
When an answer from MATLAB is required with more digits, this can be done by use of the
command >>format long.
d) Use the command >>format long and again try to compute A10 . Compare this answer
with the one of question c).
Apparently, rounding errors may be visible in the final results. Use >> help format for more
information about possible MATLAB outputs. The influence of rounding errors in the final
results of computations can usually be reduced by means of designing a good algorithm.
Exercise 4.22
and
2y1 + y2 + 5y3 + y4 = 9
y1 + y2 − 3y3 − y4 = −5
3y1 + 6y2 − 2y3 + y4 = 8
2y1 + 2y2 + 2y3 − 3y4 = 3
b) Solve the first system of equations with the righthandsides (32.1, 22.9, 32.9, 31.1) and
(32.01, 22.99, 32.99, 31.01). Solve the second system of equations with right hand-
sides (9.1, −5.1, 7.9, 3.1) and (9.01, −5.01, 7.99, 3.01). What is the effect of these minor
changes?
By slightly changing the coefficients of the equations and studying the effect of these changes
to the solutions, one can get an impression of the sensitivity for small data errors.
c) Change the elements of the original matrices by adding a matrix 0.1*rand(4) to both
of them, such that for each element, a random number between 0 and 0.1 is added.
Solve the systems of equations with the original right-hand sides.What is the effect of
the changes?
d) Systems of equations that are sensitive for small data changes have ill-conditioned ma-
trices of coefficients. Which of the two systems has the most well-conditioned matrix of
coefficients?
104
Exercise 4.27
The linear momentum P of a system with n particles with masses m1 , m2 , . . . , mn and veloc-
ities v1 , v2 , . . . , vn is given by:
P = m1 v1 + m2 v2 + . . . + mn vn
Consider two particles with velocities v1 = (2, 2, 2)T and v2 = (5, 7, 9)T . These particles will
make a collision. After this collision, their velocities are w1 = (4, 6, 4)T and w2 = (4, 5, 8)T .
Assuming preservation of linear momentum during impact, what is known about the masses
of both particles?
Exercise 4.28
b) Draw the triangles with corner points D 2 pi and D 3 pi in the same graph.
d) What matrix should be used, such that multiplication with this matrix yields an image,
mirrored in the x-axis?
106
Exercise 5.5
b) Plot the solution curves in the phase plane (in 1 figure) with initial conditions:
(x1 (0), x2 (0)) and (2,8), (2,7), (0.1,0.1), (-2,-8), (-2,-7), (-2,-6), (-0.1,-0.1) respectively
for t ∈ [0, 1].
HINT: It is recommended to fix the axes with the command axis, e.g. x1 and x2
between -10 and 10.
Exercise 5.6
a)
1) Determine the solution of this equation for k = 0.
The solution describes a vibration. You can visualise this by plotting the solution.
2) Is the vibration damped?
3) Is the vibration periodic?
4) What is the frequency of this solution?
b)
1) Determine the solution of this equation for k = 1.
2) What is the eigenfrequency of the system?
The solution describes a vibration. You can visualise this by plotting the solution.
3) Is the vibration damped?
4) Is the vibration periodic?
5) What is the frequency of the solution?
Plot the solution and the function e−kt in the same figure.
c)
1) Determine the solution of the equation:
The solution describes a vibration.You can visualise this by plotting the solution.
108
One can show that p(t) and r(t) satisfy the following relation:
This equation gives a closed curve in the (p, r)-plane as result for every constant. The popu-
lation develops itself thus according to a periodic pattern.
Plot the solutions p(t), r(t) and the corresponding curve in the phase plane for some
self chosen initial conditions and time-interval. Notice that a stationary point (constant
solution) exist in the phase plane at p = ab11 = 10 and r = ab22 = 25.
REMARK: It could be that the plotted phase curve is not exactly a closed curve due to
numerical reasons in MATLAB but a spiral curve. This only occurs when plotting
on large i-intervals. ode45 gives the best result in this case.
Exercise 5.9
Here x denotes input of the drive and y the response of the output.
m = 870 kg, k = 70000 N/m, c = 5000 N/ms (one can think of the suspension of a car). For
the input we suppose x(t) = sin(t).
Exercise 5.10
As like the previous exercise consider a driven mass-spring-damper system given by the equa-
tion:
110
A.6 Exercises chapter 6
Exercise 6.1: Script file
a) Make a script file ‘test1.m’ in which MATLAB successively performs the following:
- Delete all variables from the memory.
- Define a row vector x =1:0.1:10.
- Calculate y = sin(x) − cos(x).
- Plot y as function of x.
For later use, add comments to your script file so you can understand why you made
the file.
a) Make a function file ‘test2.m’ in which MATLAB for an arbitrary input x the output y
calculates and displays on the screen.
- Calculate y = sin(x) − cos(x).
- Plot y as function of x.
For later use, add comments to your script file so you can understand why you made
the file.
Pay attention! that the function name is the same as the corresponding filename.
b) Test the function file with a = 1:0.1:10 and, if necessary, debug the file.
c) Call up the commentary of the file with >> help test2
d) Explain the difference between a script file and a function file.
function b = kwad(r)
in which a row vector is squared element-wise. Do this without using the command >> .^2.
112
a) Work out the problem on paper.
c) Test the function file with the column [1;2;3;4;5;6;7] and, if necessary, debug the file,
function B = replace2(A)
in which all elements of a matrix greater than 5 are replaced by 0. Do this without us-
ing the command >> find.
c) Test the function file with the matrix [2 12;5 8] and, if necessary, debug the file.
This function must divide a number x by 2 till the new obtained number is smaller than
2.
- x: An arbitrary number.
114
4) ,5) Fill the resulting matrix, element after element, with a for-loop. The value of
each element is a summation of different product terms (an inner-product). For
this a new for-loop needs to be implemented in the first for-loop with the following
assignment instruction:
sum = sum + change (the new value of the sum becomes the previous value of
the sum plus the value of the change)
c) Test the function for all kinds of matrices A and columns B. Check the results with
MATLAB’s own matrix multiplication.
Exercise 6.11
Extend the function file ‘matmult.m’ from exercise 6.10 to a multiplication of two matrices.
Save this file under the name ‘matmult2.m’.
P.S. This exercise is meant for the die-hard MATLAB guru’s (which you will all be at the
end of this course!)
116
Exercise 7.5: Equation
3
A = B + 5.
4
Hint: B can be any input. However, to run the file and check the result, use an arbitrary
source, such as a ramp.
In this exercise, proceed as follows:
1. Simulate the trajectory x(t) of the following differential equation for 10 seconds:
where A = −0.5, B = 3 and u(t) = 1. Hint: First construct a block diagram. Build this
diagram in Simulink, add sinks and sources.
Simulate the trajectory x(t) of the following differential equation for 10 seconds:
ẋ = −x − xy
ẏ = x2 − y + u,
1. Run a simulation and save both x(t) and y(t) to the workspace.
3. Now, use u(t) = 0.01 sin(t), rerun the model and plot the new trajectory in phase plane
118
B.1 Answers chapter 1
Answer 1.1
a) >> a = 21
The result of the sum 1 + 2 + 3 + 4 + 5 + 6 is ascribed to the variable a. De output
a = 21 appears in the MATLAB Command Window.
b) >> ()
The result of the sum 1 + 2 + 3 + 4 + 5 + 6 is ascribed to the variable b. The output is
not visible in the MATLAB Command Window because the semicolon sign (;) is used.
However, it is possible to call up the variable b.
c) >> ans = 24
The output of the sum b + 3 appears in the Matlab Command Window as ans = 24.
No variable is ascribed to this calculation. In such a case the result is automatically
ascribed to the variable ans.
d) >> ans = 21
Also in this exercise no variable is ascribed to the calculation. The output is thus as
follows: ans = 21.
e) >> c = 210
The result of this exercise depends on the previous answer because the variable ans is
used in this calculation. Assume that ans = 21 (obtained from exercise d), then the
answer on this question becomes: c = 210.
Answer 1.2
By using the key combination ‘ctrl-c’ you can interrupt a calculation or output in MATLAB.
The effect of the key combination ‘ctrl-c’ in this exercise is that the output is early canceled,
considering the fact that you apply the key combination in time.
OUTPUT SUMMARY:
>> 0:90000
key combination: ctrl-c
Answer 1.3
a) >> a = [2 3 4
The exercise a = [2, 3, 4 can be finished, after entering the ‘return’ key, by closing the
array yet with a bracket ] and again enter the ‘Return’ key. The array [2 3 4] is now
ascribed to the variable a.
b) >> ctrl-c ()
The exercise a = [2, 3, 4 can be interrupted by using the command ‘ctrl-c’. The calcu-
lation is then stopped and nothing is ascribed to the variable a.
120
Columns 1 through 7
Columns 8 through 14
Columns 15 through 21
Answer 1.9
INPUT SUMMARY:
>> a = 9:-1:0
Answer 1.10
a) The error in this formulation is captured in the division (/). In this way a matrix-
wise division is used (which has a number as result) instead of an element-wise division
(which has an array as result).
b) The error message means that you used the power sign (∧ ) wrong. When you want to
calculate a matrix to the power n the matrix has to be square. The first term x^3 must
therefore be replaced with the term x.^3.
Answer 1.11
Enter the functions f . Pay attention that you make use of element-wise calculations (thus
with dots!).
b) >> f=(3.^x)./(1+3.^x)
Entering ‘f =’ is not necessary. Although it is useful when you want to separate different
equations.
122
PAY ATTENTION: You do not have to use a dot before the division sign (/) because this
time a division of 2 numbers is concerned.
Answer 1.16
Answer 1.17
Plotting a figure in MATLAB can be done in several ways. In this answer a plot is made by
typing several commands.
INPUT SUMMARY:
Answer 1.18
Answer 1.19
The reason that you can better save the commands for plotting a figure than the figure itself
is simply because then you can see how you obtained that figure. If you want to adjust the
124
% and step size 0.1, without reproduction in the Matlab
% Command Window (;)
y = abs(x.*sin(2*pi*x));
% Enter the function: f(x) = |x*sin(2*pi*x)|
% also without reproduction in the MATLAB Command Window.
figure(1)
% Producing of figure 1
plot(x,y)
% Depicting the function y, with x on the x-axis and y on the y-axis.
title(’f(x) = |x*sin(2*pi*x)| on the interval [0,2]’)
% The title between the brackets is ascribed to the figure.
axis([0 2 0 2])
%% The axes of the figure are scaled by [xmin xmax ymin ymax]
shg
% The figure is presented on the foreground.
Answer 1.21
The file is saved in the current directory.On top of the MATLAB window you can find the
name of the current directory.
With the command >> dir you can call up the content of the current directory.
If you want to call up the function value of f for x = 1, it can be done as follows:
>> f(1)
ans =
3.7183
Answer 1.22
>> f(1)
y =
3.37183
ans =
3.7183
The output is not displayed on the screen when the semicolon (;) is used while the opposite
is true when the semicolon is left out.
Answer 1.23
In the following you will find a possible formulation for your own made function g(x) in
MATLAB.
126
→ Matlab
→ In Alphabetical Order
→ atan
Answer 1.27
This exercise can be solved in several ways. It is important that you find the way that is most
suited for you. In the following a possible solution is given.
INPUT SUMMARY:
→ You know that ‘sin’ is the MATLAB function name for the sine function, thus you are
going to use the MATLAB ”Help Browser” and the option ”Search”.
→ Click on the ‘yellow question mark’ in the MATLAB taskbar.
→ Select the header ”Search” in the ”Help Navigator”
→ Enter by ”Search for” the following: ‘sin’
→ ENTER
→ Now ‘sin’ appears in the the window below.
→ Choose for ‘sin’ and obtain the help information by double clicking.
Answer 1.28
ans =
Columns 1 through 5
Columns 6 through 10
Columns 11 through 15
Columns 16 through 20
Columns 21 through 25
Columns 26 through 30
128
>> clear all
>> f = @(x)(x./(1+x));
>> x = 0:0.01:4;
>> figure
>> plot(x,f(x))
>> xlabel(’x’); ylabel(’f(x)’)
>> grid
Answer 1.32
1.5
0.5
−0.5
−1
−1.5
−2
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
Answer 1.33
You can define a new MATLAB function by opening a new m-file and the type
>> function [output] = function_name(input).
The function in this exercise must be able to handle with arrays so therefore you need to
multiply element-wise (thus with a dot!).
INPUT SUMMARY:
or
130
Input Output
a) (x^3)/6 1.3333
b) x/(sqrt(1+x^2)) 0.8944
c) 2^(1/3) 1.2599
d) exp(1+x^2) 148.4132
e) x^3*sin(x^2) -6.0544
f) atan(x)/(1+x^2) 0.2214
132
3. x ∈ [1.5, 2.5]
10
0
f(x)
−5
−10
−15
−20
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2 2.5 3
x
134
Answer 2.7: Numerical determination of zeroes and extrema
a) A possible suitable interval to depict the extrema and the zeroes of the function is:
[-10,2].
b) An interval is suitable when it contains all extrema and zeroes. With this interval this
can be checked by extending the left and right bound of the interval. (HINT: Make sure
that enough digits are displayed).
f2_7(-10) = 1.99981840234210
f2_7(-100) = 2
f2_7(10) = 4.850770915466111e+008
f2_7(100) = 7.225973768125749e+086
At the left bound the function approaches 2 asymptotically, while at the right bound
it reaches to infinity. The extrema are in between, which is clear when using above
mentioned interval.
c) The position of the zeroes can be determined by choosing the right intervals. Next, the
command fzero can be used:
From the graph, it can be seen that the extremum is a minimum at:
>> quad(’x.^3+x.^2+(1./(x.^2))’,1,3,1e-6)
ans =
29.333333386482213
When choosing a smaller value for the tolerance the calculation will be slower but more
accurate. With that the comparison between the result and the exact solution ( 88
3 ) will be
better. When increasing the tolerance the opposite is true.
136
>> positionmax2 = fminbnd(’f2_10(x)’,pi,2*pi)
>> maximum2 = f2_10(positionmax2)
Answer 2.11
>> polyval(p,x)
ans =
Answer 2.12
1
y
fit
0.9
0.8
0.7
0.6
y, fit
0.5
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3
x
Coefficients:
138
0.4
0.35
0.3
0.25
f(x)
0.2
0.15
0.1
0.05
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
x
3.5
2.5
f(x)
1.5
Answer 3.5
The difference in output between the commands x^1/3 and x^(1/3) is caused by the absence
of brackets in the first case and the math rules that MATLAB operates with.
140
1
0.8
0.6
0.4
0.2
0.1
0.05
−0.05
−0.1
−0.15
d) intd =
1.3461e+003
142
p
sin(t2 ) (1 + t3 ) e−2t erf(x)
2
1 1
1.5
1 0.8
0.5
0.5 0.6
0
0
0.4
−0.5 −0.5
0.2
−1
0 −1
−1.5
0 1 2 −2 0 2 −2 0 2
t x x
a) INPUT SUMMARY:
>> syms t
>> ya = sin(t^2)*sqrt(1+t^3);
>> inta = int(ya,t,0,2);
>> figure
>> ezplot(ya,[0 2])
MATLAB returns the command, because this integral can not be determined exact.
b) INPUT SUMMARY:
>> syms x
>> yb = exp(-x^2);
>> intb = int(yb,x);
>> figure
>> ezplot(yb,[-3 3])
MATLAB gives a result including an error function. Since this function can not be
expressed in elementary function, the integral of part b) can not be calculated by MAT-
LAB.
Answer 3.10
Answer 3.11
The results of the particular MATLAB commands is shown in the first figure. De graph is
only given on the interval 0 ≤ x ≤ 1, because the function asin(x) is defined for −1 ≤ x ≤ 1
√
and the function x for x ≥ 0. A better drawing of the function can be made by adjusting
144
Answer 3.12
b) ans =
log(x)
This answer is not correct. It should be log(abs(x)). For positive x the answer is
correct.
Answer 3.13
The ‘symbolic toolbox’ uses a standard notation. It denotes a square root as ∧ (1/2). Hence,
sqrt(x∧ 2) is rewritten as (x∧ 2)∧ (1/2).
Notice that, in general, sqrt(x∧ 2) equals abs(x) and not just x. Therefore, MATLAB holds
on to the square root.
INPUT SUMMARY:
>> syms x
>> sqrt(x^2)
ans =
(x^2)^(1/2)
Answer 3.14
a) dy =
(1/(1+x)+x)/(1+x)^2-2*(log(1+x)+1/2*x^2)/(1+x)^3
b) ans =
0.0767
c)
Answer 3.15
Using the command ezplot you can draw symbolic functions. The minimum of the function
can be determined with the command fminbnd. The position, function value and value of
the derivative are 1.001, -0.23023 and 1.1876 respectively. The function f has two zeroes (see
figure). The coordinates of the zeroes are: (1.0986,0) and (0.6931,0).
146
>> xmin = fminbnd(char(y),1,2)
c) The function value and the value of the derivative can be found with:
>> syms x
>> y = exp(2*x)-5*exp(x)+6
>> x1 = fzero(char(y),[xmin,xmin+1])
>> x2 = fzero(char(y),[xmin-1,xmin])
The number of zeroes can also be determined by means of the command solve:
Answer 3.16
a) No answer
b) xmin =
1.0000
ymin =
-0.9993
zero_1 =
1.0415
zero_2 =
0.9526
Answer 3.17
Before you are going to determine the minimum, maximum and zeroes, it is wise to draw the
function first using ezplot. See the figure.
The x-coordinate of the minimum can be calculated with the command fminbnd. You can
148
SUMMARY OF INPUT:
>> hold on
>> plot(xmin,ymin,’r*’)
>> plot(xmax,ymax,’r*’)
>> plot(xzero1,0,’m*’,xzero3,0,’m*’,xzero3,0,’m*’)
>> xs = 0:0.01:2*pi;
>> ys = sin(xs)
>> hold on
>> plot(xs,ys,’r’)
Answer 3.18
a)
√ √
b) The function and the line do not intersect each other there, because | x sin( x1 )| < x <
1
4 when x < 1/16.
d) intersection =
0.3681 0.2500
Answer 3.19
The positive constant a, for which the equation ex = ax(1 − x) has exactly one solution
between 0 and 1, is in this answer determined graphically. The following approach is used:
150
>> syms x
>> y1 = exp(x);
>> x2 = 0:0.05:1;
>> figure
>> ezplot(y1,[0,1])
Answer 3.20
a) x0 =
0.5992
b) ans =
-5.8133e-006
152
x y
Minimum 1.8409 -0.3795
Maximum 0.3384 0.1505
Zero 1 0.8030 0
Zero 2 2.7923 0
1. () Between brackets
2. ∧ Raising to power
3. ∗ Multiplying
4. / Dividing
5. sqrt Extracting roots
6. + Addition
7. − Subtraction
154
Answer 4.4
Symbolic objects can be entered as matrix elements. In order to enter matrix elements a11 ,
a12 , a13 , a21 , a22 and a23 you should declare them as symbolic objects first using the command
>> syms.
INPUT SUMMARY:
>> syms a11 a12 a13 a21 a22 a23
A = [a11 a12 a13; a21 a22 a23]
Answer 4.5
In principle, a row vector is a matrix with one row. Vectors are entered in the same way
as matrices. However, when the step between successive elements of the row vector are the
same, you can generate such a row vector easily by entering:
INPUT SUMMARY:
>> a = -1:0.5:9
or between brackets, since we are making a vector:
>> a = [-1:0.5:9]
Answer 4.6
In principle, a row vector is a matrix with one row. Vectors are entered in the same way
as matrices. However, when the step between successive elements of the row vector are the
same, you can generate such a row vector easily by entering:
Note that the step size should be a negative number for the row vector in this exercise.
INPUT SUMMARY:
>> a = [9:-1:0]’
Answer 4.7
Since MATLAB assumes that symbolic objects can have a complex value, MATLAB computes
the conjugated values when taking the transpose. When you declare these symbolic objects
as real numbers, MATLAB knows that these variables can only have a real value. Therefore,
there are no problems anymore when taking the transpose and other matrix transformations.
INPUT SUMMARY:
>> syms a
156
2 1
-2 -1
>> A(2,:)-7*A(1,:)
ans =
0 -12 7 -20
Answer 4.10
Within the matrix A, the 2 × 2 submatrix, formed by the elements having indices (1,1), (1,3),
(3,1) and (3,3), is replaced by the 2 × 2 matrix which has all elements valued 10.
INPUT SUMMARY:
>> A = [1 2 -1 3; 7 2 0 1; 3 -2 -1 -1; 0 1 4 8]
A =
1 2 -1 3
7 2 0 1
3 -2 -1 -1
0 1 4 8
Answer 4.11
INPUT SUMMARY:
>> A = [1 2 -1 3; 7 2 0 1; 3 -2 -1 -1; 0 1 4 8]
A =
1 2 -1 3
7 2 0 1
3 -2 -1 -1
0 1 4 8
158
>> B1 = D*A
B1 =
1 2 -1 3 % b1_11 = d11*a11+0*a21+0*a31+0*a41
14 4 0 2 % b1_21 = 0*a11+b22*a21+0*a31+0*a41
9 -6 -3 -3
0 4 16 32
>> B2 = A*D
B2 =
1 4 -3 12 % b2_11 = a11*d11+a12*0+a13*0+a14*0
7 4 0 4 % b2_21 = a21*0+a22*b22+a23*0+a24*0
3 -4 -3 -4
0 2 12 32
Answer 4.13
INPUT SUMMARY:
>> v = [1 2 3 4]
>> a = v*v’ % a = v1*v1+v2*v2+v3*v3+v4*v4
a =
30
Answer 4.14
INPUT SUMMARY:
>> a = sym(’a’,’real’);
>> b = sym(’b’,’real’);
>> c = sym(’c’,’real’);
>> A = [1 2 a; b -3 2; 3 1 c]
A =
[ 1, 2, a]
[ b, -3, 2]
[ 3, 1, c]
a) >> B = A’
160
Answer 4.16
INPUT SUMMARY:
>> A*x % Check your solution. It turns out that x is a valid solution.
>> rref([A,b]) % The linear system Ax = b has multiple solutions. This follows
% the presence of free variables and the fact that the linear
% system has more free variables than equations.
>> AA = sym(A)
>> bb = sym(b)
>> xx = AA\bb
xx =
5 % This is another solution to the linear system.
0
-3
Answer 4.17
This exercise is a nice example of an overdetermined system. Producing the reduced row
echelon form shows this. The command A\b results in a vector x, but this vector is not a
valid solution. This can be checked by entering A*x.
INPUT SUMMARY:
>> A*x % Check your solution. The vector x is not a valid solution,
162
Inf
Inf
Answer 4.20
√
Studying the system of equations Ax = b with a = 6 yields the solution x = [1.6742, 0.5505, 0.2247]T .
INPUT SUMMARY:
>> Asub=subs(A,a,sqrt(6));
>> bsub=subs(b,a,sqrt(6));
>> xsub=Asub\bsb;
>> D=rref([A,b]);
>> xsol=D(:,4);
Answer 4.21
81 0 729 0
a) A2 = 3
,A = .
0 1 0 1
n
9 0
b) An = ,
0 1
Answer 4.22
c) Try yourself.
164
ans=
[3*b21, -b12+3*b22-3*b11]
[b21, -3*b21 ]
Answer 4.26
Answer 4.27
m1 v1 + m2 v2 = m1 w1 + m2 w2
Therefore, we find:
m1 v1 + m2 v2 − m1 w1 − m2 w2 = 0
INPUT SUMMARY:
Answer 4.28
166
B.5 Answers chapter 5
Answer 5.1
a) To obtain a solution of the differential equation you first have to make a function file in
the MATLAB Editor/Debugger with the following content:
Then you have to save the file under the name ‘filename’.
after which the matrices t and x are stored in the MATLAB memory.
>> plot(t,x)
b) If you leave out the specification [t,x] the solution is directly plotted in a figure. The
values of t and x corresponding to this solution are not stored in the MATLAB memory.
In this case we can speak of a ”real-time” solution.
1.4
1.2
0.8
x
0.6
0.4
0.2
0
0 0.5 1 1.5 2 2.5 3
t
168
1.5
0.5
−0.5
−1
−1.5
−1.5 −1 −0.5 0 0.5 1 1.5
Answer 5.4
Answer 5.5
Both the numerical and symbolic solution is given below for just one initial condition, namely
x1 (0) = 2 and x2 (0) = 8. The procedure is analogous for any other initial condition.
NUMERICAL SOLUTION:
Plotting the solutions for all initial conditions in the phase plane can be done numerically
with ode23 as follows:
>> ode23(’fn5_7’,[0,1],[2,8],odeset(’outputfcn’,’odephas2’))
>> hold on
- [0,1] represents the time interval in which the solution must be calculated.
170
8
2
x1, x2
−2
−4
−6
−8
−10
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
t
0
x2
−2
−4
−6
−8
−10
−10 −8 −6 −4 −2 0 2 4 6 8
x
1
2) The eigenfrequency
√ of the system is the solution of the homogenous problem which
is feig = 2 6.
3) The vibration is damped.
√
6
4) and 5) The vibration is periodic with frequency π Hz.
c) 1) y =
172
1.2
0.8
0.6
0.4
y(t)
0.2
−0.2
−0.4
−0.6
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t
Answer 5.7
a1) Plotting this differential equation in a symbolic way can be done as follows:
>> y = dsolve(’10*D2y+50*Dy+490*y=0’,’y(0)=0.2’,’Dy(0)=0’)
>> t = [0:0.01:3];
>> y = subs(y,t);
>> plot(t,y)
a2) Plotting of the solution in the phase plane is easiest by using separated equations like:
a3) Both methods mentioned above can be used to analyse the solutions for other initial
conditions.
174
0.6
0.5
0.4
0.3
y(t)
0.2
0.1
−0.1
−0.2
0 0.5 1 1.5 2 2.5 3
y
0.5
−0.5
2
x
−1
−1.5
−2
−2.5
−0.2 −0.1 0 0.1 0.2 0.3 0.4 0.5 0.6
x
1
critical damping, it will go to its equilibrium position in one movement. To force this
movement through this equilibrium position a higher initial velocity has to be taken.
Thus choose ẏ(0) high enough, for example ẏ(0) = −25. This effect is illustrated in the
figure below. Critical damping occurs when the solution of the characteristic polynomial
possesses 2 real solutions.
176
Answer 5.8
a) For the initial conditions y(0) = 10 and ẏ(0) = 10 the results are the following:
p(t)
60
r(t)
50
40
p(t), r(t)
30
20
10
0 5 10 15 20 25 30
t
18
16
14
12
r
10
4
10 15 20 25 30 35 40 45 50 55
p
b) No answer.
178
1.5
0.5
y(t)
−0.5
−1
−1.5
0 1 2 3 4 5 6 7 8 9 10
t
1.5
0.5
y(t)
−0.5
−1
−1.5
0 1 2 3 4 5 6 7 8 9 10
t
180
B.6 Answers chapter 6
clear all
x = 1:0.1:10;
y = sin(x)-cos(x);
figure;
plot(x,y)
1.5
0.5
y
−0.5
−1
−1.5
1 2 3 4 5 6 7 8 9 10
x
b) You can run the script file by typing >> test1 in the MATLAB Command Window.
c) Calling up the commentary of the function file can be done with the command >> help test1.
The result is the following:
a) No answer
182
- End: For-loop.
function b = kwad(r)
L = length(r);
for a = 1:L
b(a) = r(a)*r(a);
end
c) You can test the function file by typen the following text in the MATLAB Command
Window:
>> a = [1 2 3 4 5];
>> kwad(a)
ans =
1 4 9 16 25
a) No answer
b) No answer
ans =
0 1
4 9
a = input(’Do you want to know the date? Press 1 for ’yes’ or 2 for ’no’,
followed bij Enter’);
if a == 1
184
b) A possible function file ‘replace2.m’ is given by
function B = replace2(A)
c) You can test the function file by typing the following in the MATLAB Command Win-
dow:
ans =
2 0
5 0
p =
q =
1.6875
Error message 1:
186
Answer 6.10
D =
15
9
Answer 6.11
Pay attention that this function file is NOT the only solution for this problem! The pro-
grammer is responsible for the approach in solving the problem and thus for the result of
the function file. Every programmer has its own style. This is one of the most important
reasons to add comments to your script. Then it is possible for every other programmer to
understand the programme very quickly.
function D = matmult2(A,B)
188