Chap1 Matlab
Chap1 Matlab
Chap1 Matlab
i
ii UNSW Sydney, Australia, MATH2301, T1 2024
Chapter 1
1.1 Introduction
In this course, we will use Matlab to carry out all of the programming exercises. Mat-
lab is a software package designed for numerical computation and visualisation. The
symbolic toolbox can do symbolic algebra as well. MATLAB = MATrix LABorartory.
As the name suggests, the building blocks of Matlab are matrices.
Matlab is provides an interactive environment. In a default setup, there are four
main windows: Command Window, Current Directory, Workspace, and Command
History.
• Command Window: This is the main window where all commands including
those for running user-written programs are typed in. The MATLAB command
prompt is >>. E.g.
• Current Directory: This is where all your files from the current directory are
listed. To change directories, click on the menu bar or in the Command Window:
>> cd directory_name
• Workspace: This window lists all variables you have generated in this session,
together with their type and size. Double click on a variable in this window to
view its value. Right click for other options.
1
2 UNSW Sydney, Australia, MATH2301, T1 2024
• Command History: This window records all commands typed in the Command
Window. Double click on a command to execute it again. You can also use the
up-arrow on the keyboard.
>> demo
There is a reserved word list. To check if a variable name var has been used or is in
the reserved list, type in the following command
>> exist(’var’)
The following table lists some special variables: If you assign a new value to one
of the special variables above, its prior value is overwritten and lost.
To clear a variable from the memory, you type in
Matlab 3
• Mat-files: binary data files with a .mat extension to the file name.
Example 1.1.1 Write a MATLAB script, named area.m, to compute the areas of
the circles of radii π 1/3 and π 2/3 . On running the script should print out the following
line (with no other outputs on the screen)
Radius Area
. . . . . .
4 UNSW Sydney, Australia, MATH2301, T1 2024
. . . . . .
For reading and writing formatted binary and text files, the following commands
should suffice fopen, fprintf, fscanf, and fclose.
One of the following commands opens a file named MyFile.
% Open file named MyFile for read access.
% File must exist before command is executed
>> fid = fopen(’MyFile’);
% or
>> fid = fopen(’MyFile’,’r’);
% Open or create file for writing,
% existing contents overwritten
Matlab 5
>> x = [1:10];
>> y = sqrt(x);
>> fid = fopen(’square_root’,’w’);
>> fprintf(fid,’ Square Root\n ’);
>> fprintf(fid,’\n’);
>> fprintf(fid,’ %3i %8.2f\n’,[x;y]);
>> fclose(fid);
To read and write binary data to a file, use fread and fwrite.
>> v1 = [ 1 2, 3 4 ]
v1 =
1 2 3 4
>> v2 = [ 3 ; 4
6 ]
v2 =
3
4
6
>> v1(3), v2(2)
ans =
3
ans =
4
6 UNSW Sydney, Australia, MATH2301, T1 2024
Row and column vectors are one-dimensional arrays. Matrices are two-dimensional
arrays. It is not necessary to declare the dimension of a matrix.
>> A = [ 1 2 3
4 5 6 ]
A =
1 2 3
4 5 6
>> B = [ 3 7 9 ; 2 6 4 ]
B =
3 7 9
2 6 4
If it is not possible to type the entire input on the same line, use an ellipsis (three
dots) and continue the input on the next line.
>> A = [ 4 7 9 7 ...
8 9 ]
A =
4 7 9 7 8 9
The size command gives the number of rows and columns of an array. The length
command gives the maximum value of these two numbers.
>> A = [1 8 0 3 ; 2 4 9 6 ; 0 3 7 9];
>> size(A)
ans =
3 4
>> length(A)
ans =
4
>> [m n] = size(A) % assign these values to variables
% m and n for later access
m =
3
n =
4
>> size(A,1)
ans =
3
>> size(A,2)
ans =
4
Matlab 7
>> a = [2 3 4 5 9];
>> size(a)
ans =
1 5
>> length(a)
ans =
5
>> B = [] % empty array
B =
[]
>> size(B)
ans =
0 0
>> a(3)
ans =
4
>> a(2) = 0
>> a
a =
2 0 4 5 9
>> A(2,3), A(5)
ans =
9
ans =
4
>> A(3,1) = 8
A =
1 8 0 3
2 4 9 6
8 3 7 9
Notes:
>> c = [1 3 4];
>> x = A\c
??? Error using ==> mldivide
Matrix dimensions must agree.
>> x = A\c’
x =
-0.1500
-0.0833
0.6056
Given a scalar a (real or complex) and two matrices A and B. The following opera-
tions are available under some appropriate conditions.
3 5 7 9
>> v = [3:2:8]
v =
3 5 7 % final value does not exceed 8
>> v = [8:-2:3] % negative increment
v =
8 6 4 % final value does not go below 3
>> v = [5:2]
v =
Empty matrix: 1-by-0
>> v = 2:-1:3
v =
Empty matrix: 1-by-0
The command linspace(a,b,n) generates a vector of n linearly equally spaced
points between (and including) a and b. If n is not specified, i.e. linspace(a,b), the
default value is n = 100.
Example 1.2.2 Generate a vector of 5 equally spaced points between and including
1 and 10.
>> linspace(1,10,5)
ans =
1.0000 3.2500 5.5000 7.7500 10.0000
This is the same as
>> [1:(10-1)/(5-1):10] % [a:(b-a)/(n-1):b]
ans =
1.0000 3.2500 5.5000 7.7500 10.0000
If a is a scalar, and A and B are two arrays of the same size, then the element-
by-element operations give the following arrays:
Operation Meaning
C = a./A Cij = a/Aij
C = A.\a Cij = a/Aij
C = A.ˆa Cij = Aaij
C = a.ˆA Cij = aAij
C = A. ∗ B Cij = Aij Bij
C = A./B Cij = Aij /Bij
C = A.\B Cij = Bij /Aij
B
C = A.ˆB Cij = Aijij
10 UNSW Sydney, Australia, MATH2301, T1 2024
>> v = 1:5
v =
1 2 3 4 5
>> 2.^v
ans =
2 4 8 16 32
>> v.^2
ans =
1 4 9 16 25
>> v^2
??? Error using ==> mpower
Matrix must be square.
To access parts of a matrix, consider the following commands:
>> A = [2 5 -1 7 ; 8 0 6 3 ; 9 8 -2 1 ; 3 7 9 2]
A =
2 5 -1 7
8 0 6 3
9 8 -2 1
3 7 9 2
>> B = A(2:4,3:4)
B =
6 3
-2 1
9 2
>> C = A(1:2:4,:)
C =
2 5 -1 7
9 8 -2 1
>> A(2:4,3:4) = 0
A =
2 5 -1 7
8 0 0 0
9 8 0 0
3 7 0 0
>> A(1:2:end,1) = -1
A =
-1 5 -1 7
8 0 0 0
-1 8 0 0
3 7 0 0
Using an array to refer to part of a matrix:
Matlab 11
>> j = [1 3 4];
>> A(3,j)
ans =
-1 0 0
Zeros (or ones) arrays are arrays that contains all zeros (or all ones).
>> zeros(3)
ans =
0 0 0
0 0 0
0 0 0
>> zeros(2,3)
ans =
0 0 0
0 0 0
>> A = [1 2 5 7 ; 2 4 8 1];
>> zeros(size(A))
ans =
0 0 0 0
0 0 0 0
>> eye(2)
ans =
1 0
12 UNSW Sydney, Australia, MATH2301, T1 2024
0 1
>> eye(3,2)
ans =
1 0
0 1
0 0
>> eye(2,3)
ans =
1 0 0
0 1 0
>> A = [1 2 5 7 ; 2 4 8 1];
>> B = eye(size(A))
B =
1 0 0 0
0 1 0 0
We can access diagonals of a matrix by the diag command. If A is a matrix then
diag(A,k), where k is an integer, produces a column vector whose components are
entries on the kth diagonal of A.
>> A = [1 3 5 ; 2 4 6]; v1 = diag(A), v2 = diag(A,1), ...
v3 = diag(A,2), v4 = diag(A,3), v5 = diag(A,-1)
v1 =
1
4
v2 =
3
6
v3 =
5
v4 =
Empty matrix: 0-by-1
v5 =
2
The same command can be use to create diagonal matrices. If v is a vector, then
diag(v,k) creates a square matrix of appropriate size whose kth diagonal is v.
>> v = [1:3]; v1 = diag(v), v2 = diag(v,1), v3 = diag(v,-2)
v1 =
1 0 0
0 2 0
0 0 3
v2 =
Matlab 13
0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0
v3 =
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
Sparse matrices are matrices which contain a lot of zeros.
>> A = [0 0 1 0 0 ; -2 0 3 0 0 ; 0 0 -5 0 0]
A =
0 0 1 0 0
-2 0 3 0 0
0 0 -5 0 0
>> nnz(A) % number of non-zero entries of A
ans =
4
>> B = sparse(A)
B =
(2,1) -2
(1,3) 1
(2,3) 3
(3,3) -5
The command full(B) reproduces a matrix identical to A. Arithmetic and index-
ing operations can be applied to sparse matrices or to a mixture of sparse and full
matrices.
For more infomation on how sparse matrices are stored, read J.R. Gilbert, C. Moler,
and R. Schreiber, Sparse matrices in MATLAB: Design and implementation. http:
//www.mathworks.com/help/pdf_doc/otherdocs/simax.pdf.
Example 1.2.3 A sparse matrix B of size 4 × 4 with nonzeros entries B(2, 1) = −2,
B(1, 2) = 1, B(4, 2) = 1, B(2, 3) = 3, B(3, 3) = −5, B(4, 4) = 1 can be created as
follows:
ans =
2 -1 0 0 0
-1 2 -1 0 0
0 -1 2 -1 0
0 0 -1 2 -1
0 0 0 -1 2
The curly braces indicate that the expression respresents a cell rather than, e.g., a
numerical value. We can preallocate a variable as a cell array, using the command
cell.
>> B = cell(2,2)
B =
[] []
[] []
>> B{1,1} = ones(1,3); B{1,2} = rand(1,2);
>> B{2,1} = ’MATLAB’; B{2,2} = A
B =
[1x3 double] [1x2 double]
’MATLAB’ {1x4 cell }
>> A{1,2}
ans =
MATH2301
>> B{2,2}
ans =
[2x2 double] ’MATH2301’ [1.0000 + 2.0000i] [1]
>> B{2,2}{2}
ans =
MATH2301
>> B{2,2}{1}
ans =
1 2
3 4
>> B{2,2}{1}(2,2)
ans =
4
A structure is a collection of objects labelled by field names. E.g.:
>> s = struct(’name’, ’harry’, ’age’, 45)
s =
name: ’harry’
age: 45
>> whos s
Name Size Bytes Class
s 1x1 266 struct array
Grand total is 8 elements using 266 bytes
>> s.name, s.age
ans =
harry
ans =
45
>> fieldnames(s)
ans =
’name’
’age’
We can also form array of structures:
>> t = struct(’name’, {’harry’, ’sue’, ’john’}, ...
’age’, {46, 37, 29})
t =
1x3 struct array with fields:
name
Matlab 19
age
>> t(2).name
ans =
sue
>> t.age
ans =
46
ans =
37
ans =
29
>> disp([t.age])
46 37 29
• Relational operators.
• Logical operators.
>> whos x A B
Name Size Bytes Class
A 2x2 4 logical array
B 2x3 6 logical array
x 1x2 2 logical array
Grand total is 12 elements using 12 bytes
The use of logical function is listed below.
>> a = 1;
>> b = logical(a); % convert a numeric value to logical
>> whos a b
Name Size Bytes Class
a 1x1 8 double array
b 1x1 1 logical array
Grand total is 2 elements using 9 bytes
>> A = [1 2 0 ; -4 0 3 ];
>> B = logical(A)
Warning: Values other than 0 or 1 converted to logical 1.
B =
1 1 0
1 0 1
>> whos A B
Name Size Bytes Class
A 2x3 48 double array
B 2x3 6 logical array
Grand total is 12 elements using 54 bytes
The following table list the relational operators supported by MATLAB.
Operator Description
== equal
e= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal
>> 3 > 4
ans =
0 % 0 when relation is false
>> s = 2 < 3 % assign the answer to variable s.
s =
Matlab 21
1 0 1
1 1 1
E =
0 1 0
0 1 0
>> u = [2 0 1];
>> v1 = any(u)
v1 =
1
>> v2 = all(B) % v2 = [all(B(:,1)) all(B(:,2)) all(B(:,3))]
v2 =
0 0 0
>> x = [5 2 8 4 9 0 -1];
>> v = x < 5 & x >= 0
v =
0 1 0 1 0 1 0
>> x(v)
ans =
2 4 0
>> x(v) = 5 % same as x(x<5&x>=0) = 5
Matlab 23
x =
5 5 8 5 9 5 -1
>> v = [0 1 0 1 0 1 0];
>> x(v)
??? Subscript indices must either be real positive
integers or logicals.
>> A = [2 0 3 ; 5 0 1]; B = [0 0 -3 ; 1 3 0];
>> A(A&B) = inf
A =
2 0 Inf
Inf 0 1
>> A = magic(3), A(~isprime(A)) = 0
A =
8 1 6
3 5 7
4 9 2
A =
0 0 0
3 5 7
0 0 2
Zero or more than one elseif branch is permitted. The else branch can also be omitted.
Example 1.4.2 Let x be given. For each element of x, if it is nonpositve then negate
it, otherwise just square it.
24 UNSW Sydney, Australia, MATH2301, T1 2024
1.5 Functions
1.5.1 Built-in functions
MATLAB has numerous built-in functions. Use the command help elfun to see
availabe elementary mathematical functions. Scalar functions naturally take scalar
arguments; but will also act on matrices elementwise.
26 UNSW Sydney, Australia, MATH2301, T1 2024
-5.0846
0.2172
>> B = [1 3 5 ; 2 4 6 ; 9 2 1 ; 4 8 2];
>> reshape(B,2,6)
ans =
1 9 3 2 5 1
2 4 4 8 6 2
function y = piecefunc(x)
% EXAMPLE of a piecewise-defined function
%
% (x+2)^2/4 for -2 <= x < 0,
% y = (3-x)/3 for 0 <= x < 3,
% 0 otherwise
y= zeros(size(x)); % preallocate y
i1 = find(-2 <= x & x < 0)
i2 = find( 0 <= x & x < 3)
y(i1) = (x(i1)+2).^2/4;
y(i2) = (3-x(i2))/3;
Example 1.5.3 Write a function file to define the probability density function
−(x − µ)2
1
f (x) = √ exp .
2πσ 2σ 2
The following script file will illustrate the use of normal dist.
x = linspace(-4,4);
y1 = normal_dist(x);
y2 = normal_dist(x,1,0.5);
plot(x,y1,x,y2)
legend(’standard normal’,’mu=1, sigma=0.5’)
trapz(x,y1) % trapezoidal rule to evaluate integral
trapz(x,y2) % type "help trapz" to learn more
funhandle = @filename.
Some MATLAB built-in functions (e.g. fzero and feval) or user-defined func-
tions have as input another function. The function handle is used to pass on this
input.
With the function sqr defined above we have
For functions defined in function M-files like piecefunc in Example 1.5.2, there are
several ways to pass it on as an input of another function.
30 UNSW Sydney, Australia, MATH2301, T1 2024
1.6 Graphics
1.6.1 2-D graphics
Example 1.6.1 Plot y = exp(x) for 0 ≤ x ≤ 3 using the plot command.
Example 1.6.2 Plot the Bessel functions of order zero, one, and two on [0, 10].
(Bessel functions of order µ are solutions of the ODE x2 y ′′ + xy ′ + (x2 − µ2 )y = 0.
Type help besselj to get more info.)
Another way to plot multiple graphs in one figure window is to use hold on:
>> x = linspace(0,2); y1 = x.^2; y2 = sin(x);
>> plot(x,y1)
>> hold on
>> plot(x,y2)
>> hold off
To save a figure: use print
>> print -dps filename % save as .ps file
>> print -deps filename % save as .eps file
>> print -depsc filename % save as .eps file (colour)
>> print -djpeg filename % save as .jpeg file
Note: MATLAB 2014b seems to have some problems with exporting Greek sym-
bols to eps files. The quick fix is to use the following commands (taking the previous
plot as an example)
>> title(’Bessel function $B_\mu$’,’interpreter’,’latex’);
>> print -depsc2 filename
Example 1.6.3 Plot sin(x) and cos(x) in one figure for a ≤ x ≤ b, where a and b
are input parameters.
The error built-in function displays the message, exits the M-file, and returns
control to the keyboard.
PN
Example 1.6.4 Plot the Riemann zeta function ζ = n=1 n−s for s ∈ [a, b] and
a > 1.
In the previous example, we have used the repmat command. The actions of the
command can be seen in the following code
5 5 5
>> mat2 = -repmat(s,length(n),1)
mat2 =
-2 -3 -4
-2 -3 -4
-2 -3 -4
-2 -3 -4
-2 -3 -4
>> t = linspace(-pi,pi);
>> plot(cos(t),sin(3*t))
>> xlabel(’x(t)’) % x-axis label
>> ylabel(’y(t)’) % y-axis label
>> title(’Parametric curve (cos(t),sin(3t))’)
Sometimes, we need to put many plots in the same figure. The command subplot
will help us to achieve this. The figure window can be divided into rectangular panes
that are numbered rowwise. Plots are then output to each pane.
x = linspace(0,pi);
y1 = sin(x);
y2 = x.^2 ./ (1+x.^3); % note the dots
subplot(1,2,1) % divide the graphic window into 2 panes,
% 1 row and 2 columns, and get the figure
% in the first pane
plot(x,y1) % plot in the first pane
subplot(1,2,2) % get the figure in the 2nd pane
plot(x,y2) % plot in the second pane
Example 1.6.5 Plot the circular helix x = cos t, y = sin t, z = t for t ∈ [0, 7π].
>> t=linspace(0,7*pi,1000);
>> plot3(cos(t),sin(t),t);
>> axis on
>> grid on
To plot a surface in R3 , firstly we need to create a grid via the meshgrid command.
>> x = -2:2; % create the vector x = [-2 -1 0 1 2]
>> y = -1:1; % create the vector y = [-1 0 1]
>> [X,Y] = meshgrid(x,y) % create a grid of 15 points
% their x-coordinates are stored in X
% their y-coordinates are stored in Y
X =
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
Matlab 35
Y =
-1 -1 -1 -1 -1
0 0 0 0 0
1 1 1 1 1
In general X, Y are matrices of size n × m where m and n are the lengths of x and y,
resp, and X(i, j) = x(j), Y (i, j) = y(i).
In the following example, we will plot surfaces in 3D using mesh and surf com-
mands.
1.7 Efficiency
Performance of your MATLAB code can be improved by vectorising loops and preal-
locating arrays.
t0 = cputime;
i = 0;
for t = 0:.01:1000
i = i + 1;
y(i) = sin(t);
end
t1 = cputime;
loop_time = t1-t0
t0 = cputime;
t = 0:.01:1000;
y = sin(t);
t1 = cputime;
vec_time = t1-t0
% Without preallocation
clear x
for j=1:n
for i=1:n
x(i,j)=(i+j)/n;
end
end
% With preallocation
clear x
x=zeros(n,n); % preallocate x
for j=1:n
for i=1:n
x(i,j)=(i+j)/n;
end
end