Matlab Manual
Matlab Manual
Matlab Manual
1
2
Contents
1 Matlab session ................................................................................................................... 5
1.1 Getting started with Matlab ....................................................................................... 5
1.2 Matlab and matrices, a general remark ..................................................................... 6
1.3 The Matlab Editor ...................................................................................................... 6
1.4 The Workspace Browser ............................................................................................. 7
1.5 The property editor..................................................................................................... 7
2 Lay-out .............................................................................................................................. 8
10 Logical programming..................................................................................................... 18
10.1 Relational and logical operators.............................................................................. 18
10.2 Conditional statements ............................................................................................. 18
12 Output ............................................................................................................................. 22
12.1 The disp command .................................................................................................... 22
12.2 The diary command .................................................................................................. 22
12.3 Generating a table using the disp command ............................................................ 22
12.4 The fprintf command ................................................................................................ 23
12.5 The save command ................................................................................................... 23
13 Input ................................................................................................................................ 24
13.1 Command line driven ............................................................................................... 24
13.2 The import wizard .................................................................................................... 24
3
15.1 Script files ................................................................................................................. 28
15.2 Function files ............................................................................................................ 28
15.3 Collecting multiple Matlab files ............................................................................... 29
15.4 Parameters and Functions ....................................................................................... 29
4
1 Matlab session
The way to start Matlab differs from computer to computer. You may type the command
‘matlab’ in a command window of the operating system. Often, though, you will have to click
on a specific icon in order to run the program.
Once you have started Matlab a Matlab command window will appear, showing the command
prompt:
The line after the prompt is called the command line. On this line you can give Matlab
commands. After you have pressed <return>, Matlab will execute the command.
Besides the command window Matlab has graphical windows. Output of plot commands is
directed to the graphical window.
The quit command enables you to leave Matlab. To terminate a running Matlab command
you may use [Ctrl]+[c] (Press both the Ctrl button and the c button simultaneously).
By using the ! symbol you can use the original operating system
Only for short computations it is useful to execute Matlab straightaway from the command
line. In general the next procedure is much more practical:
1. Make a script file (see section 15) by means of your favorite text editor or the Matlab
Editor/Debugger (see Section 1.3). A script file consists of a sequence of Matlab
commands. In general script files will contain the main program and subprograms.
2. If necessary make the additional function files, using the same editor. Through these files
we are able to define the functions which play a role in script files.
3. Matlab executes the commands in the script file after you have typed the name of the
script file on the command line. Note, however, that the script file should be in the current
(working) directory, indicated in the box above the command window.
From the command line background information can be obtained using
1. help
5
» help plot % gives information on the Matlab command plot.
2. demo
» demo % presents multiple examples of the usage of Matlab.
x(i) = i , i = 1, …, 10,
y(i) = i2 , i = 1, …, 10,
z(i, j) = sin(x(i) * y(j)) , i, j = 1, …, 10.
» for i = 1:10
x(i) = i; y(i) = i^2;
end
» for i = 1:10
for j = 1:10
z(i, j) = sin (x(i) * y(j));
end
end
In Matlab this can be done quite differently, because matrices are basic objects:
Both programming styles are possible in Matlab. However, the latter is far more efficient.
Therefore, we prefer the latter and all examples will be given in this style.
It is advantageous to use the Matlab Editor when creating or editing script files. You invoke
this editor by typing edit at the command prompt or via the “New’ or ‘Open’ button in the
upper toolstrip. The Matlab editor has various features to aid in editing script files so that
most typing errors can be recognized. For example, text strings, reserved words (if, else, for,
end, …) and expressions are all shown in different colours. Saving and running the script is
easily done using the Debug menu.
In the Matlab Editor the so-called M-lint code checker is integrated. M-lint basically checks
the syntax of the code. In the right vertical bar M-lint displays colored rectangles with syntax
messages. The contents of the message will pop up if the colored rectangle is touched with the
mouse cursor.
6
1.4 The Workspace Browser
The Workspace browser is invoked via the upper toolstrip, button ‘Layout’, and gives a list of
current variables (scalars, vectors, matrices), similar to what whos (Section 3) does. By
double clicking on a variable in the Workspace window the values of this variable are shown,
in a separate window (the array editor), enabling inspection and interactive adaptations.
Matlab directs graphical output to the graphical window. In this window the so-called
property editor is available. Access is possible via the Edit or View button. Each graphical
window contains several graphical objects such as axes and lines. One can select the different
objects by clicking on them. Next, using the property editor one may inspect, make changes or
add objects. This is in particular convenient in the final stage when it is needed to prepare the
plot for inclusion in a report. It is then easy to add a title, label, etc.
7
2 Lay-out
When you use Matlab’s default configuration, the program distinguishes upper case and lower
case characters. One says that Matlab is case sensitive.
If the default configuration is used, Matlab will also print the result after every command.
Typing ; (a semicolon) after the command will suppress this.
x=
2
The symbol … (continuation) denotes that the command continues on the next line
» x = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 . . .
+ 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20;
% this command does not fit on one line
8
3 Common commands
9
4 Numbers and strings
Numbers can be entered in Matlab in the usual way; however, spaces inside a number should
be avoided.
ans =
1.2990 e−02
Matlab automatically assigns a type for every number you enter. Depending on the type,
Matlab chooses an internal representation for these numbers and the corresponding
computations. The external representation of a number (e.g. on the screen) can be altered with
the format command.
The default configuration is ‘format short’. It might be possible that the local system manager
has changed this into short e.
Remark: The format command influences only the external representation of real numbers.
This command has no influence on the internal representation used by Matlab to process the
program and its computations.
Remark: The format command is not able to alter the external representation of integer
numbers.This can result for example in jumps in tables.
The command vpa from the Symbolic Toolbox is helpful for displaying numbers and
variables:
» x = pi/10000; d = 8; disp(vpa(x,d))
.31415927e−3
In the above the variable d in the call of vpa refers to the number of digits to be displayed.
10
5 Variables and simple operations
A variable’s name has to start with a letter, but may not contain more than 31 letters, digits,
or underscores. Matlab is case sensitive in its default settings. This means that j and J do not
have the same meaning. Matlab automatically reserves space in the computer’s memory to
store the variable. Variables do not need to be declared before use; Matlab derives the type of
the variables by looking at the stored data. So it is possible that the type of a variable changes
while a session is in progress.
The basic element of Matlab is the matrix. Depending on the size of the matrix we
distinguish scalars (1 x 1 - matrix), vectors (1 x m -, or m x 1 – matrix), etc. Depending on the
context Matlab also assigns the type of the variables in the matrix, e.g. real or complex.
The operators +, −, *, /, ^ can be used for all Matlab variables (x ^ y = x to the power of y).
In the scalar case these operations will reduce to the usual computations. At every operation
step Matlab checks if the dimensions of the matrices involved are correct.
Multiplying a vector v with itself is not possible. If we try this anyhow we get:
» w = v * v;
11
6 Complex variables
»c=1+i
c=
1.0000 + 1.0000 i
Imaginary and real parts of a variable can be obtained with the functions real and imag:
» a = real (c)
a=
1.0000
» b = imag (c)
b=
1.0000
The operators +, −, *, /, ^ also work for complex numbers. With the symbol ’ we conjugate
a complex variable:
» cgec = c’
cgec =
1.0000 − 1.0000 i
» modc2 = abs(c) ^2
modc2 =
2.0000
» modc2 = c’ * c
modc2 =
2.0000
12
7 Matrices and vectors
Matlab stores its variables in matrices of size n x m. If m = 1, we are dealing with a column
vector, and if n = 1, with a row vector. When n = m = 1 the matrix represents a scalar. The
size of a matrix does not have to be given; Matlab determines the size from the data given by
the user. Matlab does not recognize a more general array structure, for example v (-10:100);
the lower bound in Matlab is always equal to 1.
We can define matrices in different ways, e.g. by giving values to every element separately.
We separate row entries by a space or comma and column entries by a semicolon or a
<return>.
A=
1 2 3
4 5 6
7 8 9
» A = [1 2 . . .
3 4;
5 6 7 8] % generating matrix A; . . . means continuation
A=
1 2 3 4
5 6 7 8
Vectors can also be made using the colon symbol : . Here the first value stands for the initial
value, the second for the step size.
x =
0 0.2000 0.4000 0.6000 0.8000 1.0000
A very convenient alternative to generate the present row vector x is to use the Matlab
function linspace:
x =
0 0.2000 0.4000 0.6000 0.8000 1.0000
The default vector in Matlab is a row vector as can be seen here. If a column vector is
needed, extra measures are needed (see later on).
13
zeros(n,m) : gives an n x m matrix with zeros
ones(n,m) : gives an n x m matrix with ones
eye(n) : gives the n x n identity matrix
A=
3 1 1
1 3 1
1 1 3
A=
−1 2 −1
−1 2 −1
−1 2 −1
» E = eye(3); C = zeros(3,2); D = [E C]
D=
10000
01000
00100
diag(v,k) : returns a square matrix with on the k-th upper diagonal the entries
of the vector v.
vs =
1 3 5 7 9
14
A=
1 2 0 0 0 0
1 1 6 0 0 0
0 3 1 10 0 0
0 0 5 1 14 0
0 0 0 7 1 18
0 0 0 0 9 1
A(i , j) = Aij
A(: , j) = jth column of A
A(i , :) = ith row of A
A(i , j1:j2) = vector existing of the entries, from column j1 to j2, of row i
A(i1:i2 , j1:j2) = matrix existing of the entries, from column j1 to j2, of the
rows i1 to i2.
» x = A(2,3)
x=
6
In case one of the dimensions equals one, we are dealing with a vector. We can refer to this
vector with just one index. This index is either a row index or a column index, depending on
the type of the vector.
Remark: Matrix elements can also be addressed using one index only. This might sometimes
be handy. One-dimensional references are taken column wise by Matlab:
» A = [1 2 3; 4 5 6; 7 8 9];
» x = A(6)
x=
8
However, in many cases such a reference is the result of a programming error, and then one
must be aware of the fact that no error message will be given.
15
8 Matrix and array operations
Arithmetic operations on matrices and vectors come in two distinct forms. Matrix sense
operations are based on the normal rules of linear algebra and are obtained with the usual
symbols +, −-, *, /, ^. Array sense operations are defined to act elementwise and are
obtained by preceding the symbol with a dot and therefore also often referred to as dot
arithmetic.
» y = v.^2; % y(1)=v(1)^2,…,y(n)=v(n)^2.
» B=A’; % transpose A
» B=transpose(A); % alternatively
In the case of matrix operations linear algebra introduces restrictions with respect to the
dimensions of the matrices involved. Of course, Matlab checks for this.
Matlab always assumes that the index of a new vector is a column index unless explicitly
specified otherwise (see example below). This means that the new vector v above is a row
vector and an error message results.
Alternatively, the row vector can be changed into a column vector by taking the transpose.
16
9 Elementary mathematical functions and constants
pi : the constant pi
i : the imaginary unit
inf : infinity
The following mathematical functions operate in array sense, i.e. on each element of the
variable separately:
17
10 Logical programming
In Matlab six relational operators can be used to compare variables or evaluate expressions
Relational operators can be applied to vectors and then they work elementwise
The first six elements of v are smaller than or equal to 0.5 and the remaining five are larger.
& : and
| : or
~ : not
Several built-in logical functions are available. We mention only the find function for vector
input.
At the first three positions and last three positions the elements of v are further away from 0.5
than 0.2.
18
execute a group of commands that follow the conditional statement, or to skip these
commands. In a conditional statement a conditional expression or condition is stated. If the
condition is true, a group of commands that follow the statement is executed.
if condition
commands
end
if condition
commands [1]
else
commands [2]
end
if condition
commands [1]
elseif condition
commands [2]
else
commands [3]
end
The condition needs to be a relational or logical expression taking the value true or false, in
Matlab 1 (true) or 0 (false).
19
11 Loop statements
FOR - loop
Syntax:
for variable = start value : increment : end value
commands
end
The increment can be positive as well as negative. If not defined, Matlab will use increment 1
as a default.
» for j = 0 : 10
v(j + 1) = j * 0.1; % the row vector v needs to start at index one!
end
WHILE - loop
Syntax:
while condition
commands
end
» x = 1;
» while (x >10^-6)
x = x /2;
end
A loop can be terminated with the break (which passes control to the first statement after the
corresponding end) or the error statement (which halts the program). This is in particular
convenient to avoid infinite while-loops, because sometimes it is not certain that the condition
will be met at a certain moment.
20
numerical approximation within a specified tolerance taking into account that the numerical
procedure might not converge.
Influence of round-off
» x = 0;
» while (x <1)
x = x+0.1;
end
»x
x=
1.1000
Note that this is not a proper method when we want to execute the loop statement exactly ten
times. In Matlab 10 times 0.1 is just a bit less than 1, because Matlab makes round-off errors.
This means that the loop will be executed 11 times in stead of 10 times, and therefore the final
value of x will be too big. In such a case it is better to rely upon integer computation.
» x = 0;
» for j = 1:10
x = x+0.1;
end
In order to force integer computation the command round (section 9) is often useful.
21
12 Output
One must be careful in using general print commands. For example, using the print command
in the file menu you can print the whole Matlab session. This may lead to unnecessarily long
waiting time for other people who want to use the printer.
With the command format or vpa we can define how a number is displayed (see section 4).
diary output : makes a diary of everything which happens during the session
and writes this to the file output. If necessary this
file can be printed.
diary off : stops monitoring the session.
The diary command easily gives an unnecessary amount of output. Therefore use the diary
command in a selective way and only at places where output is needed.
» table=[x’ y’];
22
» disp(table); % display a table containing x and y
With the format command one may influence the appearance of the output a little. Helpful as
well is the vpa function from the symbolic toolbox:
Even more advanced features are available using the fprintf command.
Advanced control mechanisms for printing are available with the command fprintf (see the
example program in section 20 or use help fprintf).
save data varlist : the variables in varlist are written to the file
data.mat in binary format. This file can be used in
a subsequent session.
save output varlist - ascii : the variables in varlist are written legible (8
digits, floating point) to the file output. If
necessary this file can be printed.
23
13 Input
Variables can be entered in Matlab in different ways. The first method is using the command
line. We already explained how to do this. Another way to enter it is:
This command writes the text from the string to the screen, waits for input (until a <return> is
given) and assigns the value given by the user to the variable x.
» load data
fetches the binary file data.mat. The file data.mat needs to be produced beforehand in Matlab
and besides a list of variables it also contains the values of these variables.
The command
» load data.txt
fetches an ASCII file with the name data.txt. The content is stored in a double precision array
with the name data. The file data.txt is only allowed to contain numbers, separated by blanks.
Each line of the file corresponds with a row in the array data. Each number on a line
corresponds with a column in the array data. The number of columns must be equal on each
line.
Data can also be imported using a graphical user interface, called the Import Wizard. Choose
in upper toolstrip for the option Import Data to start the Import Wizard. Then choose a file in
the new window from which data should be read, preview the data, and if you are satisfied,
use the next and finish buttons to import the variables in the Matlab workspace. You may
check the imported variables afterwards, using whos (Section 3) or the Workspace Browser
(Section 1.4).
24
14 Graphical issues
axis ( [xmin xmax ymin ymax] ) : sets the axes according to the given values
grid : adds a grid to the graph
title(’text ’) : writes text above the plot
xlabel(’text ’) : writes text underneath de x-axis
ylabel(’text ’) : writes text next to the y-axis
text(x, y, ’text ’) : writes text at the point (x,y) of the graphical
screen
t = num2str(var) : makes text of the value of var, which can
for example be written to the screen with
text(x,y,t).
25
Remark: help plot shows all the possible arguments with plot.
» x = linspace(0,2,21); y = sin(pi*x);
» plot(x,y); % plot sin πx on [0,2], plot
% automatically assigns the right limits
% to the axes in the graphical screen.
» axis( [0 2 -1 1] ); % adjust the x-axis and the y-axis; it is
% preferable to call axis after plot
» xlabel(’x’); ylabel(’sin x’);
» print % send the graph to the printer.
» clf
» hold on
» type = [’- ’ ; ’: ’ ; ’- .’ ; ’- -’] % spaces to equalize the length of the
% character strings
» xgraph = linspace(0,1,101);
» for j = 1 : 4
omega = j * pi ; % plot sin(ωx) on [0,1]
ygraph = sin(omega*xgraph); % for ω = π, 2π, 3π, 4π,
plot(xgraph,ygraph,type(j,:)); % distinguish the curves visually
end
» print figure % store the graph in a file named figure;
% use help print to see a list of
% available formats.
» t = linspace(0,10*pi,501);
» x = sin(t); y = cos(t);
» plot3(x,y,t) % plots a spiral on the cylinder
% x2 + y2 = 1.
» x = linspace(0,1,11); % or x = 0 : 0.1 : 1
» y = linspace(0,2,21); % or y = 0 : 0.1 : 2
» [X,Y]=meshgrid(x,y) % build a 2D product grid by
% forming x ⊗ y
» Z=X.*sin(X+Y); % compute function values for the 231 points
% of the 2D product grid. Note the usage of
% dot arithmetic.
» mesh(X,Y,Z); % or surf(X,Y,Z) % plot x*sin(x+y) on the domain
% 0≤x≤1, 0≤y≤2 using 231 grid points.
26
Moreover, Matlab has some easy to use plotting routines with names starting with ez.
Examples are:
As has been mentioned in section 1.5, the property editor can be used conveniently to
manipulate the graphical window.
27
15 Script files, function files
A script file is a file that consists of a sequence of Matlab commands: a Matlab program. We
make such a file with the help of the Editor. The standard extension for these files is .m, e.g.
for a script plotting the sinus function an appropriate name is plotsin.m.
% plotsin.m: The script creates a plot of the function sin(x) on the interval [0, π]
clear; clc; clf; % clear
x = linspace(0, pi, 41); % create a grid with spacing π/40 on [0, π].
y = sin(x);
plot(x,y);
axis([0 pi -1 1]); % set limits along axes
title(‘sin(x)’); % put text above the plot
The commands in the script file are executed after the filename without the .m extension, i.e.
plotsin, is typed on the command line. It is also possible to run a script file from another
Matlab program by including the command plotsin.
By means of function files we can add new functions to Matlab. A function file contains a
sequence of commands, like a script file, but by means of input and output variables it is
possible to communicate with other files. The filename of a function file is used to execute the
function.
The word function on the first line implies that it is a function file and not a script file.
Remark: At the position of function_name you need to fill in your chosen name for the
function. The filename of the file containing this function must be the same as this name with
the standard extention .m. Similar to names of variables, the function name is not allowed to
start with a number.
Both the input variable as well as the output variable may be matrices or vectors.
function y = average(v);
% This function computes the average of the elements of vector v.
% The function is stored in the file average.m
28
n = length(v);
y = sum(v)/n;
Having defined the function average, stored in the file average.m, this function is available for
scripts and other functions.
Matlab does not allow for a mixture of scripts and functions in a single file. However,
functions and subfunctions can be collected in a single file. As an example we present a single
file, called examplescript.m, containing both files from subsection 15.2.
function examplescript
% EXAMPLESCRIPT This function executes the commands as contained in the
% script examplescript.m (previous subsection). No input
% and output arguments are used.
function y = average(v)
% This function computes the average of the elements of vector v.
n = length(v);
y = sum(v)/n;
Typing examplescript on the command line, excutes the script. However, it is a disadvantage
that the workspace can not be accessed easily using the Workspace Browser because functions
have local workspaces.
Functions and subfunctions have local memories and, as a consequence, variables used in the
function file are local (i.e. only accessible inside the function), and therefore they are not
stored in and/or taken from the central Matlab memory.
function y = comp(x);
y = a * x; % the variable a is defined locally and does not
% have a value irrespective of the outside world,
29
% i.e. an error message follows.
function y = comp(x);
a = 2; % the variable a has the value 2, only within this
y = a * x; % function and this value is not know elsewhere.
Often it is neccessary to use a parameter in a function that gets its value outside the function.
You can show Matlab you want to use such a parameter by adding it to the list of that
function. In the following example we add the variable a to the list of the function comp:
function y = comp(x,a);
y = a * x; % the variable a gets its value outside the function
% and is passed to the function
This is not always possible. It may sometimes be necessary to define a variable globally, by
using global. If you do so the variable is defined in all program parts that contain the same
global declaration.
Remark: The declaration with global should only be used when there is no other possibility. If
you use it, it is wise to add some comments. For an example of the use of global see
subsection 19.1.
Remark: In the context of the courses for which this manual is written a convenient way to
communicate parameters, avoiding the global command, is to use nested functions, see
subsection 19.2.
.
30
16 Solving a system of equations
Consider the system of equations A x = b . A straightforward approach is to set x = A−1b ,
implemented in Matlab as x = inv(A)*b or x = A^−1*b. However, this approach is not
recommended at all, among others because of the high computational costs.
i) If a small system with a full matrix needs to be solved only once, we may use the black-
box backslash operator:
ii) If more than one system needs to be solved with the same matrix A, but different right-
hand sides:
A sparse matrix (Nederlands: ijle matrix) is a matrix containing many zero elements (or few
nonzero elements). Sparse matrices often occur in engineering sciences. The simplest measure
is to use A = sparse(A) in order to declare the matrix as being sparse as soon as solution
procedures become active. As an example, we give the number of floating-point operations in
case A is a tridiagonal matrix of size 100 x 100.
31
17 Tracking down errors
Matlab does not give specific directions for debugging programs. In any way it is useful to
generate (intermediate) output, and if necessary to recalculate it manually. Some useful
commands are:
whos : gives a table of the variables that are stored in memory. With
this command you can check the size.
disp(’labelj’) : directs the labeled text to the screen; can be used to find out
at which line the program does not work properly.
disp(var) : prints the actual value of the variable var on the screen. Can
be used to check values of intermediate results.
The Workspace Browser (Section 1.4) provides a very simple, but often effective, way to
check names, types and sizes of variables. Moreover, variables can be opened in the array
editor and then it is easy to check the values of the variables in use.
A more advanced feature can be found in the Matlab editor. After opening a Matlab file one
can use the Debug menu, and, among others, set breakpoints.
32
18 Symbolic computing
Matlab offers the Symbolic Math Toolbox, which is based upon the Maple kernel from
Waterloo Maple, inc. This Toolbox allows symbolic manipulation of variables in a way very
much similar to Maple, so it might be helpful to consult your Maple Manual. To obtain an
overview of functions in the toolbox type help symbolic in the Matlab window. A short
survey is given below.
Expressions may contain several symbolic objects which can be substituted by a call to subs
with lists (so-called cell arrays in Matlab) as second and third argument. Symbolic integration
and differentiation is performed through the int and diff functions, as in Maple. The resulting
expression sometimes appears to be quite complicated; then simplify, factor or conversion to
numeric form, using double might help.
Expressions can be solved for a variable using solve, whereas dsolve tries to solve differential
equations symbolically. The derivatives are denoted by D, D2, etc., and initial conditions can
be passed as additional arguments.
33
» syms x a c
» f = a*x^2+c
» x0=solve(f,x) % find the zeros of f
» x0=solve(‘a*x+c=0’) % solve ax+c = 0
» y=dsolve(‘D2x+x=0’) % solve the differential equation x”+x = 0
» y=dsolve(‘D2x+x=0’,’x(0)=1’) % solve the differential equation with initial
% value x(0) = 1
34
19 Functions, some advanced issues
Function files, often userdefined, form the heart of Matlab applications. In this section we pay
attention to some advanced features related to communication.
A function can be passed as an argument in several ways (we mention function handles, inline
objects, strings). Following Mathworks, we recommend using function handles.
domain = [1 2];
fplot(@f,domain); % @ indicates the function handle
For short functions it is also possible to prevent the occurrence of a separate function file by
using anonymous command line functions.
or alternatively
fplot(@(x) x.^2,domain);
35
m = 2; domain = [1 2];
fplot(@(x) x.^m,domain);
In the context of the courses for which this manual is written it is often needed to vary
parameters which are present in low-level routines. We can communicate parameters using
the global command (see subsection 15.4). However, this is not recommended. The
alternatives are:
The first method is advocated in some text books. The second method is frequently mentioned
in the Matlab help.
d y
= − a y + sin t ,
dt
y (0) = 1.
The parameter a needs to get its value outside the function file presenting the right-hand side
of the differential equation. In the examples below we use the Matlab routine ode45 for the
numerical integration of the differential equation. If needed, it is easy to substitute your own
solver, either as a stand-alone routine or as a nested function.
Nested functions
The underlying mechanism for communication of parameters is that nested functions share the
same workspace. This enables easy communication of parameters. If functions are nested,
then it is obligatory to use end on the last line of the function
fvalue = − a*y+sin(t);
36
end % end of solvede
The above example can be done on basis of a script file solvede and a separate function file
ownrhs.
a = 2;
y0 = 1 ; tspan = [0 1];
fhandle = @(t,y) ownrhs(t,y,a); % function handle referring to the user
% defined function ownrhs and presenting
% both a list of the basic variables as well as
% a list of the basic variables + parameters
[t, y] = ode45(fhandle, tspan, y0);
plot(t,y)
By comparing the two lists Matlab knows how to separate basic variables and parameters.
Moreover, the function handle has access to the workspace of solvede, i.e. the value of the
parameter a is known to fhandle. The function file accompanying the script file reads:
fvalue = − a*y+sin(t);
Usage of global
For completeness, the option using the global command is presented as well.
a = 2;
y0 = 1 ; tspan = [0 1];
[t, y] = ode45(@ownrhs, tspan, y0);
plot(t,y)
fvalue = − a*y+sin(t);
37
20 Example program, initial value problem
Consider the initial value problem
y ′ = 2 y + y + t , y (0) = 1 ,
1 1 2 1
y2′ = y1 + 2 y2 − t , y2 (0) = 0 .
The present system of differential equations is a linear system and of the form
y 2 1 t
y′ = f (t , y ) , y = 1 , f (t , y ) = Ay + g(t ) , A= , g = −t .
y2 1 2
For obtaining a numerical approximation of the initial value problem, we apply the Euler’s
forward method, leading to the basic formula
w n+1 = w n + f (tn , w n ) .
The first thing we need is a function file implementing the right-hand side of the system:
or
% set time span, initial value and time step h; determine the time grid.
% the approximate solution will be stored in a 2-column row vector with each 2-column
% containing the approximation at the corresponding time level.
38
% do the time stepping with forward Euler
for n = 1:nsteps
w(:,n+1) = w(:,n) + h*rhs(t(n),w(:,n));
end
%6.1f means: fixed-point format with 1 decimal and 6 positions (field width).
%17.7e means: floating point (exponential) format with 7 decimals and 17 positions.
\n means: continue printing on the next line
After the format string, the variables which need to be printed follow.
The field width is chosen in such a way that extra blanks take care that everything looks nice.
39
21 Example program, boundary value problem
Consider the boundary value problem
For obtaining a numerical approximation of the solution, we apply the finite difference
method with mesh size h , leading to the basic formula
w j −1 − 2 w j + w j +1
− + 2 w j = cos( x j ) , j = 1,⋯ , n ( x j = xleft + j h) .
h2
Here, n stands for the number of interior nodal or grid points. Let N denote the number of
unknown values of the solution on the grid. Because of the two Dirichlet conditions it holds
that N = n and no extra efforts are needed. The boundary values are just filled in, via
w0 = yleft , wn +1 = yright , and the resulting terms are transported to the right-hand side. This
leads to the system Aw = b with the matrix A of size N x N .
or
40
% solve the system Ax = b
v = (2/h^2 + 2)*ones(N,1); vp1 = -1/h^2*ones(N,1); vm1 = vp1; % the vectors containing subdiagonals now also have length N
A = spdiags(vm1,-1,N,N) + spdiags(v,0,N,N) + spdiags(vp1,1,N,N); % shorter: A = spdiags([vm1 v vp1],-1:1,N,N)
41
22 Reference and index
n,m - scalar
A - matrix
v,w,b - vector
x,y - arbitrary
f - user supplied function file
42
clear clear clears the variables from the Matlab memory. clear x {y} 9
removes the variable x {and y}
clf clf clears the graphical window 9, 25
close close closes the graphical window 9, 25
cos cos(x) is the cosine of (the elements of) x 17
cputime cputime determines the cpu time 9
demo demo starts a demonstration 6, 9
det det(A) determinant of A 17
diag diag (v,k) returns a square matrix with the elements of the vector v 14
on the kth upper diagonal
diary diary filename puts all following commands and results in a file 22
with the name filename. This stops after diary off is entered
diff diff(f,x) differentiates f w.r.t. x 33
disp disp('text') writes text on the screen. disp(x) displays the value of 10, 22
the variable x, without variable name
double double(expr) converts the symbolic expression to a number 33
dsolve dsolve(deq) solves the differential equation deq 33, 34
eig eig(A) computes the eigenvalues and eigenvectors of A 17
else, elseif see if 19
end end is the command that ends loop statements, conditional 19, 20
statements and nested functions 36
exp exp(x) is the exponent of (the elements of) x with base e 17
eye eye(n) is the nxn identity matrix. eye(m,n) is an mxn matrix with 13
ones on the diagonal and zeros elsewhere
factor factor(expr) factors the symbolic expression expr 33
figure figure(n) opens a new graphical window with title ‘figure n’. If the 25
window already exists it jumps to it.
find find(v) returns the indices of the nonzero elements of v 18
for loop statement: 6, 20
for variable = start value : increment : end value,
commands
end
format formats the output: 10
format short - 5 digits, fixed point
format short e - 5 digits, floating point
format long - 15 digits, fixed point
format long e - 15 digits, floating point
standard configuration is short.
format compact suppresses extra empty lines in the output
format loose adds empty lines
fplot fplot(@f,[a,b]) plots the function f on [a,b] 25, 35
fprintf C-command for advanced formatting of output 23, 39
function user defined function: 28
function outputvar = functionname (inputvars)
commands
Function files have to have the name functionname.m.
global global x changes x into a global variable 30, 37
43
grid adds a grid (a lattice of horizontal and vertical lines) to a graph 25
help help shows the functions you can get information about. 5, 9
help functionname shows this information on the screen. helpwin
generates an extra window with helptopics
hold hold on keeps the last plot in the graphical screen. A new graph will 25
be plotted on top of the existing one. hold off restores the default
settings. In that case, when a plot command has been given, the
graphical screen will be cleared before the new graph is be plotted
i the imaginary unit 17
if conditional statement: 19
if statement if statement
commands commands
else elseif statement
commands commands
end else
commands
end
imag imag(c) returns the imaginary part of the complex number c 12
inf infinity 17
input input('text') displays text on the screen and waits for input by the 24
user. Can be assigned to a variable
int int(f,x,a,b) integrates f w.r.t. x from a to b 33
length length(v) returns the number of elements of the vector v 17
linspace linspace(x1,x2,n) generates a n-point grid on [x1,x2]; i.e. grid with 13, 25
spacing (x2-x1)/(n-1)
load load filename loads the variables of the file filename into the 24
memory. The file is of type .mat or of type .txt.
log log(x) is the natural logarithm of (the elements of) x 17
log10 log10(x) is the logarithm with base 10 of (the elements of) x 17
lu lu(A) computes the lu factorization of the matrix A 17, 31
max max(v) returns the largest element of the vector v 17
mesh mesh(x,y,Z) plots the matrix Z versus the vectors y and x, creating a 26
mesh
meshgrid meshgrid(x,y) creates a 2D grid from the vectors x,y 26
min min(v) returns the smallest element of the vector v 17
norm norm(v) computes the Euclidean norm of v and norm(v, inf) 17
computes the infinity norm
num2str num2str(var) converts the number var to a text string 25
ones ones(n) is an nxn matrix filled with ones, ones(m,n) is an mxn 13
matrix
pause pause pauses the running programme and waits until the user 5, 9
presses any key. pause(n) pauses during n seconds
pi pi is the machine’s representation of π 17
44
plot Drawing a graph: 5, 25
plot(v) - plot the vector v versus its indices
plot(v,w) - plot the vector w versus the vector v
plot(m,n,'symbol') - put a symbol at position (m,n) in the
graph. The following symbols can be
used: +, *, o and x
plot3 plot3(x,y,z) plots a line through the coordinates of vectors x, y, z 26
print direct the graph to the printer. print filename stores the graph in the 25
file filename
quad library routine: quad(f,0,1) computes the integral of the function f
on [0,1].
quit logout from Matlab 5, 9
real real (c) returns the real part of the complex vector c 12
rem rem(m,n) returns the remainder after division of m by n 17
round round(x) rounds the elements of x to the nearest integer 17
save save filename x {y} saves the variable x {and y} into the file 23
filename.mat
script file a script file is a file consisting of a sequence of Matlab commands. 28
After you have typed the file name at the command prompt these
commands will be executed.
shg shg shows the most recent graphical screen 9, 25
simplify simplify(expr) simplifies the symbolic expression expr 33
sin sin(x) is the sine of (the elements of) x 17
size [m,n] = size(A) returns the size of the matrix A 17, 32
solve solve(expr,x) solve expr=0 for x 33, 34
sparse sparse(A) saves computations as well as memory space. It can be 31, 41
used when A is a band matrix, and the computations only involve
non-zero elements.
sqrt sqrt(x) is the square root of (the elements of) x 17
subplot subplot(m,n,p) breaks the figure window into a m-by-n matrix of 25
plot areas and selects the p-th member for the current plot, where
counting is done row wise.
subs subs(y,x,value) substitutes x=value into y 33
sum sum(v) is the sum of the elements of the vector of v 17
surf surf(x,y,Z) plots the matrix Z versus the vectors y and x, creating a 26
surface
surfc same as surf, but adds a contour plot beneath the surface 26
sym sym x declares x to be symolic 33
syms syms x y declares x and y to be symbolic 33, 34
tan tan(x) is the tangent of (the elements of) x 17
text text(m,n,'text') writes text at position (m,n) of the graphical screen 25
tic,toc tic and toc are stopwatch timer for the elapsed time 9
title title('text') writes text as a title above the graph in the graphical 25
screen
vpa vpa(x,d) takes x using d digits 10, 23
45
while conditional loop statement: 20
while statement
commands
end
whos whos shows the name, size and type of the variables in the Matlab 9, 11
memory 32
xlabel xlabel('text') places text underneath the x-axis of the graphical 25
screen
ylabel ylabel('text') places text next to the y-axis of the graphical screen 25
zeros zeros(n) returns an nxn matrix with zeros; zeros(m,n) returns an 13
mxn matrix
46