Introduction to Matlab course for the CM Hub at Imperial College
3 × 2 hour classes
- Part 1: Call-and-response Matlab, basic arithmetic, simple scripts
- Part 2: 2D plots, functions, Collatz conjecture, if, for, while
- Part 3: Data analysis, linear algebra, 3D plots
- use Matlab to run scripts,
- apply fundamental components of the Matlab language including variables, loops, conditionals and functions,
- create programs designed to solve simple problems,
- interpret common errors and use these to help debug a program.
- No programming experience is required
- Students are welcome to bring their own fully charged laptops to these sessions although there are computers in situ.
- If on a laptop, please install MATLAB.
Timestamps are in the descriptions and correspond to the numbering in this document.
Pros of Matlab:
- Shallow learning curve for maths
- Comes with a lot of useful baked-in tools
- Interactivity/debugging is quite easy
- Backwards compatible and has been around for a long time
Cons of Matlab:
- Ideosyncratic
- £££££££££££
- Bad for programming in general
- Isn't used outside of universities
- Plays badly with other languages
In short: Matlab is a good plug-and-play language for medium-sized maths problems.
- The command window allows for call-and-response interface
Join in:
3+43*43/43^4
Try:
- Does Matlab respect BIDMAS?:
3+4*5
Join in:
x=2xx=-9xwidth = 3(long names are good)area = width^2y=12/2+5(y+1)^2y=sin(x)*cos(x)
- Find square root of x: Google the function
- Or use F1 on the function
Try:
- Find sin–1(1)
- Find the remainder when 14 is divided by 3
- Find |–4|
Try:
- What's the difference between
x=40andx=40;?
The building block of Matlab is the matrix. These can represent lists, data tables, or matrices as mathematical objects.
Join in:
x = [29 43 13 3.2 -26]y = [1 2; 3 4][1:10](note endpoints)[1:2:10][3:-0.1:2]
Try:
- What do apostrophes do?
x'y' - What do commas do?:
[29, 43, 13, 3.2, -26] - How long is
[1:0.5:10]?
Join in:
x = [3 1 4 1 5 9]x(2)x(4) = 50xy = [3 10; -1 6]y(1,2) = 100yA = [1:10]'*[1:10](explanation later)A(4, [1 2])A([8 9],[8 9])A(3,4:end)A(1:end,4)A(:,4)sum(A(:,4)):sumsums the columns
Try:
- Create the matrix
A = magic(5)(explanation later) - Get the element in the 1st row, 1st column
- Get the element in the 5th row, 2nd column
- Get all elements in the last row
- Get the element in the 6th row, 4th column (...)
- What does
A([2 1 1 1],4)do? Try it.
Now try:
- Show that the
sumof the first column ofA= thesumof the last column ofA - Find the
sumof the diagonal ofA(hint: search for the function that gives the diagonal ofA... or guess!) - Harder! Find the
sumof the '/'-leaning diagonal ofA. Hint: try showing the rows ofAin reverse before usingdiag - Harder! Produce the elements of
Afor which both coordinates are odd - Replace the bottom row of
Awith zeros
Join in:
x = [1:10]y = [11:20]x+yx-y2*xx/2x*y... what do you expect to happen? Why is this problematic butx+xisn't? (Hint: think about matrices)x.*yx.^22.^x
Try:
sumthe numbers from 1 to 100 (are you faster than Gauss?)sumthe squares from 1 to 5- What is the mean of the powers of 2 from the zeroth power to the sixth power? (Google the function to find the mean... or guess!)
A script is the simplest type of Matlab program.
Join in:
- Create a script
magic_square_test.m - Let's see if switching the top and bottom row of a magic square keeps it a magic square:
n = 4; % matrix size
M = magic(n);
top_row = M(1,:);
bottom_row = M(end,:);
M(1,:) = bottom_row;
M(end,:) = top_row;
disp(sum(M)); % to display we can use 'disp' or just leave off the semicolon
disp(sum(diag(M)));
disp(n*(n^2+1)/2); % magic constant
- Run the script.
- Breakpoints
- Change the script so that we do it with a matrix of size 3 instead.
Join in, putting this in a script, first_plot.m:
x = [0:10]y = exp(x)plot(x,y)- How do we make this graph smoother?
Try:
plotsin(x) for x between 0 and 2πplota circle: recall x = cos(θ), y = sin(θ) for θ between 0 and 2π to make a circle with radius 1.
Join in:
x = [0:0.1:10]y = exp(x)plot(x,y,'r-')- Change to:
plot(x,y,'go')
Try:
- Plot a magenta, dotted line with large line width and squares as markers. (Look at the F1 help file for
plot)
Join in:
xlabel('x')ylabel('exp(x)')title('Exponential growth is fast')xlim([0 5])- Now let's try multiple plots
x = [0:0.1:10]y1 = exp(x)y2 = exp(0.9*x)plot(x,y1,'r-')hold onplot(x,y2,'k--')legend('exp(x)','exp(0.9x)')
Try:
- The same but use
loglog,semilogxorsemilogyinstead ofplot(the syntax is the same). What do they do?
Now we move from simple call-and-response to writing whole programs
- Difference between scripts and functions.
- Let's do functions first.
Join in:
- Create a new file
collatz_function.mand inside it write:
function y = collatz_function(n)
y = 3*n+1;
end
- Save and run
collatz_function(5)from the command line
Try:
- Create a function
first_and_lastwhich takes a vectorvand returns the sum of the first element in the vector and the last element in the vector - Test it out in the command line, letting
test_vector=[1:10]and runningfirst_and_last(test_vector).
Join in:
- Change
first_and_lastso it outputs the first and last elements separately - Test it out:
[first, last] = first_and_last(v)firstlast
Join in:
- Create a function
function y = sign_function(x)so that the core functionality reads:
if x > 0
y = 1;
elseif x == 0
y = 0;
else
y = -1;
end
- Note:
==is not=
Try:
- Change
collatz_function(n)so that if n is even, it returns n/2, otherwise it returns 3n+1.
Join in:
- Create a new script
squares_up_to.m. Inside let's write
n = 10;
for i=1:n
disp(i^2); % this squares i and then displays it on the screen
end
- Run the script
Try:
- Change the script to display the first 10 odd cubes.
Join in:
- Create a new function
count_up_to.m. Inside let's write
function count_up_to(n)
i = 1;
disp(i);
while i < n
i = i + 1;
disp(i);
end
end
Try:
-
The Collatz conjecture:
- The Collatz conjecture is a famous mathematical conjecture about a sequence which starts with a positive integer
n. The next term in the sequence is given bycollatz_function(n). The conjecture says that this sequence will always reach the number 1 (where it ends). - For example, the sequence for
n=5is 5, 16, 8, 4, 2, 1. - Your job is to create a new function,
collatz_conjecture(n), which takes a starting numbernand displays the terms in the sequence. - Take a moment to think about the logic you need!
- Suggested method: Use a
whileloop inside the functioncollatz_conjecture(n). Whilendoes not equal 1, runcollatz_function(n)to get the next term in the sequence. - "Not equal to" is
~=in Matlab. - Hint 1: You have to let the output of
collatz_function(n)become the input of the function the next time round. - Hint 2: You have to change the value of
nwithin your while loop otherwisenwill never equal 1.
- The Collatz conjecture is a famous mathematical conjecture about a sequence which starts with a positive integer
-
For the keen: Write a script,
collatz_trials.mwhich loops through the numbers 1 to 10, printing out the Collatz path every time.
There are lots of ways of saving and reading data in Matlab. A good question to ask is 'do I want to open the saved data in another program?'
Join in:
- Download the file
examples/exchange_rates.csv - Move the CSV file to your folder
- Have a look at this file in Excel
- Create a new script,
exchange_rate_data.m data = csvread('exchange_rates.csv',1,0);
Your turn:
- Plot the GBP/USD price (12th column) against the day of the year (1st column)
- On the same graph, plot the EUR/USD price (11th column) against the day of the year
- On a new graph, plot the EUR/GBP price against the day of the year. Can you guess which year this data is from?
- What was the minimum number of euros you could buy with £1 that year?
- On which day of the year was this the case? (Hint: look up
minin the help files)
Join in:
- Create another data matrix,
data_pounds, which contains the exchange rate of these currencies versus GBP, instead of USD - Save the EUR/GBP data matrix
csvwrite('exchange_rates_pounds.csv',data_pounds)- Look at it in Excel
Join in:
A = [1 0 5; 2 1 6; 3 4 0]Ainv(A)- Let's solve Ax = (–1 0 1)T
b = [-1; 0; 1]- If Ax = b then x = A–1b, so
inv(A)*b A\b
Try:
- Solve the system of equations x+y=2, -x+3y=3.
- Let
A = [1 2 3; 4 5 6; 5 7 9]andb = [-1; 0; 1]. Solve Ax=b. What is the determinant of A? (Google!)
If you're taking this course through the Graduate School, please fill out the feedback form.
Join in:
A = [1 0 5; 2 1 6; 3 4 0]A.^2A^2
Try:
- Create a 2x3 matrix, call it
B - Create a 3x4 matrix, call it
C - Try calculating
B*CandC*B - Multiply
Bby the transpose ofB - Make one of the elements of
Bimaginary (i) - Calculate
B'. What does the apostrophe actually do?
Size gives rows × columns
size(A)size(B)x = [1:10]size(x)... note it's 1×10 (a row vector), not 10×1 (a column vectors).
Vectors by default are row vectors in Matlab.
Join in:
A- Let's multiply
Aby (3 1 4)T x = [3 1 4]'(note apostrophe) orx = [3; 1; 4](note semicolons)A*x
Try:
- Let
x = [3 1 4](without the apostrophe). Will calculatingA*xwork? Try it. - Create the 3×3 identity matrix
I = eye(3). Multiply I by x.
A = [-2 -4 2; -2 1 2; 4 2 5]eig(A)
Try:
- How to get eigenvectors? (Google or F1)
Join in:
t = [0:0.1:10];x = sin(t);y = cos(t);z = t;plot3(x,y,z)grid on
Visualise f(x,y) = sin(x)cos(2y) for 0 ≤ x,y ≤ 2π:
- Create grid
x = linspace(0,2*pi,300)y = linspace(0,2*pi,300)[xg,yg] = meshgrid(x,y);
f = sin(xg).*cos(2*yg);contour(xg,yg,f,20);surf(x,y,f)shading interp
Single-quote strings are vectors, with each character an element in the vector
Join in:
greeting = 'hello there'(note: single quotes)greeting(3)[greeting(1:4) greeting(7)]
Double-quote strings (R2016b upwards only) are individual things. You can create vectors of multiple strings
greeting = "hello there"greeting(3)greeting(1)conversation = ["hello there", "general kenobi"]conversation(2)
Try:
- Let
surnameequal your surname - Find the last letter of your surname
- Output the first and last letter of your surname, put together
- If
conversation = ['hello there', 'general kenobi'](with single quotes), what isconversation(2)?
Try:
sin(x),cos(x),tan(x)floor(x),ceil(x)max(x),min(x)triu(A),rand(n)
- Plot the graphs of sin(ax), sin(bx) and sin(cx) for x from –π to π, with these plots in different colours. Include a legend, a title and a label for the x-axis.
- Create a new function
fib.m. Let this function take a numbernand output thenth Fibonacci number. Recall the algorithm:- F(1) = 1
- F(2) = 1
- F(i) = F(i-2) + F(i-1)
- Create a vector of the first 20 Fibonacci numbers
- Save them to a file
- Plot them
- Create a 10×10 matrix of random numbers (hint: use
rand) and call itA - Find the eigenvalues of A
- Show that the sum of the eigenvalues of A = the trace of A
- Plot the eigenvalues on an Argand diagram, using a circular marker at each eigenvalue
- Now add a row and column of zeros to A, to form B, which is therefore an 11×11 matrix. (Think about how you might want to do this!)
- Now plot the eigenvalues of B on the same graph as the eigenvalues of A, in another colour.
- What can you say about the eigenvalues of B compared to the eigenvalues of A?
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Licence.

