Introduction To MATLAB: Stefan Güttel October 15, 2020
Introduction To MATLAB: Stefan Güttel October 15, 2020
Introduction To MATLAB: Stefan Güttel October 15, 2020
Stefan Güttel
Contents
1 Introduction 2
3 Expressions 3
5 Graphics 5
6 Programming Scripts 6
7 Functions 7
10 Assignment 11
1
1 Introduction
In this course of 4 hours we will give an introduction to MATLAB. This course material
is based on the MATLAB documentation which can be accessed by typing doc in the
MATLAB command window. Another useful command is help. In combination with a
function name it returns a help text for that function. Example: help sum
Apart from the excellent MATLAB documentation, there are many MATLAB tutori-
als and books available. Here are a few:
• Cleve Moler, one of the MATLAB authors, has written two interesting books on
numerical computing with MATLAB. These books are freely available at
https://uk.mathworks.com/moler.html
Familiarize yourself with the command window, workspace, command history, and
navigation in the MATLAB documentation. MATLAB code can be stored in so-called
m-files and it is convenient to use these files also during the development phase of a
project. Everything that follows the character % is treated as a comment. Use the cursor
keys to navigate up and down the history in the command window. Use the Tab key for
auto-completion.
You can leave MATLAB by typing exit or closing the window. Long-running MAT-
LAB codes can (often) be interrupted by pressing Ctrl+C. Example: while 1, end
2
Exercise 1: Create the matrix
A =
0 0 0 0 0
0 0 0 0 0
5 4 3 2 1
with a single line of MATLAB code. Then assign random numbers to its 2nd row. Then
assign the 1st row such that all columns sum to 0. Then reorder the columns reversely
and transpose the matrix. (4 commands)
Exercise 3: When accessing elements of a matrix with just a single index, the elements
will be addressed columnwise starting with the first column. For example, B(6) with
the above 5 × 5 matrix will return 2, the element in the (1, 2) position. Create a sparse
zero matrix C of size n × n via
n = 4;
C = sparse (n , n );
and populate its entries with 3 lines of MATLAB code such that
full ( C )
ans =
2 -1 0 0
-1 2 -1 0
0 -1 2 -1
0 0 -1 2
Do you recognize this matrix?
3 Expressions
In MATLAB numbers are just 1 × 1 matrices. There are some special numbers like i, pi,
eps, realmin, realmax, Inf, NaN (the latter two are not case-sensitive). MATLAB allows
to redefine these numbers as variables, which can cause confusion. So it is better to avoid
such variable names. Nevertheless, it is good practice to write 1i for the imaginary unit,
as this will give the expected result even if i has been redefined. Variables do not need
3
to be declared; they are instantiated with their first definition using the assignment
operator = .
Example 4:
rho = 1 .6180 ;
a = abs (3+4 i )
a =
5
toobig = pi * huge
toobig =
Inf
Note how the final ; in the first line suppresses the output. In order to refer to the
last output use the ans variable.
1 kb − Ax
ek2 kx − x
ek2 kb − Axe k2
≤ ≤ cond2 (A) .
cond2 (A) kbk2 kxk2 kbk2
More commands: qr, chol, schur, eig, eigs, svd, svds, fft
4
Exercise 6: Familiarize yourself with the eig command and compute the eigenvectors
and eigenvalues of the matrix A from Exercise 5. The Perron theorem implies that all
eigenvalues λj of a matrix with positive entries and equal row sums σ satisfy |λj | ≤ σ,
and that there is exactly one eigenvalue λk = σ. Verify this numerically.
5 Graphics
It is very easy to generate nice plots and animations with MATLAB. There are many
functions for 2D/3D plots and images and we will only list a few of them.
Example 7: Plot the function f (x) = sin(x) and its zeros on [0, 2π].
figure (1)
x = linspace (0 ,2* pi ,200); % 200 typically enough for plotting
fx = sin ( x );
plot (x , fx , 'b - ') % this plots a ( b ) lue line ( -)
hold on
plot ([0 , pi ,2* pi ] ,[0 ,0 ,0] , ' ro ') % this plots ( r ) ed circles ( o )
There are also commands for changing the axes, and adding legends or titles. Some
of the most useful ones are listed below.
Example 8: Following the above example, we can make our plot more descriptive.
figure (1)
xlabel ( 'x ' ); ylabel ( 'f ( x ) ' );
legend ( ' sin ( x ) ' , ' zeros ')
title ( 'a simple graph ')
axis ([0 ,2* pi , -1 .2 ,1 .2 ])
grid on
For generating a surface plot of a function f (x, y) we need to create a parametrization
of its (x, y) domain. This can be done conveniently using the meshgrid command.
Example 9: Plot | sin(x + iy)| over the domain [−1, 7] × [−1, 1].
figure (2)
x = linspace ( -1 ,7 ,200); y = linspace ( -1 ,1 ,200);
[X , Y ] = meshgrid (x , y );
Z = X + 1i*Y;
F = sin ( Z );
5
surf (X ,Y , abs ( F ) , ' LineStyle ' , ' none ')
axis tight
colorbar
6 Programming Scripts
MATLAB offers a very intuitive and clear programming language. Programs are typi-
cally written as m-files in the editor. When working with MATLAB interactively (as we
have done so far), it is recommended to type everything which requires more than one
line in the editor. This allows one to modify and debug the code very efficiently. Saved
m-files can be called by their name from the MATLAB command line or by pressing
Ctrl+Enter.
% % Fibonacci sequence
for j = 3: length ( f )
f ( j ) = f (j -2) + f (j -1);
if f ( j ) <= 10
str = sprintf ( ' %2 drd Fibonacci number is smaller / equal to 10 ' ,j );
else
str = sprintf ( ' %2 drd Fibonacci number is greater than 10 ' ,j );
end
if j == 19 , str = [ str ' --- puh , almost done... ' ]; end
disp ( str )
end
6
Exercise 11: Use meshgrid to create a grid of complex numbers z = x + iy with
x ∈ [−2, 1] and y ∈ [−1, 1]. For each number z in this grid run 200 iterations of the
Mandelbrot recursion rn+1 = rn2 + z starting with r0 = 0. Use the pcolor function to
visualize |r200 | for each number z. Challenge for MATLAB gurus: no more than 10 lines!
7 Functions
Essentially, MATLAB functions are m-files that accept input arguments and produce
outputs. In its simplest form, a function is defined in an m-file with the same name.
7
documentation (type doc). In this section we will discuss with the help of two examples
some functions for numerical integration and the solution of differential equations.
There are a number of routines for calculation definite integrals ab f (x) dx and their
R
Exercise 14: Solve the 1D heat equation on an interval, discretized in space by second-
order finite differences, and in time by MATLAB’s ode15s. More precisely, solve
2. Create a column vector xx of the grid points [x1 , x2 , . . . , xn ]T using the colon
operator : . Define a vector u0 of the initial data, [b(x1 ), b(x2 ), . . . , b(xn )]T . (If the
inline function for b(x) is vectorized this can be done via u0 = b(xx).)
8
3. Create the n × n matrix A which maps column vectors u to the finite difference ap-
proximations of the second derivative (i.e., Au will be an approximation for u00 (x) at
the grid points x1 , x2 , . . . , xn ). You can use the command gallery('tridiag',n),
which will generate a sparse tridiagonal matrix
2 −1
..
−1 2 .
∈ Rn×n .
.. ..
. . −1
−1 2
4. Define the inline function f = @(t,u) A*u and a vector tt of 100 equidistant time
points in [0, T ]. Then call
[ tt , uu ] = ode15s (f , tt , u0 );
figure
for j = 1: length ( tt )
plot ( xx , uu (j ,:));
title ([ 't = ' num2str ( tt ( j ))])
axis ([0 , L ,0 , norm ( u0 , inf )])
shg ; pause (0 .2 )
end
5. You may also want to try other MATLAB integrators like, e.g., ode45, and compare
which one works best for this problem.
9
Example 15: Compute the square root of 5 · 106 random numbers.
clear all
v = rand (5 e6 ,1);
Exercise 16: Run the above code through the profiler and find the line where most of
computation time is spent on.
Publishing MATLAB code: When publishing MATLAB code in LATEX inside the
verbatim environment, it is recommended to include the package upquote to make sure
all quotes ' can be copied-and-pasted correctly into the MATLAB command window
(this is what one gets without this package: ’ ).
Another option for publishing MATLAB in LATEX is the mcode package, which high-
lights keywords, comments, and strings in different colors (as is done in this document).
Graphics workflow: When writing a paper or thesis, often a lot of time is spent on
generating graphics. It is therefore worth spending some time in advance for optimizing
the workflow of including figures in your work. I recommend to generate all graphics with
a dedicated script and to include these directly into the LATEX file without generating
copies. (Warning: multiple instances of the same file may cause severe headaches!)
10
10 Assignment
Task: Implement and test the Runge-Kutta method and numerically solve an ordinary
differential equation. Make sure to comment your work by adding MATLAB comments.
1. Copy and paste the following MATLAB code into an m-file called rk4.m:
function [ tt , yy ] = rk4 (f , tt , y0 )
% RK4 Solve y ' = f (t , y ) with initial value y0 using Runge - Kutta.
% The argument f is a function handle with input parameters (t , y ) .
% The vector tt contains the time points at which to solve the ODE.
% The row vector y0 is the initial value at tt (1) .
% Each column of the output matrix yy corresponds to the Runge - Kutta
% approximation of y at each time point in tt.
end
2. Modify rk4.m for implementing the classical Runge-Kutta method defined via
k1 = f (tn , yn )
k2 = f (tn + h2 , yn + h2 k1 )
k3 = f (tn + h2 , yn + h2 k2 )
k4 = f (tn + h, yn + hk3 )
k1 + 2k2 + 2k3 + k4
yn+1 = yn + h ,
6
where at h = tn+1 − tn at each time step. (This can be done in less than 10 lines
of code, but doesn’t need to!)
3. Create a new m-file called test1.m to test your Runge-Kutta implementation. To
this end consider the simple initial value problem
y 0 (t) = −y, y(0) = 1, (1)
to be solved at equispaced time points t = 0, 0.1, 0.2, . . . , 2. Visually compare
your numerical solution ye(t) (the output yy) with the exact solution y(t) = e−t
for t ∈ [0, 2] by plotting both in the same figure. (Hint: Both curves should look
almost identical.)
4. Create a new m-file called test2.m to solve the same test problem (1) over the
time interval [0, 2] and measure the error of the computed solution ye(t) at t = 2
compared to the exact solution y(t) = e−t , i.e., evaluate err = |ye(2) − y(2)|. Do
this for n = 5, 10, 15, . . . , 50 equal time steps in [0, 2] and plot the error versus n.
It’s best to use a loglog plot for this. (Hint: You should see a straight line and
the error should decrease approximately like C/n4 for some constant C.)
11
5. Attach the three files rk4.m, test1.m, test2.m to an email and
You should receive a confirmation of submission via email until November 16th.
If you do not receive this confirmation, you need to get in contact immediately.
12