Beruflich Dokumente
Kultur Dokumente
Advanced Engineering
Mathematics
Background Material
Clayton Campus
Malaysia Campus
Semester 1 and 2, 2017
ENG2005
Advanced Engineering Mathematics
Module 1 - A Brief Matlab Primer
1. Purpose
The purpose of this introductory primer is to refresh your memory regarding some of
the functionality of Matlab which you will need in the later modules. Because you have
completed ENG1060 we will assume that you are already aware of the very basics of
Matlab, such as how to use the terminal, create scripts and implement some of the basic
Matlab syntax. We will briefly discuss some of the key syntax and then you will be
asked to perform some simple tasks to make use of the concepts.
In particular we encourage you to make liberal use of the Matlab help system
throughout your work on these numerical modules. The useful information, including
syntax and examples for every Matlab command can be accessed by typing
in the Matlab terminal (where "function name" is the name of the Matlab function you
are enquiring about). For instance if you type ‘help size’ in the terminal you will receive
information regarding the use of the ‘size’ function.
2. A Matlab Refresher
2.1 Variables
When performing calculations in a Matlab script (or in the terminal), we will usually
store data in variables. Variables in Matlab are created via assignment statements,
such as,
x = 4.8;
y = 7;
z = x + y;
These commands define the three variables x, y and z and assign them values based on
the statements on the right-hand side of the = sign. Remember that in a language like
Matlab, the = sign does not strictly mean the same thing that it does in mathematics.
It is in fact an assignment symbol, assigning the value on the right-hand side to the
symbol on the left-hand side.
At any particular time after you have defined variables in a script or in the terminal
you can use the ‘whos’ command to get a list of all of the variables that are currently
defined. The command will also tell you the dimension of the variables (scalar or array)
School of Mathematical Sciences Monash University
and the amount of memory used to store those variables (Give it a try!)
The semicolon is added to the end of an assignment statement in order to suppress
the automatic displaying (printing to terminal) of that variable. Making the above
assignment statements in the terminal with and without the semicolon should make the
difference clear to you.
creates a row vector called y, which has length 3. In addition, any array may be trans-
posed with the ’ symbol. Therefore,
x = [6 2 3]’;
yields the column vector x. You can check that one is a row vector and the other a
column vector by once again using the ‘whos’ command. We can access the individual
components of an array using normal brackets, i.e. typing x(1) will return the first entry
of the column vector x, which has a value of 6. Similarly we can access a limited range
of the values of an array. Typing
a = x(1:2);
for instance, will create a column vector a, of length 2, containing the first two elements
of x.
4 + [6 2 3] = [10 6 7].
2 ∗ [6 2 3] = [12 4 6],
Two vectors may only interact if they have the same dimension and orientation however.
For instance, the operation,
x+y
does not make sense as y is a row vector (of size 1 × 3) and x is a column vector (of size
3 × 1). If you attempt this calculation in Matlab you will encounter something like the
following error (Try it!):
Error using +
Matrix dimensions must agree.
x’ + y = [12 4 6]
12
(or alternatively x + y’ = 4 ) is the result of the addition of the two similarly oriented
6
row vectors. Element-by-element multiplication and division works similarly, except that
you must remember to use the ‘dot multiply’ (.∗) or the ‘dot divide (./) rather than the
standard multiplication or division operator. Thus the correct way to multiply the cor-
responding elements of x’ and y would be,
x’ .∗ y,
[36 4 9].
The first element of x’ has been multiplied by the first element of y, and similarly for the
second and third elements. This product is known as the Hadamard or Schur product
and is extremely useful when coding. Matlab instead treats the normal multiplication ∗
as a proper matrix multiplication. Thus if you compute y ∗ x, Matlab will calculate the
product of a row vector with a column vector, which is the standard dot product, while
x ∗ y will result in a 3 × 3 matrix:
y ∗ x = 49
36 12 18
x ∗ y = 12
4 6
18 6 9
It is worth noting that some calculations will require successive multiplications and/or
divisions of vectors and you must remember to include the dot in all operations. For
instance if you have 3 vectors (or matrices) x, y and z, the element-wise calculation xy/z
would be written as:
x .∗ y ./ z
So remember the dot unless you are specifically performing linear algebra operations!
a = [1 2 3; 4 5 6; 7 8 9],
A = -6.5∗ones(3,3),
M = 2∗eye(5,5)
Does the result make sense to you? If not, use the help function!
Another very useful function is ‘diags’. This allows you to create matrices by choos-
ing the value of the various diagonals based on vectors. For instance if you define a vector,
such as c = [1 2 3 4], then you can create a square matrix N, with c as the main diagonal
and 0’s elsewhere with the command,
N = diag(c,0)
where c specifies the vector to be used and the integer 0 indicates that the vector is to
be placed on the main diagonal. You can place vectors on the off-diagonals by changing
the value of the integer 0 to a 1 or -1. Does this change the dimension of the matrix?
(Check it!)
If you are peforming calculations involving arrays it is very useful to regularly use
the ‘size’ command to ensure that the dimensions of your arrays are as you expect them
to be (alternatively you can once again use the ‘whos’ command which will give you the
sizes of all of your variables.
As always just type these function and command names into the Matlab help system
if you are unsure about their usage.
%%%%%%%%%
x = 5;
if (x > 10)
y = 10;
elseif (x < 0)
y = 0;
else;
y = x;
end
%%%%%%%%%
will result in y = x when 0 < x < 10, y = 10 when x > 10, and y = 0 when y < 0 (check
it by changing the assigned value of x on the first row). As an aside, the % symbols are
the standard commenting symbol in Matlab. Any code which you enter on the same line
as a % symbol will be ignored. We use them here just to designate the beginning and
the end of the code fragments. Note that you can also use ‘block commenting’ of the form
%{
Code to be commented out
%}
in order to comment out large sections of code, rather than putting a % symbol at the
beginning of every line.
Another common control flow construct is the for loop. The for loop is simply an
iteration loop that tells the computer to repeat some task a given number of times. The
%%%%%%%%%
for i = 1:3
i
end
%%%%%%%%%
Because we have left the semicolon off the i inside the loop, Matlab will simply print
out the value of i to the terminal every time the loop iterates. You could also define the
entries in a matrix using a for loop. For instance:
%%%%%%%%%
A=zeros(5,5);
for i = 1:5
for j = 1:5
A(i,j) = i + j;
end
end
%%%%%%%%%
iterates the values of i and j from 1 to 5 and each time assigns the value of i + j to row
i, column j of A, resulting in:
2 3 4
A = 3 4 5 .
4 5 6
dx = 2*pi/100; dy =4*pi/100;
x = [0:dx:2*pi]; %% x-axis range from 0 to 2 pi.
y = [0:dy:4*pi]; %% y-axis range from 0 to 4 pi.
[X, Y] = meshgrid(x, y); %% Create the 2D 100 × 100 array.
contour(x,y,sin(X).*sin(Y)); %% Create contour plot of the 2D function.
xlabel(‘X’);
ylabel(‘Y’);
Alternatively you could define the x and y arrays above using the ‘linspace’ function. Of
course there are many alternatives to the ‘contour’ function, such as ‘contourf’, ‘surf’,
‘meshc’, ‘surfc’ among others which all display different representations of 2D data. The
usage of these functions is all described in the Matlab help system.
function may be written inside a normal script or saved separately as its own m file, but
either way you must also include an ‘end’ statement at the end of the function. As an
example, say we wish to compute the facotrial of a given number, m. Matlab already
has a built-in function ‘factorial’ but lets ignore that for the moment and create our own:
%%%%%%%%%%%
function a = facc(m)
% This program computes the factorial of a given number.
a = 1;
for i = 1:m
a = a*i;
end
end
%%%%%%%%%%%
If you save this as ‘facc.m’ in your working directory you can then call this function
(i.e. ‘facc(10)’) from either the terminal or inside some other script and it will return
the output – the factorial of the number that you supplied. Note that it is very
important that the file name and the function name match and do not conflict
with any pre-existing Matlab functions.
Note that separate functions each have their own variable workspace. A function
file will only know about the variables that are explicitly passed into it via the input.
They will not have any knowledge of any pre-existing variables outside of this in the
main script which havent been passed to it.
%%%%%%%%%%%
function B = limit0_10(A)
if (A > 10);
B = 10;
elseif (A < 0)
B = 0;
else
B = A;
end
end
%%%%%%%%%%%
It takes a variable A, and returns it unchanged if A ≤ 10. If A > 10 then the output
is limited to the value of 10. If A is negative then the output value is set to 0. As it
stands the function will only work with a scalar variable as input. We can extend the
function so that it will work on an array input as well by using the inbuilt ‘find’ function:
%%%%%%%%%%%
function B = limit0_10(A)
B = A;
i = find(A > 10);
B(i) = 10;
i = find(A < 0);
B(i) = 0;
end
%%%%%%%%%%%
x = [4 -1.5 0 17],
and then call the function as normal. Now the output will also be an array. The function
has operated on the input array in an element-wise manner. In general you can have as
many input and output variables as you wish. The form of the top line with multiple
inputs and outputs would then be,
in generality.
In Closing...
Well that about wraps up our Matlab summary! Have a go of the problem set associated
with this Module!
it is also worth reminding you that, as with any programming language, Google
is your best friend! Any problem that you are encountering has most likely been en-
countered by someone else somewhere online. If you really need additional help the
demonstrators in your assigned lab class will be able to assist you. Good luck!