Sie sind auf Seite 1von 10

ENG2005

Advanced Engineering
Mathematics

Computational Module 1 - Matlab Primer

Background Material

Clayton Campus
Malaysia Campus
Semester 1 and 2, 2017

Australia Malaysia South Africa Italy India monash.edu/science


SCHOOL OF MATHEMATICAL SCIENCES

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

help "function name"

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.

2.2 One-Dimensional Arrays


Arrays can be defined in a similar manner to variables. Instead of the array name
containing a single value however, an array can be a list of numbers (integers or real/-
complex numbers) or even characters (known as ‘strings’). You can think of a 1D array
containing n elements as being analogous to an n-dimensional vector. We can create a
row vector using the [ ] brackets. For example, typing

y = [6 2 3]; (or equivalently y = [6, 2, 3];)

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.

2.3 Array Arithmetic


In Matlab, if we add (subtract) a constant to (from) an array, the operation will be
performed to every element of that array. Thus,

4 + [6 2 3] = [10 6 7].

The same principle applies for multiplication and division by scalars:

2 ∗ [6 2 3] = [12 4 6],

and even when operating on vectors with functions; for instance:

exp(y) = [403.4288 7.3891 20.0855].

Tuesday 14th February, 2017 3


School of Mathematical Sciences Monash University

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.

To correctly perform this element-by-element addition, we would need to transpose one


of the vectors:

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,

which would result in the row vector,

[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

Tuesday 14th February, 2017 4


School of Mathematical Sciences Monash University

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!

2.4 Two-Dimensional Arrays


Matlab can also deal easily with two (and even greater) dimensional arrays, which are
referred to as tables in some contexts. Many of the same rules from one dimensional
arrays are directly extended. To create a simple array with 3 rows and 3 columns (equiv-
alent to a 3 × 3 matrix), you can simply enter,

a = [1 2 3; 4 5 6; 7 8 9],

which will give you the matrix,


 
1 2 3
4 5 6.
7 8 9
Spaces indicate a change in column and semicolons a change in row. To access any
particular element of this array simply use the notation a(1,3) to access the first row,
third column. To extract an entire column you can use the notation a(:, 2), which
means all entries in the second column. A column vector would be returned in this case.
Similarly a(3, :) would return the row vector of elements in the 3rd row.
There are also a variety of inbuilt functions that enable you to create matrices with
specific structures much more easily than simply defining all of the entries manually, as
above. For instance you can create a matrix (two-dimensional array) of a given dimen-
sion with the ‘zeros’ or ‘ones’ functions and then modify the entries as you desire. For
example,

A = -6.5∗ones(3,3),

creates a 3 × 3 matrix with all entries equal to -6.5.


With equal ease, you can easily create an identity matrix with the ‘eye’ function.
The assignment statement M = eye(m,n) will create an m × n identity matrix called M.
Try opening up the Matlab terminal and inputting the command,

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,

Tuesday 14th February, 2017 5


School of Mathematical Sciences Monash University

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.

2.5 Control flow


There are a variety of commands that allow us to control the flow of commands inside
a program. A common structure is the if-elseif-else structure. With these commands
we can execute different actions depending on whether certain conditions are met. For
example, the program,

%%%%%%%%%
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

Tuesday 14th February, 2017 6


School of Mathematical Sciences Monash University

format of the simplest possible for loop might be something like:

%%%%%%%%%
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

2.6 Data Visualisation


In this section we will briefly refresh you on some of the basics of plotting data. To
plot data you need to create one or two dimensional arrays as explained above – one (or
more) array(s) to act as the independent variable(s) and another to act on those arrays
as the function. A simple example is to create a list of known points and evaluate a
function at these sample points and plot the result. You will no doubt recall the basic
syntax ‘plot(x, y)’ which generates a plot of y on an x axis. The arrays x and y should
be the same length and orientation and should be one-dimensional.
The appearance of plots can be manipulated via simple commands and you can add
additional plots, labels, legends etc. as shown in the example overpage:

Tuesday 14th February, 2017 7


School of Mathematical Sciences Monash University

t = linspace(0, 1, 200); %% Create 200 points from 0 to 1.


clf; %% Clears the current figure.
plot(t, t .∗exp(-t)); %% Plot the function.
hold on; %% Holds for subsequent plots.
plot(t, t .∗exp(-3∗t), ‘r- -’); %% Plots with a red dashed line.
plot(t, t .∗exp(-5∗t), ‘k_.’); %% Plots with a black dash-dot line.
axis([0 1 0 1]); %% Sets axis limits between 0 and 1.
xlabel(‘t’); %% x axis label.
legend(‘t exp(-t)’,‘t exp(-3 t)’,‘t exp-5 t)’); %% Adds a legend.

Embedding commands in your programs to change the appearance of plots is most


important when the task is repetitive and you may want to generate many plots that all
look the same.
The two-dimensional analogue to the ‘linspace’ command is ‘meshgrid’. This com-
mand transforms the 1D vectors in its argument into a 2D array that can be used for
evaluating 2D functions. An example of the use of this function is provided below:

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.

2.7 Matlab Functions


You are already no doubt familiar with a variety of the inbuilt Matlab functions, such
as ‘sin’, ‘plot’ and ‘linspace’. When you use these functions on a specified input Matlab
looks up the associated function program with that name and runs it, returning the
output.
You are of course free to define your own functions which behave in the same way
as the inbuilt Matlab functions. For instance, if you are performing similar calculations
multiple times throughout a large script, it might be more efficient to set up a function
which can be repeatedly called rather than repeating the calculation again and again in
the main script.

Defining your own functions


The first line of a function must begin with the ‘function’ keyword. You then specify
the output variable, the name of the function and then the various input variables. A

Tuesday 14th February, 2017 8


School of Mathematical Sciences Monash University

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.

To continue, consider the following simple function:

%%%%%%%%%%%
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

Tuesday 14th February, 2017 9


School of Mathematical Sciences Monash University

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
%%%%%%%%%%%

We can then define some array,

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,

function [x1 , x2 , ...] = myfunc(a, b, c, ...)

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!

Tuesday 14th February, 2017 10

Das könnte Ihnen auch gefallen