Extensive MATLAB Guide
Extensive MATLAB Guide
R.P.J. Kunnen
Preamble
The aim of this course is to learn how to use MATLAB. Concurrently, basic programming
skills that will also be useful outside of this course, will be practiced. A basic knowledge of
MATLAB is required for follow-up courses such as OGO Instrumentele Fysica but will turn
out to be generally useful both during college years and afterwards.
Some parts of this manual, mainly problems, have been marked with an asterisk (∗) to identify
more challenging problems. Problems marked in this way are intended for advanced students;
they are not required for the final test.
This version of the manual was revised in 2014 to correspond to Matlab version R2014a.
iii
Schedule
The course is divided into six half-day sessions. The material to be treated per session is
shown in the table below. The exercises are located in the text, numbered with Roman num-
bers, and are meant to learn new commands. The problems, numbered with Arabic numbers,
are collected in the problem sections at the end of each chapter and serve to put the new
knowledge into practice on a more advanced level.
NB: The course is finalized by a two hour long test (“tussentoets”) that will be held during
the last two hours of the last session.
NB: Attendance is mandatory for this computer laboratory. You cannot complete the course
Experimentele Fysica 2 if you have been absent during one or more of the computer labora-
tory sessions. Absence for a valid reason must be reported via e-mail to onderwijsn@tue.nl
with a CC to phys.exp.fys@tue.nl
2 Matrices 19
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Arrays and graphical output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2.1 Graphs, continued . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3 Tables of numbers: matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.1 Simple matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.3.2 Functions of multiple variables . . . . . . . . . . . . . . . . . . . . . . 26
2.3.3 Manipulating matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.3.4 Algebraic operations for matrices . . . . . . . . . . . . . . . . . . . . . 28
2.3.5 Reading and writing data . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4 Lineair algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4.1 Systems of linear equations . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4.2 Matrix product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4.3 Solving systems of linear equations . . . . . . . . . . . . . . . . . . . . 34
2.5 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
v
vi CONTENTS
4 Differential equations 49
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.2 A first-order differential equation . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3 Systems of ordinary differential equations . . . . . . . . . . . . . . . . . . . . 51
4.3.1 ∗ Stiff differential equations . . . . . . . . . . . . . . . . . . . . . . . . 53
4.4 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
A ∗ Gaussian elimination 59
List of Tables 61
Index 62
Chapter 1
>>
After a command has been input (possibly after the output), another MATLAB prompt will
appear.
1
2 CHAPTER 1. MATLAB: THE BASICS
Figure 1.1: The start-up screen of MATLAB. A is the ‘Command Window’ used to input
and execute commands; B is the ‘Current Folder’, the contents of the current folder; C is the
‘Workspace’ that displays all currently defined variables and their corresponding value(s).
>> 1+2
What happens?
Next to the Command Window there is Current Folder window that shows the files and
folders located in the current folder. This is window B in Figure 1.1. The Workspace window
shows all variables currently in use (see also 1.5). A history of executed commands can be
displayed in an additional Command History window.
1.3 Help!
The Help documentation in MATLAB is very extensive. This option is invoked by clicking the
option ‘Help’ or ‘?’ in the menu bar on the top of the screen. It is often useful to directly go
to the correct page in the Help documentation by using the command prompt. For example,
the documentation for the built-in function sqrt can be found directly by typing into the
Command Window:
>> help sqrt
After typing this and pressing Enter, a short description of the command sqrt will be shown.
If a more elaborate description is needed one can use doc. For example, again for sqrt, enter
>> doc sqrt
1.4. DATA TYPES 3
to open a new window, showing more detailed information and some examples using sqrt.
In this Help window links to the descriptions of related functions are also displayed.
• real numbers (e.g., 6.63×10−34 ) with absolute value between 2.22507 × 10−308 and
1.79769 × 10308 ; numbers smaller than the first of these are stored as 0, numbers larger
than the second as Inf (for infinite),
• integer numbers (. . . ,-1,0,1,. . . ) with absolute value smaller than 253 ; larger integers
cannot be represented exactly by a double,
• complex numbers (e.g., 1.0+2.0i) are stored in two doubles, one for the real and one
for the imaginary part,
Textual data is stored using the type string, which is a sequence of characters. For example,
’Hello, world!’ is a string. There are many functions available to manipulate strings. Numbers
can be converted to strings using num2string, and vice versa using str2double.
Several other data types are available that are not covered here, including additional numeric
types that offer advantages for specific applications.
1.5 Variables
Exercise 1.ii — Type
>> a=1+2
We see that 1 + 2 is 3. The result of this calculation is now stored in the variable named a.
This variable is now also displayed in the Workspace (window C in Figure 1.1). Variables
can be used in further calculations.
Exercise 1.iii — What are the results of the following commands? First deduce them
yourself, then execute them in MATLAB. Were your initial thoughts correct?
>> a=a+1
>> b=a*3
If the result is not explicitly assigned to a variable (the command does not start with
variable=) then the result will be assigned to ans.
Exercise 1.iv — Describe what happens when the following commands are executed:
4 CHAPTER 1. MATLAB: THE BASICS
>> a*b
>> ans/3
>> b=a*b
>> a*b
The variable ans always contains the answer to the last command for which the result was
not assigned to another variable. ans can be used in further calculations, but be careful! It
is very easy to overwrite the variable ans by executing a subsequent command.
In long calculations some in-between results do not need to be displayed. This can be done
by using the semicolon symbol:
>> c=4;
>>
No result of the command c=4 is shown in the Command Window. The variable c, however,
is set and equal to 4. This can be seen in the Workspace, but can also be checked by entering
>> c
c =
4
>> a=0.5
>> b=a*4
>> c=1000000
>> d=1e6
>> c-d
>> f=1.34e-8
As you can see, e6 actually means ×106 ; e-8 stands for ×10−8 .
When a line of input is very long, it is often helpful to use multiple rows for one command.
This can be achieved by typing three full stops (...), and hitting the Enter key. The input
line will continue on the next row. Extra spaces can also be added freely.
Exercise 1.vi — Execute the following commands. Can you predict the results?
>> d=100*2+50*3+...
75*4+12
>> b = 2 + 3
>> c = 3 + 4
1.5. VARIABLES 5
Variables can be named using all letters, numbers, and the ‘underscore’ _. However, names
of variables need to start with a letter and can be at most 31 characters long. They are are
also case sensitive: a and A are treated as two separate variables. Some variable names have
a predefined value, such as pi, or represent a function, i.e. sin. It is allowed to use names
like these for your variables, but it is not advised for obvious reasons. For an overview of
predefined variables, see table 1.1.
To reset the value of a variable the command clear can be used.
>> x=10
>> clear x
>> x
Using clear multiple variables can be cleared. To clear variables a and b use
>> clear a b
>> clear
In order to use variables later, they can be saved on the hard disk. This can be done using
the save command. MATLAB will save the variables in a .mat file.
will save all variables in the workspace to a file named file.mat. To save specific variables
they can be added as an argument:
Now only the variables a, b, and c are saved. In order to load these variables again the load
command is used:
Symbol Meaning
ans Result of last calculation not assigned to a variable..
eps eps = 2−52 −16
√ ≈ 2.2 × 10 , the accuracy of floating-point numbers.
i and j i = j = −1, imaginary unit.
Inf Result of: 1/0.
NaN Result of: 0/0.
pi pi = 3.14159...
realmin Smallest positive number, close to 2.2 × 10−308 .
realmax Largest positive number, about 1.8 × 10308 .
6 CHAPTER 1. MATLAB: THE BASICS
Exercise 1.viii — Define three variables a, b and c, and assign a numerical value to them.
Save the variables to a file named abc.mat. Clear all variables in the workspace. Load
the saved file to see whether the variables are saved and loaded correctly.
• Addition: a+b,
• Subtraction: a-b,
• Multiplication: a*b,
• Division: a/b,
• Exponentiation: a^b.
MATLAB uses the standard order of operators: first exponentiation, then multiplication and
division, then addition and subtraction. Parentheses ( and ) can be used to force MATLAB
to first execute commands and/or operations in between. A short overview of predefined
mathematical functions is shown in table 1.2.
>> 1/2+3
>> 1/(2+3)
1.7. DEFINING FUNCTIONS AND CREATING SCRIPTS: M-FILES 7
x = cos(2π)
y=e
z = ln y
1
a = (−2 + 4) 6−4
b = a2
function y = func(x)
y = exp(x^(1/3)-sin(pi*x));
Save this file as func.m via ‘File’ → ‘Save’. In general, it is best to give the file the exact
same name as the function (func → func.m) to avoid confusion. For the same reason,
avoid using names for your own functions that are already predefined in Matlab. As
an example, it is a bad idea to define a function named cos since Matlab already has a
function by that name representing the cosine.
In Current Folder (B in figure 1.1) you should now see our new file. The command function
indicates that func.m can be used as a function: if an input value x is given, the function
will calculate an output y. It easily to see that f (0) = 1. Let’s check this:
>> func(0)
ans =
1
The function func has used the value x=0 to calculate y. This value of y is returned as the
result.
Exercise 1.xii — Try the function func for different input values. What happens when
you hand func a negative value as input?
8 CHAPTER 1. MATLAB: THE BASICS
Functions can also handle multiple input values. For example: the function that calculates
the binomial coefficient
n n!
=
k k!(n − k)!
Exercise 1.xiii — In the Editor, enter the following lines into a new m-file.
function y = binom(n, k)
y = factorial(n)/(factorial(k)*factorial(n-k));
Save this file as binom.m, and execute the following statements using the new function
>> binom(10, 4)
>> binom(6, 3)
squareroot2 = sqrt(2);
squareroot3 = sqrt(3);
goldenratio = (1+sqrt(5))/2;
esquare = exp(1)^2;
Exercise 1.xiv — Write this script, save it as constants.m and execute it. What happens
to the Workspace?
Note that the Editor signals that a script contains an error by tagging the line where the
error occurs using a red or orange mark in the right margin. Hovering above the colored
mark produces a hint about what is wrong. This is generally very helpful in debugging a
script.
1.8. PROGRAMMING IN MATLAB 9
if [condition]
[lines of code to be executed if the condition is met]
else
[lines of code to be executed if the condition is not met]
end
The condition is a so-called relational expression that can either be true of false. In most
cases the condition is tested using a relational operator.
Type this script in the Editor and save it as testiflower.m, then execute it. Using
the command input a number can be entered using the keyboard. This input value is
assigned to the variable a. Then we check whether a is indeed smaller than 10. This
is the same as checking whether the statement ‘a<10’ is true. Try the script with some
numbers i.e.: 3, 11, -12.5, -3*exp(1.5). Does the script work correctly?
Some relational operators, and their corresponding MATLAB syntax, are listed in table 1.3.
A few examples:
• 1 == 1 is true;
• 1 == 2 is false;
• 1 ~= 2 is true;
• 1 < 2 is true;
• 1 >= 2 is false.
10 CHAPTER 1. MATLAB: THE BASICS
Syntax Meaning
== equal to
~= not equal to
< smaller than
<= smaller than or equal to
> larger than
>= larger than or equal to
It is important to realize that there is a difference between = and ==! With = we can assign
a value to a variable, whereas == is used to compare two variables.
Relational operators can also be combined. There are two ways to do this. One is to use
nested if-blocks (an if inside an if). The other way is to use logical operators. An example
of the first option:
a = input(Insert a number larger than 1, but smaller than 10 ’);
if a > 1
if a < 10
disp(’True!’)
else
disp(’False!’)
end
else
disp(’False!’)
end
First, it is checked whether variable a is larger than 1. If not, the program will jump to the
last else and write False!. If a is larger than 1, a second if follows to check whether a is
smaller than 10. If this is the case, then the text True! will be displayed, as both conditions
are met. The extra spaces are a commonly applied way to visually distinguish the different if
blocks. The if, else, and end commands that belong to each other all have the same distance
to the start of the line. Lines in between have a larger indent. Especially in larger programs,
with a lot of nested if blocks, it can be hard to identify the structure of the program when
indentations like these are not inserted.
This program could also use a logical operator instead of two nested if conditions:
a = input(’Insert a number larger than 1, but smaller than 10: ’);
if a > 1 && a < 10
disp(’True!’)
else
disp(’False!’)
end
The conditions a>1 and a<10 are combined with the operator &&, the and -operator. The
combination a>1 and a<10 is only true if both a>1 and a<10 are true. Otherwise the combi-
1.8. PROGRAMMING IN MATLAB 11
nation is false. The other logical operator is ||, the or -operator.. Hold ‘Shift’ and press key
\ to get |. [condition 1] || [condition 2] is false if both condition 1 and 2 are false. If
one of the conditions (or both) is true, than the combination will also be true. There is also
a not-operator ~. This operator inverts the result of a condition : ~(1>2) is true.
b=1;
c=2;
a = input(’Insert a number: ’);
if a == b || a == c
disp(’a is equal to b or c’)
else
disp(’a is not equal to b and not equal to c’)
end
When the program arrives at the for loop, the variable counter is assigned the value start.
The following lines of code are executed until end is reached. Then we return to the for
statement, the value of counter is increased with step, and the following lines of code are
repeated with the new value for counter. This process is repeated until counter would
become larger than stop. It is also allowed to use a negative value for step: the for loop
will then be repeated until counter would become smaller than stop. In case the value for
step is omitted it takes the default value 1.
In this example a for loop is used to calculate the factorial a!:
function b = fact(a)
b=1;
for n=1:a
b=b*n;
end
Since no step size for the for loop is given it will take the default value 1. This function
does not check whether the input is a positive integer number, which is a requirement for
a mathematically well-defined factorial. However, when the input is a positive integer the
functions works perfectly! Try this script out and compare the results with that of the built-in
function factorial.
12 CHAPTER 1. MATLAB: THE BASICS
>> fact(8)
ans =
40320
>> factorial(8)
ans =
40320
>> fact(100)-factorial(100)
ans =
0
Exercise 1.xvii — Write a script that writes to the screen all the integer numbers between
(and including) 2 and 100 using a for loop. Validate that it functions properly. Can
you modify the script to make it show only even numbers? Can you modify the script
to make it count backwards from 10 to 1?
while [condition]
[lines of code]
end
When the program arrives at the command while and the condition is true, then the lines of
code within the while loop are executed. When the program then arrives at the command
end, the condition is checked again. If the condition is still true, the lines of code will be
executed again. This process is repeated until the condition is no longer true.
a=1;
b=1;
while a ~= 10
a=a+b
end
Save the script and run it. What happens, and why? What if you change the value of
b to 2? Hint: you can use Ctrl+C to abort the script.
It is very important to make sure that the condition for a while loop will actually become
false. If not, the program will get stuck inside the loop. In such cases the program can be
aborted using Ctrl+C. If a never reaches the value of 10, the loop will continue running until
there is an overflow. This will happen when a is larger than the largest number MATLAB
can cope with (realmax). Probably, the intention of this program is
a=1;
b=2;
1.8. PROGRAMMING IN MATLAB 13
while a <= 10
a=a+b
end
Another example:
secretnumber=round(rand(1)*10+0.5);
stop=0;
while stop == 0
a=input(’Guess the secret number (between 1 and 10): ’);
if a==secretnumber
stop=1;
disp(’Correct!’)
else
disp(’Try again.’)
end
end
In the first line of this example script a random number between 1 and 10 is generated.
rand(1) is a command that gives a real number x in the interval (0, 1). round rounds the
number to the closest integer. The program will continue running the code in the while loop
until the value of stop does not have the value of 0. This is the case when the secret number
has been correctly guessed.
Exercise 1.xix — Develop a script that asks for a number as input, and then displays all
odd numbers larger than 0, but smaller than the input. Use a while loop.
MATLAB is a so-called interpreted language. This means that code is executed by a part of
MATLAB that is called the interpreter. The interpreter converts the MATLAB code, one
line at a time, in such a way that the computer can execute it. This is different from compiler
languages, like Fortrain and C++, where the code as a whole is converted into an executable
file. The main advantages of using the interpreter language MATLAB are: errors are located
more easily, a larger number of functions is readily available and there are a lot of options
for graphical output. Besides this, MATLAB is optimized for the use of matrices, which are
common in many problems. The primary disadvantage of an interpreted language is that it
slower than a compiler language since every line of code has to be translated individually
during run-time. This also means that MATLAB programs cannot run without running
MATLAB, while programs that are written in compiler language can be run independently
after compilation, even if there is no compiler available.
MATLAB makes programming easier because it handles a lot of tasks automatically. Vari-
ables, for instance, do not need to be declared. In other programming languages variables
need to be assigned to a part of the available computer memory. Because there are different
representations for integer and floating-point numbers in computer memory, there is also a
difference in the accuracy of calculations carried out with those types. For example: when
an integer is divided by an integer, the result typically is stored as an integer as well, even if
the actual result is a floating-point number. Think 7/3 = 2 even though 2.333333 would be a
better representation of the result. MATLAB automatically converts variables if necessary.
1.9 Problems
Problem 1.1 — Entering numbers
1
Which of the following commands assigns the value 1000 to variable a? There can be multiple
correct answers.
a) >> a=1e-3
b) >> a=1/1000
c) >> a=1e-5/0.001
d) >> a=0.001
e) >> 0.001=a
>> 7+5;
>> a=8;
>> b=ans+a;
>> c=b/(2+a);
>> a=2^5
>> b=7/(a+3)
>> c=a^b
1.9. PROBLEMS 15
>> c=b*c
>> a=b
Problem 1.4 — Variables 3
Define the variables x and y and assign the following values to them:
2
x = (4 27 )4/9 and y = 11
.
5 + 3−1.4
Let their value be output to the screen. Now type
>> format long
and let their values be shown on the screen once again. Save the two variables in the file
xandy.mat. Now type
>> clear
and load the variables x and y from the file again.
Problem 1.5 — Maths 1
Evaluate the following expressions in MATLAB.
π2
a)
4 √
b) (3 + 3)3
c) e2 + ln 2
cos(π − e)
d) p
1 − 3/11
e) log10 (10sin(π/2) )
Problem 1.6 — Maths 2
Correct the following MATLAB commands to calculate the given expressions.
c) e2 − ln 3 >> e^2-ln(3)
X
N
n = 12 N (N + 1) .
n=0
b) Alter the script such that it asks the input of a value for N first.
Try doing this without constantly recalculating xn /n! for each n (i.e., use the result from a
previous step, rn−1 = xn−1 /(n − 1)!, to calculate rn = xn /n!). Start with format long!
b) Improve the script such that it will stop automatically once it is within a certain accuracy
of the ’real’ value exp(1).
c) Change the script to calculate exp(x) for any x.
Problem 1.21 — Series 2
a) Develop a script that generates the number π using the following series:
∞
X x2n+1
arctan(x) = (−1)n .
2n + 1
n=0
Matrices
2.1 Introduction
Chapter 1 covered basic Matlab skills, including controlling program flow. There we mostly
dealt with individual numbers stored in individual variables. However, the majority of appli-
cations involves lists of numbers in the form of one-dimensional or multi-dimensional arrays
of numbers or text. Examples are the processing of images recorded with a CCD camera,
voltages recorded as a function of time with an oscilloscope, or simulation results developed
for multiple values of the important model parameters. Therefore, numerical processing and
visualization often requires dealing with arrays and matrices. Fortunately, MATLAB (Matrix
Laboratory) is particularly suitable for such computing and visualization tasks, and includes
many built-in commands and functions that can be applied not only to individual numbers,
but equally well to arrays of numbers. This is the subject of the current Chapter.
>> x = [-5 -4 -3 -2 -1 0 1 2 3 4 5]
>> x(3)
>> x(11)
>> x(0)
>> x(25)
19
20 CHAPTER 2. MATRICES
The brackets [ and ] indicate an array of numbers. The individual elements are separated
by a space or a comma. This array has 11 elements. Individual elements can be evaluated by
entering x(#), with # the index. Indices smaller than 1, or larger than the total number of
elements, generate an error.
Sometimes the required number of elements is large, so that manually typing them is not
practical. We can also define the entire array x at once:
>> x = -5:5
x =
-5 -4 -3 -2 -1 0 1 2 3 4 5
The notation using : has already been explained in section 1.8.2. Here, the step size is 1, its
default value.
Exercise 2.ii — Now that the x values are known, we need to calculate sin(x) for each
element of x. The MATLAB function sin can do this. Type:
>> y=sin(x)
With a single command, the function values y for all elements of x are calculated! This
means that it is no longer necessary to write a for loop that calls the function sin for
each x. y is now also an array, as can be seen in the Workspace. Type the following:
>> plot(x,y)
The command plot(x,y) is used to graphically display the points (x,y). After executing
this command, a new window called Figure 1 appears, containing a graph as in figure 2.1.
We can see that the points are connected with a blue line. We can also see that the graph
is very inaccurate, it does not resemble the graph of the sine function. This is due to the
large step size in x. In order to get a smoother curve we need to use a smaller step size.
Additionally, we know that the extrema and zeroes of the sine function are found at the
‘special’ points x = nπ/2 (with n an integer) where the function is zero or ±1. For the most
accurate graphical representation it is wise to explicitly use these values.
Exercise 2.iii — To obtain a better resolution we now choose the step size for x such that
there are 100 steps between −π and π. To achieve this we multiply the array -1:0.02:1
with pi.
>> x=(-1:0.02:1)*pi;
Use the semicolon (there is no need to see all the elements of x on the screen)! The
array x of 11 elements is now replaced by a much longer array of 101 elements (check
the Workspace). Note that multiplication of an array does not require a loop. This type
of multiplication (multiplying each value of an array by the same number) is already
defined in MATLAB, just like the sine function. The same holds for dividing by a
constant, and adding or subtracting a constant.
Calculate the new function values y, and display the result in a new graph.
Figure 2.2 shows a curve that already looks a lot more like a real graph of the sine. The step
size could be made even smaller if necessary.
2.2. ARRAYS AND GRAPHICAL OUTPUT 21
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−5 −4 −3 −2 −1 0 1 2 3 4 5
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−4 −3 −2 −1 0 1 2 3 4
Figure 2.2: Graph of sin(x) with 101 x values in steps of 0.02π between −π and π.
>> plot(x,y,’go-.’)
22 CHAPTER 2. MATRICES
This will plot a green dash-dotted line with circles on the data points. The argument between
the ’’ consists of (up to) 3 parts: colour, symbol shape, line style. Each of the three parts
can also be left out. By default the colour is blue, the line is solid and no symbols are added.
In table 2.1 a overview of these properties is shown.
As you executed the second plot command you probably noticed that the first graph has
been replaced by the new graph. To prevent this and plot multiple graphs in one figure, we
can enter the following command after the first plot command:
>> hold on
By executing the command hold off we return to the default behaviour, old graphs are
replaced by new ones. Multiple graphs can also be plotted with one command:
>> plot(x1,y1,’b-’,x2,y2,’rs’)
The graph of y1 as a function of x1 is a solid blue line, y2 as a function of x2 is drawn using
red squares.
Besides the command plot there are also commands that plot on a logarithmic scale.
• semilogx(x,y) logarithmic x axis and a linear y axis;
2.2. ARRAYS AND GRAPHICAL OUTPUT 23
Plot these functions, both using a for-loop and not using a for loop by defining an array
of number for x instead, to fill arrays for f , g and h. For each function, determine which
of the plot commands results in a straight line. For x use a range of 1 to 100 with some
reasonable step size (or try something else).
Additional annotation for graphs can be inserted by using the following commands.
• Axis labels: xlabel(’x axis label’) and ylabel(’y axis label’);
• Title: title(’title’);
Graph of y=cos(φ)
1.5
0.5
0
y
−0.5
−1
−1.5
−6 −4 −2 0 2 4 6
φ
It sets the range of the x axis from x_min to x_max and the range of the y axis from y_min
tot y_max. Try it out.
>> x=-5:5
>> size(x)
ans =
1 11
This result shows that x consists of 1 row and 11 columns.
Exercise 2.vi — Variables can also consist of multiple rows and/or columns:
>> y = [1 2 3; 4 5 6; 7 8 9]
>> size(y)
With this definition we see that variable y consists of 3 rows and 3 columns. A row is filled
until the semicolon, after which a new row is started. Row 2 is also filled with 3 elements,
until the next semicolon is found. MATLAB now continues with row 3, which is also filled
with 3 elements.
Exercise 2.vii — What is the result of the following commands?
>> y(3,2)
>> y(1,1)
>> y(5,3)
>> y(2,1)
Can you figure out what the numbers between parentheses mean?
The first index between parentheses defines the row number, the second the column number.
This is the mathematical convention that is always used for matrices. Elements outside the
boundaries do not exist!
Within a matrix, all rows, and all columns, must contain an equal number of elements.
>> a=[1 2; 3]
Error using vertcat
CAT arguments dimensions are not consistent.
In the previous example, the first row would contain 2 elements whereas the second row would
only contain a single element. This results in an error.
There are several functions that can be used to quickly fill a matrix:
>> a=zeros(2,3)
>> b=ones(4,5)
Variable a is now a matrix consisting of 2 rows and 3 columns; all elements are 0. Variable
b is also a matrix, now consisting of 4 rows and 5 columns. All elements of b are 1. The
command diag can also be useful - try it out.
Exercise 2.viii — Execute the following commands:
>> d=1:10
>> c=diag(d)
(a) (b)
4
1.5
1
2
0.5
0 0
−0.5
−1 −2
−1.5
10
5 5 −4
0
0
−5
−6
−10 −5 −5 −4 −3 −2 −1 0 1 2 3 4 5
Figure 2.5: Two examples of plots of a function of two variables: (a) mesh, (b) contour.
The function meshgrid returns two matrices, x and y. Each row of x is equal to -5:0.2:5.
Each column of y is equal to -6:0.3:6. These are the x and y coordinates at which the
function is evaluated. The MATLAB functions sin and cos are, like almost all MATLAB
functions, capable of handling matrices as input variables. The command g=sin(x) with x a
matrix results in a matrix g with the same dimensions as x.
Plotting functions of two variables can for example be done using a three-dimensional mesh
plot (figure 2.5a)
>> mesh(x,y,f)
>> contour(x,y,f)
Exercise 2.x — Make a plot of the function f using filled contours. The command is
contourf. Then enter the command colorbar.
2.3. TABLES OF NUMBERS: MATRICES 27
Use the command surf(x,y,f). Use −10 and 10 as the boundaries for the x and y
coordinates and use appropriate step sizes. How can the axis ranges for the three axes
be changed? Add annotation for the three axes. (hint: use zlabel). To set the relative
scaling of the three axes use daspect([a b c]). Distances a on the x axis, b on the
y axis and c on the z axis will be plotted with equal on-screen length. Also add a
colorbar. Save the figure as a JPG file.
Exercise 2.xii — We will embellish the plot of the previous assigment. Use the following
commands in your script:
surfl(x,y,f)
shading interp
It is also possible to change the viewing angle. Select the button in the Figure
window. Now click on the figure with the left mouse button and hold, then move the
mouse. Two numbers are shown: Az and El. These are the two angles (azimuth and
elevation) that describe the viewing. They are given in degrees. What values can Az
and El attain? We can also set the viewing angle in our script: view(Az,El). Save the
figure using a nice viewing angle.
>> y = [1 2 3; 4 5 6; 7 8 9];
>> y(2,:)
>> y(:,3)
What is the result? Pay close attention to the orientation (row or column) of the result!
It might come in handy to diagonally mirror a matrix, which transforms a matrix with 3 rows
and 2 columns into a matrix with 2 rows and 3 columns. This new matrix is then called the
matrix transpose.
>> a=[1 2 3; 4 5 6]
>> b=transpose(a)
>> c=[1 2 3]
>> d=transpose(c)
Look at the number of rows and columns for each result. Can you describe what
transpose does?
28 CHAPTER 2. MATRICES
Some matrix-related commands are listed in table 2.2. We will encounter several of these
commands in the problems, where their function is illustrated. Of course the commands can
also be combined.
Matrices can be merged using similar commands. See the following assignment.
Exercise 2.xv — Write a script with the following commands.
a=[1 2 3; 4 5 6]
b=[7 8 9; 10 11 12]
c=[a b]
d=[a; b]
g=[1 2 3]
h=[4 5; 6 7]
k=[g; h]
Exercise 2.xvi — Exercises for manipulating matrices using :. See table 2.2. Use only one
command in each step!
Define a 4 × 4 matrix A filled with ones.
Fill the third column with twos.
Set the elements of row 4 equal to 3, 4, 5, 6.
Set the elements 2,3 and 4 of comlumn 1 equal to 7, 8, 9.
Fill the elements A(3,3), A(3,4), A(4,3), and A(4,4) (this is a 2 × 2 matrix in A) with
tens.
Check whether the sum of all elements is equal to 78.
>> a=[1 2 3; 4 5 6]
>> c=0.5
>> a+2
>> a-c
>> a*c
ans =
0.5000 1.0000 1.5000
2.0000 2.5000 3.0000
>> b/3
ans =
4.0000 3.6667 3.3333
3.0000 2.6667 2.3333
Exercise 2.xviii — Enter the following commands. Do you understand what happens
during each step?
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
−5 −4 −3 −2 −1 0 1 2 3 4 5
√
Figure 2.6: Graph of the function f (x) = 1/ 1 + x2 .
The operations are executed element-by-element. For example, c=a.*b means that
c(m,n)=a(m,n)*b(m,n) for all involved m and n. The other manipulations are carried out in
a similar fashion.
Example: a script that plots the function f (x):
1
f (x) = √ .
1 + x2
First we define the x values.
x=-5:0.1:5;
There are some points of attention for the determination of the function values. It is important
to use a full stop before the operations for division and exponentiation. The correct way to
write this function is:
y=1./sqrt(1+x.^2);
If we then use
plot(x,y)
e−x
2
f (x) =
cos x
2.3. TABLES OF NUMBERS: MATRICES 31
Table 2.3: Some useful matrix operations. x is a matrix. n is a variable used to define the
direction of operation, n=1 executes the operation on the columns, n=2 executes the operation
on the rows.
Command Meaning
sum(x,n) sum
prod(x,n) product
max(x,n) maximum
min(x,n) minimum
mean(x,n) mean value
std(x,0,n) standard deviation (for a description of 0 see doc std)
There are many commands that can be used to calculate a matrix sum, product, average,
standard deviation, etc. Several are listed in table 2.3.
Exercise 2.xx — Define an array of numbers a that contains the integer numbers from 1
to 10. Calculate the average and the sum using the commands in table 2.3.
Exercise 2.xxi — It takes some caution to apply the commands in table 2.3. To see why,
try the following commands.
The operations work as you would naively expect as long as the matrix consists of only one
row or column. If a matrix consists of more than one row and one column the operations are
applied to the columns first, e.g. we get a row matrix containing the sum of the columns.
If the operation should be applied to the rows first, a second argument stating the direction
should be added. This is done as sum(b,2). The part ,2 states that the operation should
be applied to the rows (,1 is used for columns, and is the default value). If the operation
should be applied to both the rows and the columns, the operation can be executed twice
sum(sum(b)). The first sum(b) gives the sum of the columns in a row matrix, the second sum
sums these values thus giving the total sum of all elements of matrix b.
containing all the data from the file. If the file contains a header containing explanations
of the data, then it might be easier to use the import-tool which can be found under ‘File’
→ ‘Import Data’. Using this option a column delimiter (often a comma, semicolon or space
character) can be chosen and a header can be skipped when importing data.
Exporting/storing data can be done in a similar fashion. If data has to be used by programs
other than MATLAB, it is often best to save it as a text file. The default output of MATLAB
is .mat, which is binary and not readable for other programs. Thus we add the option ascii:
This command creates a text file data.txt containing the data stored in variable a.
Exercise 2.xxii — Create a matrix F consisting of two columns. Fill this matrix with
the function values of f (x) = sin(x) and the corresponding values for x. The x values
should be placed in the first column, the values f (x) = sin(x) should be placed in the
second column. Save the matrix F in a text file sin.txt. Import the file in Origin and
plot the data.
For this simple example, the solution is easily found. Rewrite the first equation as l = 3 − 2k
and substitute it into the second equation. We immediately find that l = 13 3 , and thus k =
− 3 . However, as the number of equations in the system increases, it becomes increasingly
2
impractical to solve it manually. MATLAB can help here. First, we need to rewrite the
system of linear equations as a product of a matrix and a vector.
X
n
Cij = Aik Bkj .
k=1
The element in row i and column j of C is in effect the vector dot product of row i of matrix A
and column j of matrix B. Obviously, the matrix product is only defined for matrices for
2.4. LINEAIR ALGEBRA 33
which the number of columns of the first matrix A is equal to the number of rows of the
second matrix B. The resulting matrix C is an m × p matrix. We illustrate the matrix
product in figure 2.7, where we multiply the matrices
2 4
5 −3 8 2 −5 −2
A = 4 −6 0 3 and B = 3 −6 .
−1 3 6 −3
9 −4
Figure 2.7: A matrix product example. The purple element on the right-hand side is located
in the second row and the first column of the matrix. It is therefore obtained from the vector
dot product of the second row (red) of matrix one on the left-hand side and the first column
(blue) of matrix two on the left-hand side. Indeed, the dot product of the red and blue vectors
is 4 · 2 + (−6) · (−5) + 0 · 3 + 3 · 9 = 65.
• even if both AB and BA satisfy the condition above, generally AB 6= BA. Only in
rare, special circumstances AB = BA.
The matrix product of A and B can be calculated with A*B. We also see that MATLAB
generates an error when trying to calculate B*A; the dimensions of A and B do not satisfy the
criteria for a valid matrix product B*A.
Exercise 2.xxiii — We define two square matrices (equal number of rows and columns).
Now evaluate C = AB and D = BA. Compare the results. As is evident, even for
simple matrices AB 6= BA!
Exercise 2.xxiv — What do the following commands do? Why are the results the same
this time?
>> E=A.*B
>> F=B.*A
Matrices can also be raised to a power, but this operation is only defined for square matrices.
The notation Ak means that A is multiplied k − 1 times by itself.
A1 = A A2 = AA A3 = AAA
Exercise 2.xxvi — Determine the unique parabola passing through the points P (−2, 4),
Q(1, 1) and R(2, −4). The equation for the parabola has the general form y = kx2 +
lx + m. This problem is described by three linear equations. Which ones? Write the
equations in matrix form.
One way to solve these kind of problems by hand can be found in appendix A. MATLAB has
an operator for solving these kinds of problems.
Exercise 2.xxvii — We use the same matrix A and vector b as in the previous assignment.
We find the solution x of the equation Ax = b with
>> x=A\b
What are the values of the constants k, l, and m? Check the solution. What should be
the result of A*x?
If we look closely to which linear equations are defined, we find the problem. The system is:
k + 2l = 3
3k + 6l = 9
The second equation is actually just three times the first equation. Actually, the same con-
dition is stated twice. Because there are two unknown parameters k and l, and only one
independent condition, there is an infinite number of solutions. For each arbitrary value
of k, l = 23 − 12 k is a solution. This system is underdetermined..
Again we recognize the problem from the system of linear equations. The system is now:
k + 2l = 3
3k + 6l = 3
The second equation divided by 3 gives k + 2l = 1, which is in direct contradiction with the
first equation. The system cannot fulfill both requirements at the same time, the system is
overdetermined.
36 CHAPTER 2. MATRICES
Systems of linear equations have already been used in the method of least squares, introduced
in the course Exerpimentele Fysica 1. When fitting a polynomal
X
N
p(x) = an xn
n=0
of order N through a set of measurement data (xm , ym ), the sum S of the quadratic deviations
is introduced as
X
M
S= (ym − p(xm ))2 .
m=0
The deviation is minimised by setting the derivatives of S to the coefficients an equal to zero.
∂S
= 0, 0≤n≤N.
∂an
This gives a system of N linear equations, see the reader Experimentele Fysica 1, equation
(5.47). Systems like these can be solved easily using MATLAB.
2.5 Problems
Problem 2.1 — Arrays
Which MATLAB command should be used to assign the following arrays to x? In each case,
how many elements does the array contain?
a) From 0 to 9, step size 1.
b) From -6 to -10, step size -2.
c) From 0.5 to 9.0, step size 1.5.
d) From 0 to 3π, step size π/6.
e) From 10e to −2e step size −e/13.
Problem 2.2 — Bubble sort
Bubble sort is a simple sorting algorithm for an array of numbers. It works as follows. Starting
from the first element, each element is compared with the next element in the array. If the
next element is smaller than the current element, they are swapped. The loop from begin to
end of the array is repeated until no swaps are made anymore.
a) Make a design (e.g. on paper) for a function that carries out the bubble sort algorithm
on an input array of arbitrary size. What command(s) do you intend to use for the various
steps?
b) Write the function and test it! Start by filling an array of length N with random numbers
using rand(1) (look up rand in help) and some kind of loop.
Bubble sort is not efficient. For large arrays the continuous looping makes it run very slowly.
Typically, for arrays containing n elements, bubble sort requires a time that scales as n2 .
More efficient sorting algorithms require only a time that scales as n log n. For very large n
this makes quite a difference!
Problem 2.3 — Graph of a function 1 √
Write a script that plots the function f (x) = 1 − x2 for −2 ≤ x ≤ 2. Why does MATLAB
give a warning? Add a title and axis labels.
2.5. PROBLEMS 37
P
N
1
b) n!
n=0
PN
(−1)n
c) 4 2n+1
n=0
d) Export in a text file, for −1 ≤ x ≤ 1, and x step size 0.1, the x values in the first column,
and the function values in the second column. What function value is written for x = 0?
Problem 2.16 — Matrix product 1
What is wrong with the matrix product A*B of the following matrices? Does the product B*A
exist?
1 2 3 7 8
a) A = en B = .
4 5 6 9 10
b) A = 1 2 3 en B = 4 5 6 .
1 2 3 4
5 6 7 8 1 2 3
c) A = en B = .
9 10 11 12 4 5 6
13 14 15 16
Problem 2.17 — Matrix product 2
Define the following matrices:
−2 5 3 1 0 0
A = 6 −4 −2 en B = 0 1 0 .
3 8 −1 0 0 1
3x −3y +5z −6 = 0
−2x +5z −8 = 0
x −y +2z −2 = 0
Create a script that locates the point of intersection of the three planes.
∞
X (−1)n 2n+1 x3 x5 x7
sin x = x =x− + − + ···
(2n + 1)! 3! 5! 7!
n=0
How would you check this formula with a set of linear equations? Create a script that finds
the first three terms of the approximation. Also check the accuracy of your result by using
format long.
0.5 m 0.5 m
x1
x2
What is the relation between x1 and x2 ? Use a MATLAB script to find the answer! Also
look at the boundaries of x1 and x2 .
42 CHAPTER 2. MATRICES
Chapter 3
3.1 Introduction
There exist a large number of physics problems in which it is known that the state if a
system can be described by a certain function, and we are interested in finding out particular
characteristics of the behavior of the system. As an example, let’s consider the motion of
a projectile: a ball or bullit of mass m that is launched with some initial velocity v0 under
a certain angle α with the horizontal direction, whose motion is then influenced only by a
gravitational force of magnitude m g. The vertical position y and horizontal position x of the
ball are known functions of the time t after the ball was launched,
x(t) = v0 cos(α) t,
1
y(t) = v0 sin(α) t − g t2 .
2
In studying the motion of the projectile, we may wish to know
• at what time does the ball reach a particular height y1 ? Then we must solve the equation
y(t) = y1 , which is equivalent to finding a zero of the function y(t) − y1 .
• what is the maximum height that the ball can reach? Then we have to find the maximum
of the function y(t).
• what is the largest distance from the origin that the ball reaches
p before it hits the
ground? The answer is found by maximizing the distance r(t) = x2 (t) + y 2 (t) in an
appropriate time interval.
• how much work is done by Rthe gravitional force in a time interval t1 < t < t2 ? Then we
t
must evaluate the integral t12 mg vy (t) dt, where vy (t) = v0 sin(α) − g t is the vertical
velocity of the ball.
Using Mathematica, such problems can often be solved analytically. MATLAB does not
perform analytical calculations, however. We have seen this when plotting functions in the
43
44 CHAPTER 3. NUMERICAL EVALUATION OF FUNCTIONS
1.5
0.5
−0.5
−1
−1.5
−2
−5 −4 −3 −2 −1 0 1 2 3 4 5
previous chapters. In order to get a smooth graph it is necessary to make sure that MATLAB
calculates the function value at a sufficiently large number of points. It is unclear beforehand
which number of points is sufficient; this must be assessed separately for each problem by
trial and error.
There are many recipes for the numerical evaluation of a function f (x). There are iterative
schemes for the numerical determination of extrema and zeroes of functions, as well as for
numerical integration. These iterative schemes start at a predefined starting point and then
‘walk’ along f (x) in small steps of x until the desired point is reached with enough accuracy.
For instance, when searching for a zero, a change in sign of f (x) is a clear indication that a
zero has been passed. The next step in the iteration will then be in the opposite direction.
By decreasing the step size the point can be found with any desired precision.
Schemes like these are well suited for application in MATLAB. We do not have to implement
them ourselves because they are already predefined in Matlab. There is one requirement for
the application of these predefined functions: an m-file must be defined that returns a matrix
with function values f (x) on input of a matrix with x values. As an example we consider the
function
Exercise 3.i — Develop an m-file f.m that returns the function values for a given input
matrix x. Also, plot f (x) for −5 ≤ x ≤ 5.
The function is plotted in figure 3.1. The gap around x = 0 is due to the fact that ln 0 is
undefined. We will use this function in the following sections 3.2–3.4.
3.2. ZEROES 45
3.2 Zeroes
MATLAB is capable of finding the zero, or root, of a function in an interval of coordinates x.
However, the function must change sign between the two limits and it needs to be continuous
within the interval. From figure 3.1 it is found that f has a zero around x = 3.
Exercise 3.ii — Find the zero of f (x) in the interval x ∈ [2, 4] using the command fzero:
x0=fzero(@f,[2 4])
The @ symbol defines a so-called function handle. MATLAB now expects an m-file f.m to be
present that returns function values f(x) for any input values x. If the function is saved as
function.m in stead of f.m, then the function handle is @function.
The analytical value for the zero is x = π, because sin π = 0. Let’s see how accurate MATLAB
can approximate this value.
Exercise 3.iii — Calculate the function value f in the point x0. Is x0 a good approximation
of π? Remember that x0 is a numerical approximation of the zero, and will never be
exact.
fzero only finds one zero at a time, even if there are more zeros in the given interval. If f
becomes zero, but does not change sign (example: f (x) = x2 at x = 0), fzero will not find
the zero.
Exercise 3.iv — Find the zeroes around x = −1 and x = −3. What intervals did you use?
What happens if the interval contains more than one zero? Is x = 0 a zero according
to the MATLAB function fzero?
3.3 Extrema
Extrema can also be found numerically. MATLAB only has a function fminbnd to find
minima. In figure 3.1 we see that there is a local minimum in the interval [0, 1].
x1=fminbnd(@f,0,1)
The first argument in fminbnd is again the function handle. The second argument states the
lower bound of the interval which will be evaluated, in this case 0. The third argument states
the upper bound, in this case 1. The value x1 for the location of the minimum appears to
be a good approximation, judging by the graph. Again, we stress that fminbnd only returns
one minimum.
Exercise 3.vi — Find the minimum in the interval [0, 6]. Which minimum is found? How
can we find the second minimum?
In order to find maxima of functions we need to apply a trick:
Exercise 3.vii — Define a new function g.m, that calls the function f with a minus sign.
Find the minima of g(x). Do the minima of g(x) correspond to the maxima of f (x)?
46 CHAPTER 3. NUMERICAL EVALUATION OF FUNCTIONS
First, create a function g.m that returns the function values g(x) = x. This function is
very simple, but necessary for MATLAB to be able to numerically evaluate the integral.
Then, evaluate the integral using:
quad(@g,0,1)
Check the solution by calculating the integral by hand. Try changing the limits of the
integral.
Exercise 3.ix — For the function h(x) = sin(x), use MATLAB to calculate the following
integrals. Check the answers by hand.
Zπ Z1 Zπ/4
h(x) dx , h(x) dx , h(x) dx .
0 −1 0
We could have easily calculated these simple integral by hand. However, as function such
as f (x) = sin(x) ln |x| does not have an antiderivative, so we cannot analytically calculate the
integrals
Zx1
f (x) dx
x0
by simply evaluating the antiderivative in the limits of the integral. We must use numerical
methods to solve this integral.
Exercise 3.x — Calculate the integral stated above using MATLAB.
It is clear that the singularity in x = 0 is no problem for quad. One can guess by looking at
the graph, and it can also be proven analytically, that
lim f (x) = 0 .
x→0
Using this additional information the integral can be evaluated numerically. The command
quadgk can be used for the numerical integration of convergent integrals with ±∞ as one of
the limits.
Exercise 3.xi — Integrate the function h(x) = 1/x2 from 1 to ∞. First try quad, then try
quadgk. What is the analytical solution?
3.5. PROBLEMS 47
3.5 Problems
Problem 3.1 — Zeroes 1
f (x) = ln x + x .
a) For which values of x is f (x) defined?
b) Plot f (x).
c) Determine the zero of the function. Check by looking at the graph.
Problem 3.5 — Consider the motion of a projectile as described in Sec. 3.1. Assume that
v0 = 100 m/s, α = 30o and g = 9.81 m/s2 . Calculate:
Plot the trajectory of the ball to see if the answers are correct!
Problem 3.9 — Consider a small block of mass m = 1 kg that can move on a frictionless
track. The block is connected to a spring with spring constant k = 2.5 kg/s2 . In addition,
a damper is placed with damping coefficient c. The force on the block due to the damper is
Fd = −cv with v the velocity of the block and c = 0.2 kg/s.
The velocity of the block is given by
c h c i
v(t) = −x0 exp − t cos(ωt) + ω sin(ωt) (3.1)
2m 2m
p
where x0 = 0.1 m and ω = k/m. The period T of the motion is T = 2π/ω.
The work W delivered by the damper in the temporal interval [t1 , t2 ] is given by the integral
Zt2 Zt2
W = Fd v dt = −c v 2 dt . (3.2)
t1 t1
Make a script that calculates the work delivered by the damper during the first period of the
oscillation, from t = 0 to t = T . Save any required additional functions!
−∞
Differential equations
4.1 Introduction
Many physical phenomena are described by differential equations (DEs): relations specifying
the behavior of the derivatives of a physical quantity, for example with respect to time or
position. Perhaps the most familiar example so far is Newton’s second law from classical
mechanics, for instance as applied to the motion of a projectile or a pendulum. The result in
each case is a first order DE for the velocity of the object or a second order DE for the position
of the object. Similarly, in quantum mechanics the wavefunction of a particle follows from
a second order DE known as Schrödinger’s equation, while the properties of electromagnetic
fields follow from a set of coupled, first order DEs known as Maxwell’s equations.
Since DEs describe such a multitude of phenomena, numerical solutions to DEs play an
important role in simulations and computations. Therefore is it no surprise that MATLAB
contains a number of functions and commands that allow us to solve a variety of DEs, and
some of these are introduced in this Chapter.
v(t) = v0 + gt .
49
50 CHAPTER 4. DIFFERENTIAL EQUATIONS
Exercise 4.i — Now let us compute a numerical solution for the ODE
dv
=g (4.1)
dt
with MATLAB and compare the result to the analytical solution. First create an m-file
dv.m containing the code:
For a given time t and velocity v this function returns the derivative dvdt, in this case
simply the value g. Note that there are two function arguments: both time and velocity,
even though for this particular ODE the derivative in the right hand side of Eq. 4.1 is
independent of t and v. MATLAB always uses this standard function format to define
an ODE because, in a more general case, the derivative that is being calculated could
depend on these arguments. Note that the arguments correspond to the quantities in
the denominator (t) and numerator (v) of the derivative in the ODE (left hand side of
Eq. 4.1).
Solve the ODE for 0 ≤ t ≤ 2 s and v0 = 10 m s−1 with the command
[t,v]=ode45(’dv’,[0 2],10);
The command ode45 works on the m-file dv.m (that is why it has to have the structure as
shown above; note that dv.m is passed as an argument to ode45 as ’dv’), and solves the
ODE for time t in the interval [0 2] with initial condition v=10. The function returns
two vectors t and v, that contain the values of the velocity v for the corresponding time
values t. Plot the numerical result together with the analytic solution.
As a second example, we investigate the velocity of a steel sphere that is dropped into a
viscous liquid. The friction force Fw scales linearly with the velocity v of the sphere, but
is directed opposite to the direction of motion. Assume that Fw = −cv with c a positive
constant. Applying Newton’s second law, we find:
dv dv c
mg + Fw = m ↔ = − v+g,
dt dt m
with g = −9.81 m s−2 as the gravitational acceleration. The positive direction is upwards
again. Now assume the sphere is released from rest: v(t = 0) = 0, and that c/m = 10 s−1 .
Again, the analytic solution is known:
v(t) = A exp − mc
t + mgc .
Now let us solve the ODE numerically using MATLAB. To do this we first define a function
dv2.m that contains the ODE:
4.3. SYSTEMS OF ORDINARY DIFFERENTIAL EQUATIONS 51
Because there are now two variables y and v involved in the problem, both dependent on t,
two initial conditions are required! We choose v(t = 0) = 10 m s−1 and y(t = 0) = 0 m.
Exercise 4.iv — Now solve the system of ODEs defined above using:
The initial condition is now a column vector consisting of two elements [0; 10]. Plot
the graph of y(t). Also solve the ODEs by hand, and plot this solution in the same
graph. When does the ball hit the ground? Plot the exact and numerical solutions
for v(t) in a second graph.
Exercise 4.v — Now the ball is shot from a height y(t = 0) = 20 m with an initial velocity
of v(t = 0) = 5 m s−1 . What changes? At what time does the ball hit the floor this
time (look at the graph)?
θ0 (t = 0) = 0 ⇒ B = 0,
φ0 = f (t, φ) , (4.3)
where φ can be a vector. Because there is a second-order derivative in the ODE, φ0 must
contain the derivative θ0 . As such we can effectively introduce a second-order derivative on
the left-hand side. Looking at the original ODE, we can deduce that the function on the
right-hand side must contain both θ and θ0 . We define a vector φ that contains both the
angle θ and the angular velocity θ0 of the pendulum:
0
θ 0 θ
φ= ; φ = .
θ0 θ00
4.3. SYSTEMS OF ORDINARY DIFFERENTIAL EQUATIONS 53
1
θ′ (rad s−1)
0
θ (rad)
−1
−2
−3
0 1 2 3 4 5 6 7 8 9 10
t (s)
Figure 4.1: Graphs of the solution of the ODE for the pendulum displaying both θ and θ0 .
We then arrive at
0 0
θ θ
= ,
θ0 − g` θ
where we have used the fact that the angular velocity is the time derivative of the angular
displacement (first line); the second line represents the original ODE.
Exercise 4.vi — Develop a new function dv3.m that returns the derivative φ0 for this
vector φ. φ0 is also a vector. What quantities do the elements of φ represent?
Solve the ODE in the time interval [0, 10] with initial condition θ(0) = 0.5 rad, θ0 (0) = 0.
Plot the graphs for θ(t) and θ0 (t). Compare your results with Fig. 4.1.
Exercise 4.vii — Change the value of g/` and compare the numerical result with the exact
solution.
Rewriting higher-order ODEs to a system of the form (4.3) is always possible. The required
number of equations follows directly from the highest order of derivation in the ODE. For the
pendulum, due to the second-order derivative, two equations and two initial conditions are
required.
2.5
µ = 0.2
2
(a)
1.5
0.5
0
x
−0.5
−1
−1.5
−2
−2.5
0 5 10 15 20 25 30 35 40 45 50
t
2.5
µ=5
2
(b)
1.5
0.5
0
x
−0.5
−1
−1.5
−2
−2.5
0 10 20 30 40 50 60 70 80 90 100
t
2.5
2
(c)
1.5 µ = 500
0.5
0
x
−0.5
−1
−1.5
−2
−2.5
0 100 200 300 400 500 600 700 800 900 1000
t
Figure 4.2: Solutions of the Van der Pol equation for different values of µ: (a) µ = 0.2; (b)
µ = 5; (c) µ = 500. Compare the shapes of the graphs and the scalings of the horizontal axis.
4.4. PROBLEMS 55
differential equations. One example is the Van der Pol equation. The equation was derived
by Balthasar van der Pol in 1920 as a model for a certain electric system with a vacuum tube:
a triode-oscillator. The equation is:
The exact meaning of this equation is beyond the scope of this course. We are only interested
in the solutions of this equation.
Exercise 4.viii — Create a function vdpol.m for this ODE. Set µ = 0.2 and use the time
interval [0, 1000]. The initial conditions are x(0) = 2, and x0 (0) = 0. Solve the ODE
using methods discussed in previous sections. Compare your results with figure 4.2(a).
Change µ to 500, and solve again. What do you notice?
It is clear that µ = 0 is no problem for MATLAB. Even for small values µ < 0.5, the solution
still resembles a sine (figure 4.2a). If we increase µ (i.e. µ = 5; figure 4.2b) a few things
happen. The oscillation period increases. The graphs contain increasingly steeper slopes.
But, perhaps most noticeably, we find that the calculation time increase. For µ = 500 it is
no longer practical to use ode45 (figure 4.2c): the equation has become stiff. Conventional
methods to solve ODEs numerically such as those used in ode23 and ode45 are no longer
stable unless an extremely small time step is used. This means that many more steps are
needed in the calculation, taking considerably more time. To solve a stiff differential equation
it is often faster to use ode15s. This is a special function that uses a different numerical
algorithm than ode45 and finds a solution much faster. To find out whether an ODE is stiff,
it is often best to compare calculation times for ode45 and ode15s (and perhaps ode23 in
case ode45 is too slow).
4.4 Problems
Problem 4.1 — A differential equation
Consider the following ordinary differential equation (ODE):
x0 = ax .
With t1/2 the half-life of the sample. The half-life is the time it takes for half of the radioactive
particles to decay. Check this formula by solving the ODE. Choose different values for t1/2 ,
and look at the decay of N (t) in a graph.
56 CHAPTER 4. DIFFERENTIAL EQUATIONS
p0 = αp − βpr
r0 = −γr + δpr
where r(t) is the predator population, and p(t) the population of prey; α, β, γ and δ are all
positive constants.
a) What processes do the individual terms in the equations represent?
b) Set α = 1, β = 1.5, γ = 0.5, δ = 0.5, and solve the equation for the initial condi-
tions: p(0) = 1, r(0) = 0.5.
c) Plot r(t) as a function of p(t). Explain the behavior of r(t) and p(t). Save the figure.
d) Vary the parameters and investigate under which circumstances stable and finite popula-
tions of predator and prey develop.
Problem 4.5 — The Lorenz oscillator
In 1963 Edward Lorenz presented a simple model for convection in the atmosphere (see
Wikipedia for more information). This showed that small changes in initial conditions could
have a huge effect on the outcome at later times, which is now known as the butterfly effect
which signifies chaotic behavior. The model consists of a set of three coupled ODEs.
dx
= σ(y − x)
dt
dy
= x(ρ − z) − y
dt
dz = xy − βz
dt
β, ρ and σ are all constants. For this problem set β = 8/3, ρ = 28 and σ = 10.
a) Solve the system for 0 ≤ t ≤ 200 with initial conditions x = 0, y = 1, z = 0.
b) Plot the result with plot3(x,y,z). To get a nice view use view(-10,10). Save the figure.
c) Change the value of ρ to 14 and try again. Under these conditions the behavior is no longer
chaotic.
4.4. PROBLEMS 57
c x(t)
k m
1111111111111111111111111111
0000000000000000000000000000
0000000000000000000000000000
1111111111111111111111111111
0000000000000000000000000000
1111111111111111111111111111
A cube of mass m is lying on a smooth horizontal table. There is no friction between the cube
and the table. The cube is connected to a spring. The force of this spring increases linearly
with the displacement x of the cube from the equilibrium position and is directed opposite to
the displacement: Fv = −kx, where k is the spring constant. There is also a damping device
attached to the cube. This device exerts a force that scales linearly with the velocity v but is
directed in opposite direction: Fd = −cv.
The motion of the cube is described by the following ODE:
c 0 k
x00 = − x − x.
m m
a) Rewrite the ODE in a suitable form for numerical solution in MATLAB.
b) Is x0 (t = 0) = 0, x(t = 0) = 0 a suitable initial condition for this system?
c) What do you expect to happen when the damping coefficient c is increased?
d) For m = 1 and k = 4, solve the ODE with: c = 0, c = 2, c = 4 and c = 6. Choose suitable
time intervals and initial conditions. Plot the four solutions, and save the figures.
58 CHAPTER 4. DIFFERENTIAL EQUATIONS
∗ Gaussian elimination
We want to find the line connecting the points P (2, 3) and Q(5, 1). The general equation
for a line is y = kx + l. We need to determine the constants k and l. In point P it follows
that x = 2 and y = 3, thus 2k + l = 3. For point Q, 5k + l = 1. The set of equations is:
2k + l = 3
5k + l = 1
1. Multiply the first equation with a constant, such that the constant in front of k becomes
1. In our example this means that we multiply by 12 ; the equation reduces to k + 21 l = 32
and the system is
k + 12 l = 32
5k + l = 1
2. Because both equations must be true, we can add or subtract them from each other
without any problems. Because k + 12 l = 32 and 5k +l = 1 it follows that k + 21 l +5k +l =
3
2 + 1. This means that we can eliminate k from the second equation! We just subtract
the first equation 5 times from the second equation, leaving us with − 32 l = − 13 2 for the
second equation.
3. The second equation can be simplified just like we did in step 1: multiply both sides
with − 23 to find l = 13
3 .
4. Now that l is a known constant, k follows directly from the first equation: k = − 23 .
Now we solve the problem of three points that define a unique parabola passing through them.
The three points are P (−2, 4), Q(1, 1) and R(2, −4). We are looking for a parabola of the
form y = kx2 + lx + m. To find the parabola that passes through these three points, we use
the same steps as stated above, but now we use the matrix notation. We rewrite the problem
as one single matrix C = (A | b):
4 −2 1 4
C= 1 1 1 1 .
4 2 1 −4
59
60 APPENDIX A. ∗ GAUSSIAN ELIMINATION
The vertical line has no special meaning, it is just used to visually separate A and b.
Step 1: We make the first nonzero element of the first row equal to 1. We could do this by
multiplying the entire row (this is in fact multiplying the entire first equation) by 14 . However,
we already have a row which has a 1 as the first element. The order of execution is of no
importance (all points are given in random order), so we can exchange rows if we want. We
exchange row 1 with row 2.
1 1 1 1
C = 4 −2 1 4 .
4 2 1 −4
Step 2: We want to reduce all the rows apart from row 1 to have a 0 as the first element. To
do this we must subtract row 1 four times from both row 2 and row 3.
1 1 1 1
C = 0 −6 −3 0 .
0 −2 −3 −8
Now we repeat step 1, but for the second row. The first element that is not zero must become
1, so we multiply by − 16 :
1 1 1 1
C= 0 1 1
2 0 .
0 −2 −3 −8
We repeat step 2 for the third row, making the second element a 0. We add the second row
two times to the third row.
1 1 1 1
C= 0 1 1
2 0 .
0 0 −2 −8
Now we make the first element in row 3 that is not zero a 1. So we multiply by − 12 . We are
left with:
1 1 1 1
C = 0 1 12 0 .
0 0 1 4
With this form we can find the solution by substitution. The last row tells us that 0 · k + 0 ·
l + m = 4 or m = 4. The second row tells us that 0 · k + 1 · l + 12 · m = 0, or (using m = 4)
l = −2. Finally, we can find k using the first equation: 1 · k + 1 · l + 1 · m = 1, or k = −1.
The parabola is y = −x2 − 2x + 4. This procedure is also known as Gaussian elimination or
row reduction.
List of Tables
61
Index
( ) , 6, 20 comment, 13
* , 6, 29, 33 contour, 26, 38
+ , 6, 29 contourf, 26
- , 6, 29 cos, 6
. ,4 Current Folder, 2
.* , 29
... , 4 daspect, 27
./ , 29 diag, 25
.^ , 29 differential equation, 49
/ , 6, 29 system, 51
: , 11, 20, 27 disp, 9
; , 4, 25 doc, 3
< , 10
e, 4
<= , 10
Editor, 7
= , 10
else, see if
== , 10
end, see if, see for, see while
> , 10
eps, 5
>= , 10
errorbar, 37
[ ] , 19
exp, 6
&&, 10
extremum, 45
\ , 35
^ , 6, 34 factorial, 8
@ , 45 Figure, 20
~ , 11 figure, 20
~= , 10 annotation, 23
axis label, 23
abs, 6 title, 23
acos, 6 fminbnd, 45
algebraic operations, 6 for .. end, 11
for matrices, 28 format, 15
ans, 4, 5 function, 7
asin, 6 handle, 45
atan, 6 fzero, 45
axis, 24
Gaussian elimination, 59
clear, 5 graph, see figure
colorbar, 26, 38 Greek character, 23
Command History, 2
Command Window, 2 help, 2
62
INDEX 63
hist, 37 plot3, 56
histogram, 37 polar, 37
hold, 22 predefined variables, 5
prod, 31
i, 5
if .. else .. end, 9 quad, 46
Inf, 5 quadgk, 46
input, 9
rand, 13
j, 5 realmax, 5
realmin, 5
load, 5, 31
relational operator, 9, 10
log, 6
rotation matrix, 39
log10, 6
round, 13
logical operator, 10
loglog, 23 save, 5, 32
m-file, 7 script, 8
mathematical functions, 6 semilogx, 22
matrix, 24 semilogy, 23
column, 27 shading, 27
element, 20 sin, 6
manipulation, 28 size, 24
merger, 28 sqrt, 6
power, 34 start-up screen, 2
product, 32 std, 31
reduction, 59 stiffness
rotation, 39 differential equation, 53
row, 27 sum, 31
max, 31 surf, 27
mean, 31 surfl, 27
mesh, 26 system of linear equations, 32
meshgrid, 26 overdetermined, 35
min, 31 underdetermined, 35
mod, 16
tan, 6
NaN, 5 text, 23
nchoosek, 8 title, 23
numerical integration, 46 transpose, 27
ode45, 50 variable, 3
ones, 25 array, 19
in a function, 8
pi, 5 in a script, 8
plot predefined, 5
colour, 22 view, 27, 56
line, 22
symbol, 22 while .. end, 12
plot, 20, 21 Workspace, 2
64 INDEX
xlabel, 23
ylabel, 23
zero, 45
zeros, 25
zlabel, 27