MATH2221C
Mathematics Laboratory II
Lecture 1: Introduction to MATLAB
Gary Choi
January 7, 2025
Teaching team
Instructor: Prof. CHOI Pui Tung Gary
• Email:
[email protected] • Office: Lady Shaw Building (LSB) Room 204
Teaching Assistants:
• Mr. TSANG Hei Tung (Science Center 333B, [email protected])
• Mr. HUANG Yanwen (Science Center 333B, [email protected])
2
Course logistics (MATH2221C)
Lectures: Tuesday 10:30am – 11:15am, LSB 232B
Lab sessions: Thursday 2:30pm – 4:15pm, LSB 232B (starting from 16/1)
Assessment scheme:
• Lab Assignments 40% (10 Labs, 4% each, to be completed
and submitted during each lab session)
• Test 1 30% (February 27, 2025, 90 minutes,
during the usual lab session time)
• Test 2 30% (April 17, 2025, 90 minutes,
during the usual lab session time)
Note: You must attend your registered lab session but not the other MATH2221
sessions. Attending the wrong session will result in 0 marks for the assessment!
3
Course schedule
January February
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 [1]
5 6 7 8 9 10 11 [2] [3] 4 5 6 7 8 Lecture 1-
12 13 14 15 16 17 18 9 10 11 12 13 14 15 Lecture 13
19 20 21 22 23 24 25 16 17 18 19 20 21 22
26 27 [28] [29] [30] [31] 23 24 25 26 27 28 1
March April Lab 1 - Lab 10
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
2 [3] [4] [5] [6] [7] [8] 1 2 3 4 5
9 10 11 12 13 14 15 6 7 8 9 10 11 12 Test 1 and
16 17 18 19 20 21 22 13 14 15 16 17 Test 2
23 24 25 26 27 28 29
30 31
4
Course policy
Honesty in Academic Work
• The Chinese University of Hong Kong places very high importance on honesty
in academic work submitted by students, and adopts a policy of zero tolerance
on cheating and plagiarism. Any related offence will lead to disciplinary action
including termination of studies at the University. Although cases of cheating or
plagiarism are rare at the University, everyone should make himself / herself
familiar with the content of the following website:
http://www.cuhk.edu.hk/policy/academichonesty/
and thereby help avoid any practice that would not be acceptable.
Artificial Intelligence (AI) Policy: Prohibit all use of AI tools
• This is a first course for you to learn and practice MATLAB
• AI-generated codes are usually not optimal!
5
What is MATLAB?
MATLAB stands for …
6
What is MATLAB?
MATLAB stands for …
7
What is MATLAB?
MATLAB stands for MATrix LABoratory
8
What is MATLAB?
MATLAB stands for MATrix LABoratory
Why matrix? … Markov process
Electric circuits
Image processing
[Wikipedia]
Regression analysis
[matrixlab-examples.com]
−3 1 2 𝑖1 −1
1 −6 3 𝑖2 = 0
[Mathworks]
2 3 −6 𝑖3 −6
[Wikipedia] 9
What is MATLAB?
MATLAB stands for MATrix LABoratory
Why matrix? …
Calculus and Optimization in Engineering
Modelling in Biology
[Mentor Graphics] [Youtube]
10
What is MATLAB?
MATLAB stands for MATrix LABoratory
Why matrix? … The Matrix (1999)
Morpheus: The Matrix is everywhere. It is all around us.
11
What is MATLAB?
MATLAB stands for MATrix LABoratory
Invented by Cleve Moler in late 1970s
Calculator x Programming language x
Interactive visualization and control tool Cleve Moler (1939 - )
• Facilitate matrix and vector computations
• Easy-to-use visualization tools
• Easier to program than C/C++/Python/…
MathWorks, Inc established in 1984
http://www.mathworks.com/
• MATLAB
• Simulink MathWorks headquarters
Natick, Massachusetts, USA 12
MATLAB’s main features
MATLAB
Built-in Functions / User-written Functions
Computation Visualization External Interface
(Mex-files)
• Linear algebra • 2D Graphics
• Interface with C, Java,
• Calculus • 3D Graphics
and Fortran Programs
• Differential equations • Animation
• Optimization Toolboxes (Collections of Specialized Functions)
• Data analysis • Optimization • Symbolic Math • Medical Imaging
• Signal/image/video • PDE • Computer Vision • Financial
processing
• Parallel Computing • Radar • Aerospace
• Deep Learning • Bioinformatics • and many more… 13
Where can I access MATLAB?
Our computing lab (LSB 232B)
• MATLAB version R2021a
• With some toolboxes installed
CUHK library computers
https://www.lib.cuhk.edu.hk/en/use/facilities/computer/
Download and install on your own computers
• CUHK license
https://www.itsc.cuhk.edu.hk/all-it/procurement-
support/campus-wide-software/matlab-and-simulink/
14
By the end of this course, you will be able to use MATLAB to…
Perform basic computations
• Scalar
• Vector
• Matrix
• Commonly used built-in functions
• Loops and Conditional Statements (if, for, while, …)
Write your own MATLAB programs with different input and output
15
By the end of this course, you will be able to use MATLAB to…
Create 2D and 3D visualizations
Line plot: Polar plot: Surface plot:
x=0:0.05:5; t=0:.01:2*pi; [X,Y] = meshgrid(-10:0.25:10,-10:0.25:10);
y=sin(x.^2); polar(t,abs(sin(2*t).*cos(2*t))); f = sinc(sqrt((X/pi).^2+(Y/pi).^2));
surf(X,Y,f);
plot(x,y);
16
By the end of this course, you will be able to use MATLAB to…
Perform data analysis
• Reading numerical data or text data
from txt/xlsx/csv/…
• Analyzing them in MATLAB
• Saving the results
Perform other special tasks
using different toolboxes
• Image processing
• Optimization
• …
17
MATLAB software interface
To start MATLAB: Start → MATLAB R2021a → MATLAB R2021a
(or look for the MATLAB shortcut on the desktop)
Directory
Window:
showing the Command Window: Workspace
files in the where you input Window:
current folder MATLAB commands showing what
variables are in
the memory
Details:
show the
file details
18
MATLAB software interface
Note: The interface can be customized! Further change the layout
Hide/show
different parts
Drag and change the
size of different parts
19
Basic arithmetic operations in MATLAB
>> MATLAB prompt
>> 2*(2 + 2) – 4/2 Enter 2*(2 + 2) – 4/2 and hit the return/enter key
ans = Note that the result of an unassigned
expression is saved in the default variable ans
6
Use the arithmetic operations
• Addition +
• Subtraction -
• Multiplication *
• Division /
>> x = 2*(2 + 2) – 4/2 You can also assign the value of an
expression 2*(2 + 2) – 4/2 to a variable x
x=
6 Hit the up-arrow key. What do you see?
20
Basic arithmetic operations in MATLAB
>> radius = 2.5; Assign a value to a variable
A semicolon ; at the end suppresses screen output
>> radius MATLAB remembers radius, though.
You can recall the value radius by simply typing radius
radius =
2.5000
>> A = pi*radius^2 Use the arithmetic operation:
• Exponentiation ^
A= Assign the values of an expression pi*radius^2 to a variable A
MATLAB knows the constant value 𝜋
19.6350 ( try: >> pi )
21
Basic arithmetic operations in MATLAB
>> clear A Clear the variable A in the memory
>> A Now MATLAB does not know what A is
Unrecognized function or variable 'A’. ← Giving an error message
(You will get familiar with it very soon!)
>> a = 3; Assign the value 3 to a
>> b = a; Assign the value a (i.e., 3) to b
>> a = 2; Assign the value 2 to a
>> a
a= (note: changing the value of a will NOT change the value of b)
2.0000
>> b
b=
3.0000 22
Basic arithmetic operations in MATLAB
>> pi The default value of pi
pi =
3.1416
>> pi = 3; (Caution) If you assign a value to some special variables (e.g. pi),
>> pi it will replace the default value of the variables
pi =
3.0000
>> pi*radius^2 Now the answer is different from the previous one. Hard to debug!
ans = Be mindful when choosing what variables to use.
18.7500
>> clear pi Clear the variable pi in the memory.
>> pi The default value of pi will be restored.
pi =
3.1416 23
Variable naming rule in MATLAB
A valid variable name starts with a letter, followed by letters, digits, or underscores:
• a ✓
• b ✓
• AbC12 ✓
• Edge_length_1 ✓
• aa, aaa, aaaa … ✓ (but not recommended, hard to understand)
• pi ✓ (but not recommended, will replace the default value of pi)
• 12a ✗
Case sensitive
• A and a are treated as different variables
See https://www.mathworks.com/help/matlab/matlab_prog/variable-names.html
24
Matrix operations in MATLAB
>> v = [1 3 -1] Define a row vector (using space to separate the entries)
v=
1 3 -1
>> w = [2, 3, 4, 6] One can also use comma “,” or space “ ” to separate the entries
w=
2 3 4 6
>> u = [1; 3; 5] For column vector, use semicolon “;” to separate them
u=
1
3
5
>> u(2) Extract the second entry in the vector
ans =
3 25
Matrix operations in MATLAB
>> A = [1, 2, 3; 4, 5, 6] Define a matrix
A= • Use comma “,” or space “ ” to separate the entries for each row
1 2 3 • Use semicolon to separate the rows
4 5 6
>> A(2,1) Extract the entry in the 2nd row and 1st column of A
ans =
4
>> c = A(2,3); One can also store the extracted entry as a new variable
>> c
c=
6
26
Matrix operations in MATLAB
>> M = [1, 2, 3; 4, 5, 6];
>> u = [1; 3; 5];
>> v = [1 3 -1];
>> M+1.5 Adding a scalar value to all entries of M
ans =
2.5000 3.5000 4.5000
5.5000 6.5000 7.5000
>> 3*v Scalar multiplication of v
ans =
3 9 -3
27
Matrix operations in MATLAB
>> M = [1, 2, 3; 4, 5, 6];
>> u = [1; 3; 5];
>> v = [1 3 -1];
>> M*u Matrix multiplication
ans =
22
49
>> M*v Matrix multiplication with incompatible dimension
Error using * Getting an error message!
Incorrect dimensions for matrix multiplication. Check that the number of columns
in the first matrix matches the number of rows in the second matrix. To perform
elementwise multiplication, use '.*'.
Related documentation 28
Matrix operations in MATLAB
>> A = [1, 2, 3; 4, 5, 6];
>> v = [1 3 -1];
>> transpose(v) Transpose of v
ans =
1
3
-1
>> v’ Alternative method (use apostrophe “ ’ ”)
ans =
1
3
-1
>> A*v’ Matrix multiplication with compatible dimension
ans =
4
13 29
Matrix operations in MATLAB
>> M = [1, 2, 3; 4, 5, 6];
>> v = [1 3 -1];
>> [M; v] Forming a new matrix consisting of M followed by v in a new row
ans =
1 2 3
4 5 6
1 3 -1
>> [M(2,2), v] Forming a new matrix consisting of the entry in M(2,2) followed
ans = by v in the same row
5 1 3 -1
>> [M, v] Incompatible dimension, getting an error message
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
30
Commands for creating vectors efficiently
>> 1:5 Use colon “m:n” (where n > m) to create a row vector with
ans = consecutive entries from m to n
1 2 3 4 5
>> 3:0.2:4 Use colon “m:s:n” to create a row vector with entries from m to n
ans = with an increment of s
3.0000 3.2000 3.4000 3.6000 3.8000 4.0000
>> a = 5:-1:-3 Negative increment can also be used
a=
5 4 3 2 1 0 -1 -2 -3
>> 0:pi:10 Values outside the interval will not be included
ans =
0 3.1416 6.2832 9.4248
31
Commands for creating matrices efficiently
>> M = zeros(2,4) Creating a zero matrix with 2 rows and 4 columns
M=
0 0 0 0
0 0 0 0
>> A = ones(3,2) Forming a matrix with 3 rows and 2 columns, with all values = 1
A=
1 1
1 1
1 1
>> B = ones(2) Will assume the matrix is a square matrix if only one input is given
B=
1 1
1 1
32
Learning resources
The best way to learn MATLAB is by using it!
• Type demo in the command window to access the MATLAB Help Center
(search and look for certain functions and examples)
• Type help xxx (where xxx is the function you want to know more about)
to read the documentation
Lecture Notes
MATLAB Academy: https://matlabacademy.mathworks.com/
MATLAB Central: https://www.mathworks.com/matlabcentral/
33
Thank you!
Next time:
• More basic functions
• Writing MATLAB scripts
34