You are on page 1of 79

# MATH286 -- Part1 Semester1

## FURTHER INTRODUCTION TO MATLAB

We discuss further as well as basic features of MATLAB programming,
including
Contents
1.1 MATLAB Basics............................................................................................................. 2
1.2 Arithmetic Operations and Variable Assignment ........................................................... 3
1.3 Vectors in MATLAB ...................................................................................................... 9
1.3.1
Horizontal Vectors ................................................................................................... 9
1.3.2
Column Vectors ..................................................................................................... 12
1.3.3
Operations on arrays .............................................................................................. 13
1.4 Simple graphs ................................................................................................................ 14
Exercises A ........................................................................................................................... 17
Solutions A ........................................................................................................................... 20
2: MATRICES AND STATISTICAL ANALYSIS & SIMULATION ................................... 26
2.1 MATRICES ........................................................................................................................ 26
2.1.1
Fundamentals ......................................................................................................... 26
2.1.2
Elementary Matrix Operations ............................................................................... 29
2.1.3
Matrix Inversion..................................................................................................... 32
2.1.4
Systems of Linear Equations ................................................................................. 33
2.1.5
Eigenvalues and Eigenvectors ............................................................................... 34
2.1.6
Matrix Transpose ................................................................................................... 35
2.1.8
Functions which perform element-by-element operations on matrices ................. 37
2.1.9
Functions length, size, sum, mean, max, min ........................................................ 38
2.2 STATISTICAL ANALYSIS AND SIMULATION ..................................................... 41
2.2.1
Random Samples from a Uniform Distribution ..................................................... 41
2.2.2
Random Samples from a Gaussian Distribution .................................................... 43
2.2.3
Simple Statistical Analysis .................................................................................... 44
3: CONTROL STRUCTURES ................................................................................................ 46
3.1 A FEW USEFUL COMMANDS ....................................................................................... 47
3.2 CONDITIONAL CONTROL STRUCTURES .................................................................. 49
Example................................................................................................................................ 52
3.3 REPETATIVE CONTROL STRUCTURES ..................................................................... 54
3.3.1
The For loop ........................................................................................................... 54
3.3.2
The while loop ....................................................................................................... 59
Example................................................................................................................................ 61
4: MATLAB GRAPHICS ........................................................................................................ 62
4.1 2-D PLOTS ........................................................................................................................ 62
4.2 3-D PLOTS .................................................................................................................... 67
4.3 Fractals And Chaos ........................................................................................................ 73
4.4 Making Movies .............................................................................................................. 76

## 1.1 MATLAB Basics

MATLAB is a computer program (software package) used extensively to perform engineering
and scientific calculations. MATLAB has become popular because of its ease of use and
because it has excellent graphical capabilities.

MATLAB is short for MATrix LABoratory. It started life in the mid 1980s
as a program to perform various matrix operations, but over the years it has
grown into a flexible computing system capable of solving essentially any
technical problem.
If MATLAB is not installed on your PC, the first step for using it is to install it.
From windows desktop, click on the Start button (at the bottom left hand side
of the screen); then on the Install University Applications.
Choose the Category of Mathematics from the drop-down menu to refine the
list of available software. Then select MATLAB 2008 and click Run. This will
place the MATLAB icon on your desktop. Now you can start MATLAB by
double clicking the MATLAB icon.
When you start MATLAB, a special window called the MATLAB desktop
appears. The default configuration of the MATLAB desktop in shown in the
following figure. MATLAB desktop is composed of the following windows:
Command Window: This is the main window of the MATLAB desktop. When
MATLAB is ready to accept a new command, it shows the command prompt >>
in this window. To execute a command, you should first type it at the command
prompt and then press the enter key.
Command History Window: The Command History Window displays a
list of the commands that you have entered in the Command Window. To
execute a command that you have previously used, locate it in the Command
History Window and double-click it with the left mouse button. To delete,
copy or evaluate one or more commands from the Command History
Window, select the commands and right-click them with the mouse. A popup
menu will be displayed that allows you to delete, to copy or to evaluate the
selected commands.

Current Directory Window: This is where all the files you have generated will
be saved. The default current directory at the University of Liverpool is
m:\matlab. You can select a file and right-click it to see what options are
available. For example, you can delete a file in this way. You can also browse
for folders and change your current directory by the browse for folders
button provided in the MATLAB Toolbar at the top of the MATLAB desktop.
Workspace Window: This window lists all the variables that you have
generated together with their type and size.
The Desktop Menu allows you to determine which of the above windows you
want to be active. You can always go back to the default desktop configuration
through the Desktop Menu by clicking on Desktop Layout and then by
clicking on the Default.

## 1.2 Arithmetic Operations and Variable Assignment

MATLAB is an interpreter. That means you can type text to it and receive
output right away, like a pocket calculator. By contrast, FORTRAN, C, and Java
require "compilation" of your program first.
3

To begin this discussion, lets assume we are purchasing rolling stock for a
railroad company. We buy 4 tanker cars at a cost of 25.5K each, 6 box cars at a
cost of 22K each and 2 refrigeration cars at a cost of 50K each. To compute
our total cost for this purchase, we could use MATLAB just like an ordinary
calculator. That is, we would enter the following command in the MATLAB
command window at the prompt (>>) and press the enter key:
>> 4 * 25.5 + 6 * 22 + 2 * 50
and the monitor would display
ans

=
334

## The number 334 is the cost of purchase (expressed in units of 1,000); it is

called a constant. The ans (short for answer) is a variable. A variable is a
labelled piece of computer memory. In the above expression, the constant 334
is stored in a cell in computer memory and is given the label ans. (Alternatively,
we can say that the equal sign assigns the constant 334 to the variable ans.)
The variable name ans is what MATLAB uses as a default; i.e., any constant
not assigned to a variable is assigned to ans.
We might choose to assign our cost to a variable named OurCost by typing the
following:
>> OurCost = 4*25.5 + 6*22 + 2*50
which would generate the output
OurCost =
334
Note that in any assignment statement, the variable receiving some constant
must be on the left-hand side of the equal sign.
When a command such as OurCost = 4*25.5 + 6*22 + 2*50 is
evaluated, MATLAB does the followings:
It chooses a memory location to store the value in
It gives the name OurCost to the memory location

## Evaluates the expression 4*25.5 + 6*22 + 2*50 and stores the

result (334) in the memory location.
The name OurCost serves as an identifier for the location in memory where
the number 334 is stored. Therefore, we never need to worry about what the
actual memory location is. We can use the variable name OurCost instead of
334 for further calculations. For example, if the rolling stock manufacturer
offered us a 10 percent discount on our purchase, we might calculate our new
cost as follows:
>> NewCost = OurCost * 0.9;
For the above command, we would not receive any output; the semicolon at the
end of the line suppressed it. However, if we typed
>> NewCost
NewCost =
300.6
which is, of course, 90% of the value stored in OurCost.

You, the programmer, decide what name to give to variables. There are a few
rules in this regard, but if you always start a variable name with a letter (as
opposed to a number or some other character), and if you dont use a very large
number of characters, and if you dont use MATLAB reserved words (such as
if, for, length, sum, end, pi and size), youll be fine.
The names you give to variables should convey some meaning (e.g., a diameter
might be stored in a variable named dia). This makes it easier for people to
review your code. You can use the underscore (_) to make your variables more
readable. For example, compare Estimated_cost with Estimatedcost.
They are both valid variable names, but the first one is more readable.
Alternatively you can use a mixture of upper and lower case letters. For example,
compare EstimatedCost with Estimatedcost. Again, they are both
valid variable names, but the first one is more readable. Also remember that
only the first 63 characters in a variable name are significant. In other words, if
two variables are declared with names that only differ in the 64th character,
MATLAB will treat them as the same variable.

This is a good place to emphasize that MATLAB is case sensitive. For example,
if we typed
>> Newcost
(Note the lowercase c) MATLAB would display a message that we have an
"undefined variable" because Newcost is different from NewCost
and no value has been assigned to Newcost.
If we type the following code:
>> NumTank = 4; NumBox = 6; NumFridge = 2;
>> OurCost = NumTank * 25.5 + NumBox * 22 + NumFridge
* 50
OurCost =
334
But suppose we changed our minds and decided we really only need 3 tanker
cars, not 4. We could (re)assign the constant 3 to the variable NumTank
>> NumTank = 3;
Now 3 is stored in NumTank; the old value of 4 "disappears." But whats the
value now stored in OurCost? It is still 334! MATLAB wont automatically
update the constants previously stored in variables. After assigning 3 to
NumTank, we could retype the expression
>> OurCost = NumTank * 25.5 + NumBox * 22 + NumFridge
* 50
and press the enter key or we could scroll backward through our commands
(by using the arrow key ) until returning to that expression and press the
enter key. Alternatively, locate the command in the Command History
Window and double-click it with the left mouse button.
The following symbols are used for arithmetic operations
^ for exponentiation (raising to a power)
/ for division

* for multiplication
- for subtraction
A common mistake made by first-time programmers is to omit the
multiplication operator. For example, writing
>> b = 5(2*3)
will generate the following output
??? b = 5(2*3)
|
Error: Missing operator, comma, or semicolon.
The correct syntax is
>> b = 5*(2*3)
b =
30
When an expression involves multiple operators, it may not be clear which
operator should be applied first. To avoid ambiguity, all operators have an
associated precedence. The operator with the highest precedence is applied first,
followed by the second highest, and so on. Operators of the same precedence are
evaluated from left to right. You often need to use parentheses to make sure that
the operations are carried out in the correct order.
MATLAB performs operations in the following order of precedence:
1. The contents of all bracketed expressions are evaluated, starting from the
innermost brackets and working out.
2. All exponentiations are evaluated, working from left to right.
3. All multiplications and divisions are evaluated, working from left to right.
4. All additions and subtractions are evaluated, working from left to right.
For example, consider the following expression
>> X = 2*(1+2/3) + 2.5*(3*(23+14.7-4/6)/3.5 + 5) + 1
X =
96.1905
>>

## MATLAB calculates X in the following manner.

MATLAB gives precedence to parentheses, and if there are nested
parentheses, it gives precedence to the innermost one. So (23+14.74/6) = 37.0333 is calculated first. Therefore, X would be equal
to X = 2*(1+2/3) + 2.5*(3*37.0333/3.5 + 5) + 1
Now we have two sets of parentheses in X. MATLAB gives precedence
from left to right. So it first calculates (1+2/3). We have two operations
inside these parentheses: addition and division. MATLAB gives
precedence to division over addition, so it first calculates 2/3 and then
adds the results to 1 to come up with 1.6667. So X would be X =
2*1.6667 + 2.5*(3*37.0333/3.5 + 5) + 1. Now
MATLAB calculates the expression inside the right-hand-side parentheses.
Inside this set of parentheses we have three operations, multiplication,
division and addition. Again multiplication and division have precedence
over addition. However, multiplication and division are of the same
precedence, so MATLAB does the calculations from left to right. That is,
it first calculates 3*37.0333 and then divides the result by 3.5.
Finally, it adds 5 to the outcome to come up with 36.7428. So X
would be equal to X = 2*1.6667 + 2.5*36.7428 + 1.
Now we have two multiplications and two additions. MATLAB does the
multiplications first and from left to right. So it first calculates
2*1.6667 = 3.3334 and then 2.5*36.7428 = 91.8570. So
X would be equal to X = 3.3334 + 91.8570 + 1.
MATLAB now calculates X by first adding 91.8570 to 3.3334 and
then adding 1 to the outcome. So X would be equal to X = 96.1905.
As another example, lets assume we want to compute the total cargo carrying
capacity of 4 (cylindrical) tanker cars with external diameters of 7 ft, external
lengths of 20 ft and a wall thickness of 0.08 ft. We can use the following
commands.
>> rad = 7/2; len = 20;
>> volume = pi * (rad - 0.08)^2 * (len - 2*0.08) * 4;
By the way, MATLAB assigns a value of 3.14159265358979 to the
variable named pi by default. You could reassign any value to pi, but it is not

good practice. It is best to leave the value of pi, i, j and eps which have
pre-assigned values unchanged. Also remember that length is the name of a
function in MATLAB and you should avoid using it as a variable name. Instead
use a variation of it such as length1 or garden_length, etc.
1.3 Vectors in MATLAB
In MATLAB, an array is a collection of data values organised into rows and
columns. Although an array is composed of many elements, a single name is
used to refer to it. The term matrix is usually used to refer to an array with
two or more dimensions, while the term vector is usually used to describe an
array with only one dimension. A vector can either be horizontal or vertical.
1.3.1 Horizontal Vectors
A horizontal vector, named A, can be defined in the following way
>> A = [a1, a2, ..., an];
The square brackets are required for specifying arrays. Each element (i.e., each
ai) can be separated by commas and/or spaces. For example,
>> A = [10, 3, -5, 20]
A =
10
3
-5
20
You can extract individual values from an array by specifying the index within
the array using round brackets. For example, if you type,
>> C = A(2)
The value of the second element of A would be assigned to C. The output would
be,
C =
3
Now, suppose we wanted to compute values of the sin function over the range
0 to pi/2 in steps of 0.1*pi. (The function sin is a MATLAB built-in
function. It calculates the sine of its argument. That is, sin(x) will give you
the value of the sine of the angle x, where x must be in radians).

## >> x = [0 .1*pi .2*pi .3*pi .4*pi .5*pi]

x =
0
0.3142
0.6283
0.9425
1.2566

1.5708

>> y = sin(x)
y =
0
0.3090

1.0000

0.5878

0.8090

0.9511

Again, you can access individual elements of x and y using that elements index
number. For example,
>> x(2)
ans =
0.3142
>> z = 1 + x(3)
z =
1.6283
Colon Notation

## The shorthand a:b:c means a to c in steps of b. That is, typing 2:3:12 is

equivalent to typing [2,5,8,11] and typing [8:-1:3] is equivalent to
typing [8,7,6,5,4,3]. If b is equal to unity, it can be eliminated;
therefore, the shorthand a:c is equivalent to a:1:c.
Having introduced the colon notation, we can use this notation to access
elements of an array. For example,
>> x = [0 .1*pi .2*pi .3*pi .4*pi .5*pi]
x =
0
0.3142
0.6283
0.9425
1.2566
>> x(1:3)
ans =
0

0.3142

0 .6283

cc =
0.3142
0.9425
>> y = sin(x)
y =
0
0.3090

1.5708

1.2566

0.5878

0.8090

0.9511

1.0000

10

>> y(3:-1:1)
ans =
0.5878

0.3090

## Here the array y is accessed from element 3 to element 1 in steps of -1.

There are all kinds of ways to append arrays in MATLAB. As examples:
>> a = 1:5, b = 1:2:9
a =
1
b =
1

>> c = [b a]
c =
1
3
5

>> d = [a(1:2:5) 1 0 1]
d =
1
3
5
1
0
1

Function linspace
Linspace is a built-in MATLAB function. The expression linspace(X1,
X2, N) generates N equally-spaced points between X1 and X2, starting with
X1 and ending with X2. For example,
>> x = linspace(0,6,5)
x =
0
1.5000

3.0000

4.5000

6.0000

## A few useful points

In MATLAB, all the indices start from one. In other words, an array does not
have a zero or a negative element index. If you try to access or to assign a value
to an element with a zero or negative index, MATLAB will return an error
message. For example, assigning 1 to element number 0 of vector a will lead to
>> a(0) = 1
??? Index into matrix is negative or zero.

11

If the vector or mathematical expression is too long to easily fit on a line you
can use the MATLAB continuation operator, "..."
>> x = [0 .1*pi .2*pi ...
.3*pi .4*pi .5*pi]
x =
0 0.3142 0 .6283

0.9425

1.2566

1.5708

However, this operator does not work for comment lines. Comment lines begin
with the following symbol %. The symbol % tells MATLAB that this is a
comment line and so MATLAB disregards the rest of the line.
1.3.2 Column Vectors
Thus far weve looked at horizontal vectors, which are also called row vectors.
We can also define column vectors. One way is to separate rows by means of
semicolons, e.g.,
>> Vvect = [7;5;10]
Vvect =
7
5
10
Alternatively, we can code the following
>> Vvect = [7
5
10];
A row vector can be converted into a column vector, and vice versa, by
transposition and MATLAB performs this using an apostrophe (or prime)
>> Hvect = Vvect'
Hvect =
7 5 10
The command Y = X(:) converts the horizontal vector X into a vertical
vector. On the other hand, if X is already a vertical vector, it leaves X
unchanged, so that the vector Y would always be a vertical vector, regardless
of the state of X.

12

## 1.3.3 Operations on arrays

This can be divided into scalar-array operations and array-array operations. A
scalar is a number such as 5 or 6.71.
Scalar-Array Operations

## The operations +, -, *, and / are performed "element by element" when

used between a scalar and an array. For example,
>> A = [1 2 3 4 5];
>> A - 2
ans =
-1

>> Z = 2 * A - 1

3
%note the precedence of multiplication over subtraction

Z =
1

Array-Array Operations

For two vectors of the same size and orientation, the ".*", ./ and .^
operators mean "element by element" multiplication, division and
exponentiation, respectively. For example,
>> A = [1,2,3]; B = [4,5,6];
>> P = A + B
P =
5
7

>> Q = A - B
Q =
-3
-3

-3

>> C = A.*B
C =
4
10

18

>> D = A./B
D =
0.2500

0.4000

0.5000

>> E = A.^B
E =
13

32

729

>> F = A.^2
F =
1
4

>> T=2.*A
T =
2

or
4

9
2*A
6

>> S=A./2
S =
0.5000

or A/2

>> U=2./A
U =
2.0000

1.0000

1.0000

1.5000

0.6667

## 1.4 Simple graphs

One of the strong points of MATLAB is its extensive and device-independent
plotting capabilities. To produce a two-dimensional plot, just create two vectors
containing the same number of elements and then use the plot function
Example 1:
Plot the function y = x2 5x + 1, for 0 x 10
The following three statements are sufficient to create the plot. The first
statement creates a vector of x values between 0 and 10 using the colon operator.
The second statement calculates the y values from the x values. Note that x is
an array and that we have to use array operators so that y would be calculated
for each x value on an element-by-element basis.
>> x = 0:0.5:10;
>> y = x.^2 - 5*x + 1;
>> plot(x,y)
Note: we can equally define y as y = x.^2 5.*x + 1;
The function plot will create a figure window in which a plot of y versus x
will be displayed. The previous commands will lead to the following plot.

14

60
50
40
30
20
10
0
-10
0

10

We now need to improve this figure by adding labels to the x and y axes and by
giving the figure a title. The following commands should be used.
>> xlabel('x')
>> ylabel('y')
>> title('Graph of y(x) = x^2 - 5x + 1')
These commands will lead to the following figure
Graph of y(x) = x 2 - 5x + 1
60
50
40

30
20
10
0
-10
0

10

Now type the following command and see what will happen
>> grid on
As you see grid on turns the grid lines on and grid off turn them off.
15

## Now type axis square to make the plot square in size.

>> axis square
The final plot should be like this
Graph of y(x) = x 2 - 5x + 1
60
50
40

30
20
10
0
-10
0

10

If you use the function plot again to display the variation of two new vectors
(for example, t=1:10; z=t.^2; plot(t,z)), MATLAB will use the
existing figure window to display the new plot. If you want the plot of z versus
t to be displayed in a new figure window, you should include the command
figure before plot. The function figure will create a new figure window.
Try the following,
t=1:10;
z=t.^2;
figure,plot(t,z)
If you want to close all your figure windows, use
close all
If you want to close a few figures try the following:
%The
following
command
will
close
Other %figures will remain open.
close(2)

figure

2.

16

## %The following command will close figures 3, 4 and

5. %Other figures will remain open.
close(3:5)
%The following commands will close figures
and %8. Other figures will remain open.
close([3 5 8])
close([3, 5, 8])
close([3; 5; 8])

3,

Exercises A
1.

2.

32 5
2.3 2 5
60
23
60 3
2
2(5)(7)
12 3
5 1
sin(0.1 )
2 4
4 2 3 cos ( / 2)

3.

## Write MATLAB commands to set the value of the variable r to 5. Then

calculate the circumference of a circle of radius r and assign the value to an
appropriate name.

4.

Plot the function cos(x) versus x for x in the range of 0 and 2. Label
the x and y axes and give the plot a title. Use the colon notation to generate
the x values.

5.

## Plot the function x2 + 2x + sin(x) versus x for x in the range of 0

and 2. Label the x and y axes and give the plot a title. Use the function
linspace to generate the x values.
17

6.

## Now plot the function x2 + 2x + sin(x) versus x for x in the range of

0 and 3 in a new figure window. Label the x and y axes and give the plot
a title. Use the function linspace to generate the x values. Set the grids
on and make the plot square in size.
As this exercise is very similar to the previous one, rather than typing all
the commands again, use the key to find the command linspace you
used before. Then edit it and press the enter key. This will define the new
values of the variable x. Then locate the commands you used to plot the
figure in the Command History Window and double click them to
execute them. There is no need to retype them.
7. Use the function linspace to generate five values between 0 and 1
(call it x) and five values between 10 and 15 (call it y). Now
multiply x and y element-by-element using the operator .*. Repeat the
exercise but this time generate six y values between 10 and 15. Why do
you get an error message?
8. Try the following commands. The results would be the following
polar in the command window. The function sqrt(x) means the
square root of x and the function abs(x) means the absolute value of x.
can we use the function plot rather than polar to get a similar graph?
>> theta = linspace(0,2*pi,800);
>> distance = sqrt(abs(2*sin(5*theta)));
>> figure,polar(theta,distance,'*')
>>

18

90

1.5

120

60

1
150

30
0.5

180

210

330

240

300
270

19

Solutions A
1.

>> 2 + 3 * 5
ans =
17
>> (2 + 3)*5
ans =
25

2.

## Write MATLAB commands to evaluate the following expressions:

32 5
2.3 2 5
60
23
60 3
2
2(5)(7)
12 3
5 1
sin(0.1 )
2 4
4 2 3 cos ( / 2)

>> 3^2 + 5
ans =
14
>> 2.3^(2+5)
ans =
340.4825
>> 60/(2+3)
ans =
12
>> (60+3)/2
ans =
31.5000

20

>> -2*5*-7
ans =
70
>> (12-3)/(5+1)
ans =
1.5000
>> sin(0.1*pi)/2^(4+pi)
ans =
0.0022
or
>> sin(0.1*pi)/(2^(4+pi))
ans =
0.0022
>> 4^2 + 3*cos(pi/2)
ans =
16

3.

## Write MATLAB commands to set the value of the variable r to 5. Then

calculate the circumference of a circle of radius r and assign the value to an
appropriate name.
>> r=5;
>> circle_circumference = 2*pi*r
circle_circumference =
31.4159

4.

Plot the function cos(x) versus x for x in the range of 0 and 2. Label
the x and y axes and give the plot a title. Use the colon notation to generate
the x values.
>>
>>
>>
>>
>>
>>

x=0:0.1*pi:2*pi;
y=cos(x);
plot(x,y)
xlabel('x')
ylabel('cos(x)')
title('Variation of cos(x) with x')
21

>> grid on
>> axis square
Variation of cos(x) with x
1
0.8
0.6
0.4

cos(x)

0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0

5.

## Plot the function x2 + 2x + sin(x) versus x for x in the range of 0

and 2. Label the x and y axes and give the plot a title. Use the function
linspace to generate the x values.
>>
>>
>>
>>
>>
>>
>>

x = linspace(0,2*pi,50);
y = x.^2 + 2*x + sin(x);
plot(x,y)
xlabel('x')
ylabel('x^2 + 2x + sin(x)')
grid on
axis square

22

60

x 2 + 2x + sin(x)

50

40

30

20

10

0
0

6.

## Now plot the function x2 + 2x + sin(x) versus x for x in the range of

0 and 3 in a new figure window. Label the x and y axes and give the plot
a title. Use the function linspace to generate the x values. Set the grids
on and make the plot square in size.
As this exercise is very similar to the previous one, rather than typing all
the commands again, use the key to find the command linspace you
used before. Then edit it and press the enter key. This will define the new
values of the variable x. Then locate the commands you used to plot the
figure in the Command History Window and double click them to
execute them. There is no need to retype them.
>>
>>
>>
>>
>>
>>
>>
>>
>>

x = linspace(0,3*pi,100);
y = x.^2 + 2*x + sin(x);
figure
plot(x,y)
xlabel('x')
ylabel('x^2 + 2x + sin(x)')
title('Variation of x^2 + 2x + sin(x) with x')
grid on
axis square

23

## Variation of x 2 + 2x + sin(x) with x

120

x 2 + 2x + sin(x)

100

80

60

40

20

0
0

10

## 7. Use the function linspace to generate five values between 0 and 1

(call it x) and five values between 10 and 15 (call it y). Now
multiply x and y element-by-element using the operator .*. Repeat the
exercise but this time generate six y values between 10 and 15. Why do
you get an error message?
>> x = linspace(0,1,5)
x =
0
0.2500
0.5000
>> y = linspace(10,15,5)
y =
10.0000 11.2500 12.5000

0.7500

1.0000

13.7500

15.0000

>> z = x.*y
z =
0

10.3125

15.0000

2.8125

6.2500

>> y = linspace(10,15,6)
y =
10
11
12
13

14

15

>> z = x.*y
??? Error using ==> .*
Matrix dimensions must agree.

24

## 8. Try the following commands. The results would be the following

polar in the command window. The function sqrt(x) means the
square root of x and the function abs(x) means the absolute value of x.
can we use the function plot rather than polar to get a similar graph?
>>
>>
>>
>>
>>
>>
>>

theta = linspace(0,2*pi,800);
distance = sqrt(abs(2*sin(5*theta)));
x = distance.*cos(theta);
y = distance.*sin(theta);
figure,plot(x,y,'*')
axis square

1.5

0.5

-0.5

-1

-1.5
-1.5

-1

-0.5

0.5

1.5

25

## 2: MATRICES AND STATISTICAL ANALYSIS & SIMULATION

This part is composed of two Sections; In Section 1, we discuss matrices, which
have wide applications in all branches of engineering and science. In Section 2,
we discuss how MATLAB can be used to generate random samples from
populations with uniform or Gaussian distributions. We will also discuss simple
ways in which the statistical properties of the simulated data can be expressed.
2.1 MATRICES
MATLAB accommodates matrices easily because the basic object in MATLAB
is a matrix. MATLAB sees a vector as a matrix with either one row or one
column. A scalar is seen as a matrix with one row and one column. In this
section we will see how matrices are defined in MATLAB and how we can use
MATLAB commands to perform various operations on them.
2.1.1 Fundamentals

Definition
A matrix is a two-dimensional array; i.e., it is a collection of numbers organised
into rows and columns. (Therefore, each element of a matrix is identified by two
indices referring to that elements respective row and column numbers). The
size of a matrix is specified by the number of its rows and the number of its
columns, with the number of rows mentioned first. A matrix can be entered in
MATLAB with rows separated by semicolons or by carriage returns. The entire
matrix must be enclosed by square brackets. For example, consider the
following 2-by-3 matrix,

1 2 3
A

4 5 6
in MATLAB, matrix A can be entered as:
>> A = [1 2 3; 4 5 6];
or
>> A = [1 2 3
4 5 6];
Now, if you type A at the command prompt, you will get the following response,

26

>> A
A =
1
4

2
5

3
6

Once a matrix has been defined, its elements will be identified by their
corresponding row and column indices. For example, A(2,3) refers to the
element in the second row and the third column of martix A. Therefore,
>> A(2,3)
ans =
6
You can use indices to change an entry. For example, you can use the following
command to change the value of A(2,3) to 9.
>> A(2,3)= 9;
Now if you type A, the new value of matrix A is,
>> A
A =
1
4

2
5

3
9

Sub-matrices
A section of a matrix can be referred to by identifying the indices of its elements.
For example, B = A(m:n,r:s) specifies a matrix which is composed of those
elements of A which are in rows m to n and columns r to s. In the following
example, a sub-matrix defined by rows 1 and 2 and columns 1 and 3 of matrix
A is extracted.
>> B = A(1:2,[1 3])
B =
1
3
4
9
A colon is used to specify all the rows or all the columns of a matrix. For
example,
>> A(1,:)
ans =
1
2

3
27

The 1 in A(1,:) refers to the first row of matrix A and the : means all its
columns. Similarly, the colon in the following command means all the rows of
matrix A and 2 refers to the second column.
>> A(:,2)
ans =
2
5

Special matrices

A vector is a special type of matrix with just one row (horizontal vector)
or one column (vertical vector). For example,
>> Horizontal_vector = [ 1
3.15
Horizontal_vector =
1.0000
3.1500
7.8000

7.8]

## >> Vertical_vector = [1; 3.15; 7.8]

Vertical_vector =
1.0000
3.1500
7.8000
A scalar (single number) is a one-by-one matrix. A scalar does not need
brackets. For example,
>> Gravitational_constant = 9.806;
Square brackets with no elements between them define an empty (null)
matrices. For example,
>> Empty_matrix = []
Empty _matrix =
[]

Combining matrices
Matrices can be combined as long as their sizes are compatible. In the following
examples, matrices A and B have been combined to create new matrices.
>> A = [1 2 3; 4 5 6];

28

>> B = [7 8; 9 10];
>> C = [A B]
C =
1
2
3
7
8
4
5
6
9
10
or
>> [A(1:2,1:2); B]
ans =
1
2
4
5
7
8
9 10
2.1.2 Elementary Matrix Operations

## If a scalar is added to or subtracted from a matrix, it will be added to or

subtracted from all its elements. For example,
>> A = [1 2 3; 3 4 5];
>> A+5
ans =
6
7
8
8
9
10
If a matrix is multiplied or divided by a scalar , then all its elements would be
multiplied or divided by . For example,
>> A = [1 2 3; 3 4 5];
>> 5*A (Alternatively, you can use 5.*A)
ans =
5
10
15
15
20
25
>> A/5 (Alternatively, you can use A./5)
ans =
0.2000
0.4000
0.6000
0.6000
0.8000
1.0000
You can divide a scalar by all the elements of a matrix using the ./ operation.
For example,
>> A = [1 2 3; 3 4 5];
29

>> 3./A
ans =
3.0000
1.0000

1.5000
0.7500

1.0000
0.6000

Note that using the operation / to divide a scalar by all the elements of a matrix
is not acceptable and will result in the following error message. For example,
>> 3/A
??? Error using ==> /
Matrix dimensions must agree.
Finally, you can raise all the elements of a matrix to the power of a scalar using
the symbol .^. For example,
>> B = A.^2.5
B =
1.0000
5.6569
15.5885
32.0000

15.5885
55.9017

## Element-by-element operations between matrices of the same size

We have already mentioned in Session 1 that for two vectors of the same size
and orientation, the "+", "-", ".*", "./" and ".^" operators can be used for
element-by-element operations. The same is true for matrices of the same size.
For example,
>> A = [1 2;3 4];B=[5 6;7 8];

>> A+B
ans =
6
10

8
12

>> A-B
ans =
-4
-4

-4
-4

>> D = A .* B
D =
5
12
21
32

30

>> E = A./B
E =
0.2000
0.4286
>> F = A.^B
F =
1
2187

0.3333
0.5000

64
65536

Matrix multiplication
Suppose matrix C is the product of matrix A and matrix B. Then, by definition,
Cij would be equal to the dot product of row i of matrix A and column j of
matrix B. For example,
a
b
a
b
A 11 12
B 11 12
a21 a22
b21 b22
a11b12 a12 b22
a b a b
C A * B 11 11 12 21

## Thus, to multiply two matrices, they must be compatible; i.e.,

Number of columns in 1st matrix = Number of rows in 2nd matrix
Matrix multiplication in MATLAB is very simple. For example,
>> A =
>> C =
C =
19
43

[1 2; 3 4]; B = [5 6; 7 8];
A * B
22
50

You can raise a square matrix to an integer power. For example, A^2 is
equivalent to A*A and A^3 is equivalent to A*A*A.
>> A= [1 2; 3 4];
>> B = A^3
B =
37
54
81
118

31

Note the difference between A^3 (calculated above) and A.^3. The first
command raises matrix A to the third power (A^3 = A*A*A) while the second
command raises each element of matrix A to the third power.
>> B = A.^3
B =
1
8
27 64
2.1.3 Matrix Inversion
Let A be a square n-by-n matrix. If there is another n-by-n matrix B such
that
AB=BA=I
where I is the n-by-n identity matrix (i.e. a matrix with 1s on its main
diagonal and 0 everywhere else), then A is called non-singular and B is called
the inverse of A and is usually denoted by A-1.
Matrix inversion can be performed by hand, but the process is very tedious.
MATLAB helps us out via a built-in function. The inverse of matrix A (well
call it A_inverse) can be computed using the function inv. For
example,
>> A = [2 3 1; 0 1 2; 4 2 0];
>> A_inverse = inv(A)
A_inverse =
-0.3333
0.6667
-0.3333

0.1667
-0.3333
0.6667

0.4167
-0.3333
0.1667

Now calculate the product of A and A_inverse to confirm that the result
would be equal to the identity matrix.
>> C = A*A_inverse
C =
1.0000
-0.0000
0
1.0000
0
0

-0.0000
0
1.0000

## One way to determine whether a matrix is non-singular is to evaluate its

determinant, which is a property of a square matrix. If the determinant is non32

zero, the matrix is non-singular. We can use the MATLAB built-in function
det to compute a determinant:
>> A = [2, 3, 1; 0, 1, 2; 4, 2, 0];
>> det(A)
ans =
12
2.1.4 Systems of Linear Equations
Matrices can be used to represent systems of linear equations. For example, the
following set of three linear equations
2 X1

3X 2
X2

X3
2X3

4 X1 2 X 2

4
6

12

can be represented as
2 3 1 X 1 4
0 1 2 X 6

2
4 2 0 X 3 12

## or, in a more compact form as

AX B
2 3 1
A 0 1 2 ;

4 2 0

X1
X X2 ; B

X 3

4
6

12

where A is the matrix of coefficients, B is the right-hand side vector, and X is the
solution vector.
If matrix A is non-singular, there would be a unique solution (X = A-1 * B)
to the above set of equations (i.e., there would exist unique values of Xi which
would satisfy the above set of linear equations). The following MATLAB
commands will solve the foregoing equations.
>> A = [2 3 1; 0 1 2; 4 2 0];
>> B = [4; 6; 12];

33

## >> A_inverse = inv(A);

>> X = A_inverse * B
X =
4.6667
-3.3333
4.6667
Alternatively, we can use a technique called Gaussian Elimination, which is a
faster and more stable way of solving a set of linear equations. It is invoked in
MATLAB with the left division operator (\).
>> X = A\B
X =
4.6667
-3.3333
4.6667
Now confirm the validity of the foregoing solution by multiplying A by X. The
result should be equal to vector B.
>> A*X
ans =
4.0000
6.0000
12.0000
2.1.5 Eigenvalues and Eigenvectors
Lets assume A is a square matrix. If there is a scalar and a vector v such that
Av v

## then is called an eigenvalue of matrix A and v would be its corresponding

eigenvector. The command [V,D] = EIG(A), where A is a square matrix,
produces a diagonal matrix D of the eigenvalues of matrix A and a matrix V
whose columns are their corresponding eigenvectors. For example, the
eigenvalues and eigenvectors of the following matrix are
>> A = [1 2 3; 2 4 5; 3 5 6];
A =
1
2
3
2
4
5
3
5
6

34

V =
0.7370
0.5910
0.3280
-0.7370
-0.5910
0.3280

0.3280
0.5910
0.7370

D =
-0.5157
0
0

0
0.1709
0

0
0
11.3448

## The smallest eigenvalue of matrix A is 0.5157 and its corresponding

eigenvector is the first column of matrix V. Similarly, the largest eigenvalue of
matrix A is 11.3448 and its corresponding eigenvector is the third column of
matrix V. Now, confirm that matrix A multiplied by an eigenvector is equal to its
corresponding eigenvalue multiplied by that eigenvector. In other words,
confirm the validity of the following equations:
A*V(:,1) = D(1,1)*V(:,1)
A*V(:,2) = D(2,2)*V(:,2)
A*V(:,3) = D(3,3)*V(:,3)
For example,
>> A*V(:,1)
ans =
-0.3801
-0.1692
0.3048
which is equal to
>> D(1,1)*V(:,1)
ans =
-0.3801
-0.1692
0.3048
2.1.6 Matrix Transpose
If B is the transpose of matrix A, then bij = aji. In other words, the first column of
matrix B would be the same as the first row of matrix A and so on and so forth.
For example,

35

>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]
A =
1
2
3
3
4
5
6
7
9
12
13
14
>> B=A'
B =
1
2
3

3
4
5

6
7
9

12
13
14

## 2.1.7 Special Matrices

The function zeros takes two arguments, m and n, and returns an m-by-n
matrix of zeros. For example,
>> Fox = zeros(3,5)
Fox =
0
0
0
0
0
0
0
0
0

0
0
0

0
0
0

The function ones takes two arguments, m and n, and returns an m-by-n
matrix of ones. For example,
>> Fox = ones(3,5)
Fox =
1
1
1
1
1
1
1
1
1

1
1
1

1
1
1

The function eye takes two arguments, m and n, and returns an m-by-n
identity matrix. An identity matrix is a matrix with 1s on the diagonal and zeros
elsewhere. For example,
>> Fox = eye(3,5)
Fox =
1
0
0
0
1
0
0
0
1

0
0
0

0
0
0

36

## 2.1.8 Functions which perform element-by-element operations on matrices

Most of MATLAB built-in functions take matrix inputs. The output would be a
matrix of the same size because MATLAB works on the input matrix on an
element-by-element basis. For example,
>> x=pi/2;
>> sin(x)
ans =
1
>> x=[1 2 3];
>> sin(x)
ans =
0.8415

0.9093

x =
0
2.0000
4.0000
5.0000

0.1411

3.0000
1.5708

>> sin(x)
ans =
0
-0.7568

0.9093
-0.9589

0.1411
1.0000

## The most important MATLAB functions which work on an element-by-element

basis on the input matrix are
Function
abs(x)
sqrt(x)
log(x)
exp(x)
sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)
sinh(x)
cosh(x)
tanh(x)

Description
Absolute Value, |x|
Square Root, x
Natural logarithm, logex
Exponential, ex
Sine with x in radians, sin(x)
Cosine with x in radians, cos(x)
Tangent with x in radians, tan(x)
Inverse Sine with the result in radians, sin-1(x)
Inverse Cosine with the result in radians, cos-1(x)
Inverse Tangent with the result in radians, tan-1(x)
Hyperbolic Sine
Hyperbolic Cosine
Hyperbolic Tangent

37

asinh(x)
acosh(x)
atanh(x)
round(x)

## Inverse Hyperbolic Sine

Inverse Hyperbolic Cosine
Inverse Hyperbolic Tangent
Rounds x to the nearest integer

## To get a more complete list of MATLAB elementary functions type help

elfun at the MATLAB prompt.
2.1.9 Functions length, size, sum, mean, max, min
There are exceptions to the above rule. In other words, there are functions for
which the output would be a single number or a matrix whose size would be
different from that of the input matrix. The most important of these functions
will now be discussed.
You can use the function length to determine the
number of elements of a horizontal or vertical vector.
For example,
>> x=[1 3 5 7];
>> N=length(x)
N =
4
Similarly, you can use the function size to determine
the number of rows and columns of a matrix. For
example,
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]
A =
1
2
3
3
4
5
6
7
9
12
13
14
>> [m,n] = size(A)
m =
4
n =
3
The command ones(size(A)) will produce a matrix whose
size is equal to the size of matrix A and whose
elements are equal to unity. For example,

38

>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14];
>> B = ones(size(A))
B =
1
1
1
1
1
1
1
1
1
1
1
1
Also note the following useful command

>> C = zeros(size(A))
C =
0
0
0
0
0
0
0
0
0
0
0
0
The function sum can be used to calculate the sum of the elements of a
horizontal or a vertical vector. For example,
>> x=[1 3 5 7];
>> sum_x = sum(x)
sum_x =
16
When the function sum is applied to a matrix, it returns a row vector containing
the sums of the matrix elements column by column. For example,
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]
A =
1
2
3
3
4
5
6
7
9
12
13
14
>> sum_A = sum(A)
sum_A =
22
26
31
Sum(A) is equivalent to sum(A,1), which calculates the sums of elements of
matrix A column-by-column. On the other hand, sum(A,2) calculates the sums
of the matrix elements row-by-row. For example,

39

## >> sum_A = sum(A,1)

sum_A =
22
26
31
>> sum_A = sum(A,2)
sum_A =
6
12
22
39
If you want to calculate the sum of all the elements of a matrix, you can use the
function sum two times in the following manner,
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14];
>> sum_A = sum(sum(A))
sum_A =
79

You can use functions mean, max and min in a manner similar to the function
sum. Function mean calculates the arithmetic mean of the data while functions
max and min identify the largest and the smallest elements of the data,
respectively. For example,
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]
A =
1
2
3
3
4
5
6
7
9
12
13
14
>> mean_A = mean(A)
mean_A =
5.5000
6.5000

7.7500

## >> max_A = max(A)

max_A =
12
13
14
>> min_A = min(A)
min_A =
1
2
3

40

>> mean(mean(A))
ans =
6.5833
>> max(max(A))
ans =
14
>> min(min(A))
ans =
1

## 2.2 STATISTICAL ANALYSIS AND SIMULATION

In this Section, we discuss how MATLAB can be used to generate random
samples from populations with uniform or Gaussian distributions. We will also
discuss simple ways in which the statistical properties of the simulated data can
be expressed.
2.2.1 Random Samples from a Uniform Distribution
The function rand is used to simulate random samples from a uniform
distribution. This function takes two arguments, m and n, and returns an m-byn matrix of random numbers in the interval [0, 1]. The implication of the
uniform distribution is that all the numbers between 0 and 1 have an equal
chance of being picked up by the function rand. For example, the following
command will generate a 3-by-5 matrix of random numbers between 0 and 1.
>> xx = rand(3,5)
xx =
0.6721
0.8381
0.0196

0.6813
0.3795
0.8318

0.5028
0.7095
0.4289

0.3046
0.1897
0.1934

0.6822
0.3028
0.5417

Note that when you use the function rand to simulate (i.e., pick up) random
numbers between 0 and 1, your results will be different from that of xx above.
Furthermore, each time you execute the foregoing command, you will get a
different set of random numbers (Try it for yourself). That is what we mean by
random numbers. You cannot predict what the resultant numbers will be; all that
you can say is that they originate from a particular probability distribution. For
example, the function rand picks up numbers between 0 and 1 randomly,
where all numbers in this interval have an equal chance of being picked up.

41

There are other MATLAB functions for simulating numbers originating from
other probability distributions.
If you intend to simulate random numbers in the interval [a, b], then you
should first simulate random numbers in the interval [0, 1], and then multiply
the simulated numbers (xx) by (b-a) and then add a to them. For example,
use the following commands to simulate random numbers between 10 and 85.
>> a=10; b=85; xx=rand(3,5); yy=(b-a)*xx + a
yy =
60.4103
72.8589
11.4730

61.0958
38.4611
72.3847

47.7110
63.2104
42.1669

32.8463
24.2240
24.5073

61.1667
32.7073
50.6255

If you want to simulate integers between 20 and 150, then you will use the
following commands
>> a=-20; b=150; xx=rand(3,5);
>> yy=(b-a)*xx+a
yy =
72.6372
126.7859 100.3727
121.2067 123.1127 102.5977
109.0900 -12.1738
23.8156
>> zz=round(yy)
zz =
73
127
100
121
123
103
109
-12
24

16
88
-4

15.7428
88.2388
-4.1077

91.0830
136.0464
77.3836

91
136
77

It should be noted that the simulated random numbers (yy) are real numbers.
That is why we had to use the function round to convert them into integer
numbers. The function round rounds a real number toward its nearest integer.
For example,
>> round(119.1)
ans =
119
>> round(-19.8)
ans =
-20
42

Functions ceil, floor and fix are also used for rounding numbers. Type the
following help commands to learn how these functions are different from the
function round.
>> help floor
>> help ceil
>> help fix
2.2.2 Random Samples from a Gaussian Distribution
The function randn is used to simulate random samples from a Gaussian
distribution. This function takes two arguments, m and n, and returns an m-byn matrix of random numbers taken from a standardised Gaussian (normal)
distribution. (A standardised distribution is a distribution whose mean is zero
and whose standard deviation is equal to unity, where standard deviation is a
measure of the spread of the data about its mean; that is, the higher the standard
deviation, the higher the spread of the data about its mean). For example, the
following command will generate a 3-by-5 matrix of random numbers from a
standardised Gaussian distribution.
>> xx = randn(3,5)
xx =
2.0211
0.5018
-1.9983

0.2723
0.3368
0.1378

-1.6106
-1.0075
-0.5144

-2.0889
1.0461
0.2153

-0.1624
-0.1758
1.1022

## If you intend to simulate random numbers from a Gaussian distribution whose

standard deviation is sigma_x and whose mean is mean_x, then you should
first simulate random numbers from the standardised Gaussian distribution as
before, and then multiply the simulated numbers by sigma_x and then add
mean_x to them. For example, you can use the following commands to
simulate random numbers from a normal distribution whose mean is 175 and
whose standard deviation is 20.
>> mean_x=175;sigma_x=20;x=randn(3,5)
x =
0.8979
0.5058
0.3299

-0.0901
0.6481
1.7347

-0.0858
-0.3083
1.4596

-1.4038
-0.7092
0.6330

0.2215
-1.3326
0.7305

43

>> y=sigma_x*x+mean_x
y =
192.9581 173.1973
185.1164 187.9621
181.5986 209.6938

173.2833
168.8337
204.1930

146.9244
160.8168
187.6603

179.4303
148.3489
189.6097

## Functions to calculate mean and standard deviation of data

You can use functions mean and std to calculate the mean and standard
deviation of an array of numbers. For example, simulate 1000 numbers from a
normal distribution whose mean and standard deviation are 175 and 20,
respectively. Then calculate the mean and standard deviation of the simulated
numbers. First simulate the data by the following commands:
>> mean_x=175;sigma_x=20;x=randn(1,1000);
>> y=sigma_x*x+mean_x;
Now calculate the mean and standard deviation of the simulated numbers.
>> mean_y= mean(y),std_y=std(y)
mean_y =
174.7924
std_y =
19.6464
As you can see the mean and standard deviations are somewhat different from
175 and 20, which were the mean and the standard deviation of the normal
distribution from which these numbers have been simulated. Can you explain
why? (If you repeat the foregoing exercise, you will see that the mean and
standard deviation will be different from one batch of simulated numbers to
another one).

Histograms
Histograms are one of the tools used in the analysis of data. Given a onedimensional array yy, the command hist(yy,n) sorts the elements of yy
into n bins, according to their numerical value and draws a histogram of the
number of elements in each bin. For example, simulate 2500 uniformlydistributed random numbers between 1000 and 10000 and draw their
histogram with 20 bins.

44

>>
>>
>>
>>
>>
>>

a=1000;b=10000; xx=rand(1,2500);
yy=(b-a)*xx + a;
hist(yy,20)
xlabel('bins')
ylabel('number of elements in each bin')
title('Histogram of uniformly-distributed data with 20 bins')

160

## number of elements in each bin

140
120
100
80
60
40
20
0
1000

2000

3000

4000

5000 6000
bins

7000

8000

9000 10000

It should be noted that everyone of you will end up with a somewhat different
histogram from the one shown above. This is because we are simulating random
numbers and everyones set of 2500 random numbers will be different from the
random numbers simulated by other people.
Now repeat this exercise, but change the number of random numbers to 100 and
then to 1,000,000 and compare the resultant histograms. You will see that as
the number of simulated numbers increases, the histogram will become more
uniform; that is, the number of items in all the bins will be nearly equal.
However, if the number of simulated numbers is small (say 100), then the
number of items in different bins would vary significantly.
We will now simulate 10000 random numbers from a normal distribution with
mean 175 and standard deviation of 20 and plot its histogram with 15 bins.
45

>>
>>
>>
>>
>>
>>

mean_x=175;sigma_x=20;x=randn(1,10000);
y=sigma_x*x+mean_x;
hist(y,15)
xlabel('bins')
ylabel('number of elements in each bin')
title('Histogram of Gaussian data with 15 bins')

The resultant histogram will be similar to the one shown below although
everyone will have a somewhat different histogram.
Histogram of Gaussian data with 15 bins
2000

## number of elements in each bin

1800
1600
1400
1200
1000
800
600
400
200
0
100

150

200

250

bins

Now repeat this exercise, but change the number of random numbers to 100 and
then to 1,000,000 and compare the resultant histograms.

3: CONTROL STRUCTURES
In all the programs we have written so far, MATLAB commands (statements)
are executed one after the other in the order they have been written. We will
now introduce MATLAB statements that allow us to control the order in which
MATLAB commands in a program are executed.
46

There are two types of control statements available in MATLAB. Those which
allow specific sections of the code to be executed or skipped (branching) and
those which cause a specific section of the code to be executed more than once
(looping). We begin with conditional control structures, which allow execution
of a block of statements based on some logical condition. Then we will discuss
how to create loops for repetitive operations. However, before discussing
different types of control statements, we will introduce a few useful MATLAB
commands.
3.1 A FEW USEFUL COMMANDS

disp command
Consider the following example in which the variable aa has been first defined
and then its name has been typed at the command prompt. MATLAB displays
the name of the array aa and also its value.
>> aa=[8.9 11];
>> aa
aa =
8.90

11.00

disp(aa) displays the value of array aa, without printing the array name. For
example,
>> disp(aa)
8.90
or

11.00

>> disp(10)
10.00
>> disp(20*pi)
62.8319
If x in disp(x) is a character string, the text would be displayed. For example,
>> disp('20*pi')
20*pi

## Functions who, whos and clear

47

The function who lists the variable names in current use (Command
Window workspace).
The function whos lists the variables and how much memory they use.
The function clear removes all the variables from workspace. clear
x clears the variable x from computer memory, while clear x y z
clears the variables x, y and z from the memory.
Try these functions to see how they work.

## The format command

When data is displayed in the Command Window, integer values are always
displayed as integers, and other variables are displayed using the default format.
Although MATLAB calculates the value of all the variables internally to 16
significant figures, the default format displays numbers with four digits after the
decimal point. Furthermore, it may display numbers in scientific notation if they
are too large or too small. You can use the following format commands to
modify the way numbers are displayed.
format
format
format
format
format
format
format
format

short
long
short e
long e
short g
long g
bank
+

format

## 4 digits after decimal.

14 digits after decimal.
5 digits plus exponent.
15 digits plus exponent.
5 total digits with or without exponent.
15 total digits with or without exponent.
fixed format for dollars and cents.
the symbols +, - and blank are printed for
positive, negative and zero elements.
default format. Same as format short.

spacing:
format compact

format loose

48

## 3.2 CONDITIONAL CONTROL STRUCTURES

Fundamentals
Conditional control structures are used to select different paths (branching)
depending on the value of some computed variables. For example, lets assume
we want to buy a number of box cars for a railroad company. The dealer tells us
that that the price of each box car depends on the number of items we purchase.
If we buy 3 or less, the price is 22K each; if we buy between 4 and 10, the
price is 20K each and finally, if we buy more than 10, the price is 19K each.
Now we want to write a function file to calculate the cost of purchase as a
function of the number of box cars.
We can write a program called box_car_cost.m in the following way:
function cost = box_car_cost(number_of_cars);
%This program calculates the cost of buying
%a number of box cars
%
%The only input (number_of_cars) is the
%number of box cars
%
%The only output (cost) is the cost of purchase
Low_price = 19;
Medium_price = 20;
High_price = 22;
if number_of_cars > 10
cost = Low_price * number_of_cars;
elseif number_of_cars > 3
cost = Medium_price * number_of_cars;
else
cost = High_price * number_of_cars;
end
We see that the if construct has allowed the value of the variable
number_of_cars to determine which block of code to be executed and
which blocks to be skipped over.

49

## The if construct has the following form

If (control expression 1)
Statement
Statement

Statement
Statement

else
Statement
Statement

end

block 1

block 2

block 3

## Control expressions dictate which block of code will be executed. If control

expression 1 is True, then the program executes the statements in block
1 and then skips to the first executable statement following the end statement.
Otherwise the program checks for the status of control expression 2. If
control expression 2 is True, then the program executes the statements
in block 2 and then skips to the first executable statement following the end
statement. If all the control expressions are False, then the program executes
the statements in the block associated with the else clause.
There can be any number of elseif clauses (0 or more) in an if construct,
but there can be at most one else clause. The control expression in each clause
will be tested only if the control expressions in every clause before it are all
False. Once one of the control expressions is True, the corresponding block
of statements is executed, and the program skips to the first executable statement
following the end statement. If all the control expressions are False, then the
program executes the statements in the block associated with the else clause.
If there is no else clause, then execution continues after the end statement
without executing any part of the if construct.
Remember to indent the body of an if construct by a few spaces to improve the
Control expressions make use of relational and logical operators. These are now
explained.

50

Relational operators
A relational operator compares two values and yields a True or False result.
MATLAB relational operators are:
Operator
==
~=
>
>=
<
<=

Meaning
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to

For example, the value of the expression 5>3 is True and the value of the
expression 5<3 is False.
Logical operators
Logical operators provide a method for combining or negating relational
operations. A logical operator yields a logical result of either True or False.
MATLAB logical operators are:
Operator
~
&
|

Meaning
Not
And
Or

A logical statement containing the And operator (&) is True if both its
arguments are True. Otherwise, it is False. That is,
expression expression expression
A
B
A&B
True
True
True
True
False
False
False
True
False
False
False
False
For example, the expression 5>3 is True and the expression 2==1+3 is
False. Therefore, the expression 5>3 & 2==1+3 is False.
A logical statement containing the Or operator (|) is True if one or both of its
arguments are True. In other words, it is only False if both its arguments are
False. That is,

51

## expression expression expression

A
B
A|B
True
True
True
True
False
True
False
True
True
False
False
False
For example, the expression 5>3 is True and the expression 2==1+5 is
False. Therefore, the expression 5>3 | 2==1+5 is True.
The Not (~) operator negates its argument. A True argument is made False
and a False argument is made True. That is,

expression expression
A
~A
True
False
False
True
For example, the expression 2 == 1+5 is False. Therefore, the expression
~(2 == 1+5) is True.
Example
Write a MATLAB function to evaluate the value of z = f(x,y) for any
scalar values of x and y, where the function f(x,y) is defined as follows:
x y

2
x y
f ( x, y ) 2
x y
x2 y 2

x 0 and y 0
x 0 and y 0
x 0 and y 0
x 0 and y 0

## Also calculate the square root of the absolute value of z = f(x,y).

function [z, square_root_of_abs_z] = function_of_x_and_y(x,y)
%This function calculates the value of f(x,y) defined as

%
%
%
%
%
%
%

f(x,y) =

|
|x +
|x +
|x^2
|x^2
|

y
y^2
+ y
+ y^2

x>=0 & y<0
x<0 & y>=0
x<0 & y<0

52

## %The first input argument is the value of x

%The second input argument is the value of y
%Both x and y must be scalars
%
%The first ouput argument is the value of f(x,y)
%The second output argument is the square root of
the %absolute value of f(x,y)
%
%Example: [z1, z2] = function_of_x_and_y(10,11)
if (x>=0 & y>=0)
z = x + y;
elseif(x>=0 & y<0)
z = x + y^2;
elseif(x<0 & y>=0)
z = x^2 + y;
else
z = x^2 + y^2;
end
square_root_of_abs_z = sqrt(abs(z));
It should be noted that sqrt is a standard MATLAB function for calculating
the square root of a number and abs is a standard MATLAB function for
calculating the absolute value of a number.

## The error statement

The command error('message') stops the execution of a program and
displays the error message on the screen.
For example, consider the program box_car_cost.m, which we have already
discussed. Obviously the number of cars cannot be negative. We can therefore
use the error function to stop the execution of the program if someone assigns
a negative value to the variable number_of_cars.
function cost = box_car_cost(number_of_cars);
%This program calculates the cost of buying
%a number of box cars
%The only input (number_of_cars) is the
%number of box cars
%The only output (cost) is the cost of purchase

53

if (number_of_cars < 0)
error('number of cars cannot be negative')
end
Low_price = 19;
Medium_price = 20;
High_price = 22;
if number_of_cars > 10
cost = Low_price * number_of_cars;
elseif number_of_cars > 3
cost = Medium_price * number_of_cars;
else
cost = High_price * number_of_cars;
end
Now if you run the program with a negative argument, you will get the
following error message.
>> cost = box_car_cost(-15)
??? Error using ==> box_car_cost
number of cars cannot be negative
3.3 REPETATIVE CONTROL STRUCTURES
Loops are MATLAB constructs that allow us to execute a block of statements
more than once. MATLAB provides two forms of loop constructs:
1. The for loop, which repeatedly executes a block of statements a definite
number of times.
2. The while loop, which repeatedly executes a block of statements as long
as some condition is satisfied.
The while structure is most appropriate when the number of iterations in the
loop is not known beforehand. In contrast, the for structure should be used
when the number of iterations is known.
We will now explain these two constructs in more detail.
3.3.1 The For loop
Fundamentals
The for loop will execute a block of statements a fixed number of times. The
general form of the for loop is
54

## for index = first:increment:last

statement
statement

end
statement
where index is called the loop variable (or loop index). The statements
between the for statement and the end statement are referred to as the body of
the loop.
The loop variable (index) is initialised with the value first. Each time
through the for loop, increment will be added to index. The termination
condition is that index will be greater than last if increment is positive,
or smaller than last if increment is negative. The following two examples
will demonstrate how a for loop works.
>> for XX=1:0.5:4
disp(XX)
end
1
1.5000
2
2.5000
3
3.5000
4
and
>> for XX=5:-1:2
disp(XX)
end
5
4
3
2

55

## It should be noted that if the increment is equal to unity, it can be eliminated.

Therefore, for II=5:1:12 and for II=5:12 are equivalent.
Now lets write a script file to calculate the sum of squares of all the odd
numbers between 11 and 46. Call this program sum_of_squares.m.
%This script file (sum_of_squares.m) calculates
%the sum of the squares of all the elements of
%an array defined in this program.
%XX is an array whose elements
odd %numbers between 11 and 46.
XX = 11:2:46;

are

all

the

## %determine the total number of elements in array XX

N_XX = length(XX);
sum_of_terms = 0;

%initialise sum_of_terms

for II = 1:N_XX
sum_of_terms = sum_of_terms + XX(II)^2;
end
disp('sum of the elements of array XX squared')
disp(sum_of_terms)
Now type sum_of_squares on the command line to calculate the sum.
It should be noted that we have used the standard MATLAB function length
to calculate the total number of elements in array XX. This is necessary as we
should tell MATLAB how many times the for loop is to be repeated. Also note
that sum_of_terms must be given an initial value before the for loop starts.
The initial value of sum_of_terms must be zero. This is so because in the
statement sum_of_terms = sum_of_terms + XX(II)^2, for II=1,
sum_of_terms must be equal to XX(1)^2. This is only possible if the initial
value of sum_of_terms is set equal to zero.
Remember to indent statements inside a for loop by a few spaces to improve
the readability of the code. Also note that the loop index of a for loop should
not be changed anywhere within the loop. This will lead to strange errors which
are very difficult to find.

56

Nested Loops
It is possible for one loop to be completely inside another loop. If one loop is
completely inside another one, the two loops are called nested loops. Lets write
a program called body_mass_index_table.m which calculates the body
mass index for a range of heights and weights.
%This script file (body_mass_index_table.m) calculates
%the body mass index for a range of heights and weights
disp('

height

weight

bodymassindex')

for height=1.50:0.10:1.90
for weight=50:10:90
bodymassindex = weight/height^2;
disp([height weight bodymassindex])
end
end

Now type body_mass_index_table on the command line and you will get
the following results.
>> body_mass_index_table
height
weight bodymassindex
1.5000
50.0000
22.2222
1.5000
60.0000
26.6667
1.5000
70.0000
31.1111
1.5000
80.0000
35.5556
1.5000
90.0000
40.0000
1.6000
50.0000
19.5312
1.6000
60.0000
23.4375
1.6000
70.0000
27.3437
1.6000
80.0000
31.2500
1.6000
90.0000
35.1562
1.7000
50.0000
17.3010
1.7000
60.0000
20.7612
1.7000
70.0000
24.2215
1.7000
80.0000
27.6817
1.7000
90.0000
31.1419
1.8000
50.0000
15.4321
1.8000
60.0000
18.5185
1.8000
70.0000
21.6049
1.8000
80.0000
24.6914
1.8000
90.0000
27.7778
1.9000
50.0000
13.8504
1.9000
60.0000
16.6205
1.9000
70.0000
19.3906
1.9000
80.0000
22.1607
1.9000
90.0000
24.9307

57

It is noted that in the first for loop the variable height is incremented from
1.50 to 1.90 in steps of 0.1. Then, for each fixed value of height, the
variable weight will change from 50 to 90 in steps of 10.

## The break Statement

There are times when you want to break out of a loop because some special
condition has arisen. If a break statement is executed within the body of a loop,
execution of the program is transferred to the first statement after the end
statement of the loop. For example, save the following program as
test_break.m
%This script file (test_break.m) demonstrates
%the effect of a break statement in a for loop.
for ii=1:5
yy = ii^5;
if (yy > 1000)
break
end
disp('ii = ')
disp(ii)
end
disp('MATLAB has finished executing the for loop' )
disp(' ')
disp('After executing the for loop, the loop index ii is equal to')

disp('ii = ')
disp(ii)
Now run the program by typing test_break on the command line. You will
get the following output.
>> test_break
ii =
1
ii =
2
ii =
3
MATLAB has finished executing the for loop

58

## After executing the for loop, the loop index ii is

equal to
ii =
4
The output shows that for ii=4, yy is greater than 1000 and therefore the
control was transferred to the first executable statement after the end statement
of the for loop, which simply displays the message MATLAB has
finished executing the for loop. That explains why ii = 1,
ii = 2 and ii = 3 are printed inside the loop, while ii = 4 and ii =
5 are not.
If the loops are nested, the break statement would only terminate the
innermost loop containing the break statement.
3.3.2 The while loop
The while loop executes a block of statements repeatedly as long as some
condition is satisfied. The general form of a while loop is:
While control expression
statement
statement

end
statement
If the control expression is True, the block of statements inside the
loop will be executed. When the end statement is reached, control returns to
the while statement. If the control expression is still True, the block
of statements inside the loop will be executed again. This process will be
repeated until the control expression becomes False. Once the control
expression becomes False, control is transferred to the first statement after the
end statement. As an example, we can write a program to add up a number of
measurements when we have not counted how many measurements we have
%This script file (add_up_numbers.m) calculates the sum of a
%set of numbers which are entered at the keyboard.
disp('enter all the numbers you want to add up; then enter 0 to stop.')

59

sum_x = 0;

%initialise sum_x

## %You must give an initial value to x so that the while loop

%can start

x = 1;
while (x ~= 0)
x = input('enter a number: ')
sum_x = sum_x + x
end
Now you can run your program by simply typing its name on the command line.
An example follows:
enter all the numbers you want to add up; then enter 0 to stop.

enter a number:
x =
1.5000
sum_x =
1.5000
enter a number:
x =
2.5000
sum_x =
4
enter a number:
x =
3.7860
sum_x =
7.7860
enter a number:
x =
0
sum_x =
7.7860

1.5

2.50

3.786

Note that both sum_x and x must be given initial values before the while loop
starts. The initial value of sum_x must be zero. This is so because in the
statement sum_x = sum_x + x, once the first x value has been entered,
sum_x must be equal to the entered value. This is only possible if the initial
value of sum_x is set equal to zero. On the other hand, the control expression of
the while loop says that the loop will be carried out only if x is different from
60

zero. Therefore, any non-zero number can be used to initialise x. Note that this
initial value of x just serves to start the while loop and does not have any
effect on the value of sum_x. The reason for this is that before sum_x is
calculated, a new x value is entered at the keyboard.
Remember to indent statements inside a while loop by a few spaces to improve
Example
Write a MATLAB function to evaluate the values of z = f(x,y) for all
[xi,yi] values, i=1,2,3, , n, where x and y are two vectors of the
same length. The function f(x,y) is defined as follows:
x y

2
x y
f ( x, y ) 2
x y
x2 y 2

x 0 and y 0
x 0 and y 0
x 0 and y 0
x 0 and y 0

Also calculate the square root of the absolute value of z = f(x,y). Use a
for loop to solve this problem.
Solution
function [z, square_root_of_abs_z] = function_x_y_vector(x,y)
%This function calculates the value of f(x,y) defined as
%
|
%
|x + y
x>=0 & y>=0
%
|x + y^2
x>=0 & y<0
% f(x,y) = |x^2 + y
x<0 & y>=0
%
|x^2 + y^2
x<0 & y<0
%
|
%
%The first input argument is the value of x
%The second input argument is the value of y
%x and y are vectors of the same length
%
%The first ouput argument is the value of f(x,y)
%The second output argument is the square root of the
%absolute value of f(x,y)
%
%Example: [z1, z2] = function_x_y_vector([10,11],[9 -20]);
n1 = length(x);
n2 = length(y);
if (n1 ~= n2)
disp('the two inputs are not of the same length')
disp('the smaller of the two have been taken as the number of points')
disp(' ')

61

n_points = min(n1,n2);
else
n_points = n1;
end
%Create two all-zero horizontal arrays with n_points elements
%in each of them.
%The following two commands are not essential. They will, however,
%speed up the for loop significantly as MATLAB does not have
to %adjust the size of the variables z and square_root_of_abs_z in
each
%iteration of the for loop. The real values of these two variables
%are calculated inside the for loop, and these real values will then
%replace
the
initial
zero
values.
Therefore,
the
following
two %commands are just used to establish the size of the variables z
and %square_root_of_abs_z. Their real values will be calculated
inside %the for loop.
z = zeros(1,n_points);
square_root_of_abs_z = zeros(1,n_points);
for ii=1:n_points
if (x(ii)>=0 & y(ii)>=0)
z(ii) = x(ii) + y(ii);
elseif(x(ii)>=0 & y(ii)<0)
z(ii) = x(ii) + y(ii)^2;
elseif(x(ii)<0 & y(ii)>=0)
z(ii) = x(ii)^2 + y;
else
z(ii) = x(ii)^2 + y(ii)^2;
end
square_root_of_abs_z(ii) = sqrt(abs(z(ii)));
end

4: MATLAB GRAPHICS
In this session we will discuss a few more functions for 2-D and 3-D plots. We
will also briefly touch on the subject of chaos and fractals. We will see that very
simple programs can lead to amazingly complex and beautiful pictures. We can
also use MATLAB to create animation by displaying a succession of figures,
where each figure is only slightly different from the figure immediately before it.
We will use this technique to make a clip in which a beautiful supermodel spring
will dance for us!
4.1 2-D PLOTS

Function plot
You have already learned how to use the function plot. However, for
completeness, this function will be defined again. The general form of this
function is
62

plot(x_values, y_values,style_option)
Various line styles, marker types and colours may be obtained
with style_option where style_option is a character string made
from one element from any or all of the following 3 columns:
Colour
b blue
g green
r red
c cyan
m magenta
y yellow
k black

Marker type
. point
o circle
x x-mark
+ plus
* star
s square
d diamond
v
^
<
>

p
h

Line styles
- solid
: dotted
-. dashdot
-- dashed

triangle (down)
triangle (up)
triangle (left)
triangle (right)

pentagram
hexagram

For example, plot(x,y,'c+:') plots y vs. x with a cyan dotted line where
each data point is marked with a plus; plot(x,y,'bd') plots y vs. x with a
blue diamond at each data point but does not draw any line. When
no style_option is specified, MATLAB uses a blue solid line as the
default value.
plot(x1,y1,style_option_1,x2,y2,style_option2,...)
combines the plots defined by plot(x1,y1,style_option_1) and
plot(x2,y2,style_option_2) in the same graph. For example, the
command plot(x,y,'y-',x,y,'go') plots the data twice; the first time
it draws a solid yellow line going through the (x,y) data points and the second
time it shows the position of each (x,y) data point by a green circle.
To remind yourselves of how to use the functions xlabel, ylabel,
title, grid on, grid off and axis square, refer to Section 1.4

Function legend
You can use function legend to produce a legend on your plot. As an example,
try the following

63

x = 0:0.2:10;
y1 = x.^2;
y2 = x.^3;
figure,plot(x,y1,'ko',x,y2,'r*'),grid on, axis square
legend('2nd order polynomial','3rd order polynomial')

1000

900

800

700

## 2nd order polynomial

3rd order polynomial

600

500

400

300

200

100

10

You can change the position of the legend with the mouse by first left clicking
the legend and then dragging it.

Function axis
Once you have produced a plot, you can use the function axis to change the x
and y axes limits. The general form of this command is
>> axis([x_min x_max y_min ymax])
For example, lets assume that the foregoing figure is your current (active)
figure, then if you type the following command
>> axis([4 6 0 300])
You will get the following figure, in which the x axis is shown between 4 and 6
and the lower and upper limits of the y axis are 0 and 300, respectively.

64

300

250

## 2nd order polynomial

3rd order polynomial

200

150

100

50

4.2

4.4

4.6

4.8

5.2

5.4

5.6

5.8

In order to make figure number n your active (current) figure, use the following
command
>> figure(n)
Function fplot
In addition to the function plot, the hybrid function fplot can be used to
produce 2-D plots. We call it because it either allows the built-in functions as
with
>> figure,ezplot('sin(x).^3 + 2*cos(x).^2',[-pi pi])

## or calls a users own function M-file (see fplot_example.m below).

The command fplot(FUN,[x_min x_max], style_option) plots
the function FUN between the x-axis limits specified by [x_min x_max]. The
name of the function FUN must be given in single quotes. Various line types,
marker types and colours may be obtained with style_option as
described previously. For example,
>> figure,fplot('sin(x).^3 + 2*cos(x).^2',[-pi pi],'.')

65

1.5

0.5

-0.5

-1

-3

-2

-1

## It should be noted that the function fplot is adaptive, meaning that it

calculates and displays more data points in the regions where the slope of the
function being plotted is changing most rapidly.
As remarked, you can create a function M-file and then use the name of the Mfile with fplot. For example, create the following function M-file, named
fplot_example.m, that returns a two column matrix Y:
function Y = fplot_example(X)
%The output of this function (Y) is a two column matrix,
%where each column is a function of X.
%The two functions are calculated at values
%given by the input argument X.
%The following command converts the horizontal vector X to
a %column vector. On the other hand, if X is already
vertical, %it will remain unchanged. In other words, use the
following %command to make sure X is a vertical vector.
X = X(:);

## %Y is a two column matrix, where each column has the

%same number of elements as X.
Y = zeros(length(X),2);
%Each column of Y defines a separate function of X.
Y(:,1) = 200*sin(X)./X;
%the first column of Y
Y(:,2) = abs(X).^(pi/1.5); %the second column of Y
Now, Plot the function with the following statement:
>> fplot('fplot_example',[-20 20],'.')
66

## >> axis square

Function plotted by fplot
600

500

Y1 and Y2

400

300

200

100

-100
-20

-15

-10

-5

0
x

10

15

20

As observed, both columns of the output matrix Y are plotted in the same figure.
In the foregoing command, the first input argument of the function fplot is the
name of the function to be plotted in single quotes, the second one is the range
of the variable X and the third one is the symbol or the line type used in the
graph.
4.2 3-D PLOTS

Line plots
A three-dimensional line plot can be created with the function plot3. This
function is similar to the two dimensional plot function, except that each point
is represented by x, y and z values instead of just x and y values. The
following example will demonstrate how to use this function.
t=0:0.05:15;
x=exp(-0.05*t).*cos(2*t);
y=exp(-0.05*t).*sin(2*t);
z=t;
figure,plot3(x,y,z,'.')
xlabel('x (meters)')
ylabel('y (meters)')
zlabel('z (meters)')
title('Three-dimensional line plot')
67

## grid on, axis square

Three-dimensional line plot

15

z (meters)

10

0
1
0.5

1
0.5

0
0
-0.5
y (meters)

-0.5
-1

-1
x (meters)

## Surface plots, Mesh plots and Contour plots

A surface is usually defined by a function of two independent variables; For
example, the function z = f(x,y), where x and y are two independent
variables and the function f is used to calculate z for each pair of (x,y) values.
Therefore, to create a surface plot, we first need to generate a grid of (x,y)
points and then find the value of z at each point of this grid. The function
meshgrid makes it easy to generate a grid of (x,y) values for surface plots.
The general form of this function is
[x y] = meshgrid(xstart:xinc:xend,ystart:yinc:yend)
for example, the following commands
>> [xx yy] = meshgrid(1:1:4,2:0.5:5);
figure,plot(xx,yy,'bo')
title('Grid generated by function meshgrid','Fontsize',16)

will generate the following xx and yy matrices and also the following plot.

68

xx =
1
1
1
1
1
1
1

2
2
2
2
2
2
2

3
3
3
3
3
3
3

4
4
4
4
4
4
4

yy =
2.0000
2.5000
3.0000
3.5000
4.0000
4.5000
5.0000

2.0000
2.5000
3.0000
3.5000
4.0000
4.5000
5.0000

2.0000
2.5000
3.0000
3.5000
4.0000
4.5000
5.0000

2.0000
2.5000
3.0000
3.5000
4.0000
4.5000
5.0000

5

4.5

3.5

2.5

1.5

2.5

3.5

## The xx and yy matrices can then be used to calculate corresponding zz values,

which can then be plotted using the functions surf or mesh. The following
example clears the situation.
t1 = -2:0.1:2;
t2 = -2:0.1:2;
[x y] = meshgrid(t1,t2);
z = (x.^2) + (y.^2) -0.5*(x.^2).*(y.^2);
figure,surf(x,y,z)

69

The function mesh creates a surface which has a wire-frame appearance, while
the function surf creates a surface which looks more like a real surface. The
following example demonstrates the difference between functions mesh and
surf and also shows an application of the functions contour and contourf.
A contour plot is the level curves of the function z. The general form of the
function contour is contour(x,y,z,v), where vector v refers to the
height of the level curves.
t1 = -2:0.1:2;
t2 = -2:0.1:2;
[x y] = meshgrid(t1,t2);
z = exp(-0.5*(x.^2 + y.^2));
figure,mesh(x,y,z)
xlabel('x','Fontsize',14),ylabel('y','Fontsize',14)
zlabel('z','Fontsize',14)
title('Plotted by function mesh','Fontsize',14)
figure,surf(x,y,z)
xlabel('x','Fontsize',14),ylabel('y','Fontsize',14)
zlabel('z','Fontsize',14)
title('Plotted by function surf','Fontsize',14)
figure,contour(x,y,z,[0.1:0.1:1.9])
axis square
xlabel('x','Fontsize',14),ylabel('y','Fontsize',14)
zlabel('z','Fontsize',14)
70

## title('Plotted by function contour','Fontsize',14)

figure,contourf(x,y,z,[0.1:0.1:1.9])
axis square
xlabel('x','Fontsize',14),ylabel('y','Fontsize',14)
zlabel('z','Fontsize',14)
title('Plotted by function contourf','Fontsize',14,'Fontweight','Bold')

71

2

1.5

0.5

-0.5

-1

-1.5

-2
-2

-1.5

-1

-0.5

0.5

1.5

72

2

1.5

0.5

-0.5

-1

-1.5

-2
-2

-1.5

-1

-0.5

0.5

1.5

## The command contour(x,y,z,N) draws N contour lines; try it.

4.3 Fractals And Chaos
Some simple programs which are based on the theory of chaos and fractals can
lead to amazing pictures. For example, the following simple program will plot a
leaf for you. The theory of this subject is beyond this course; however, it shows
that sometimes very simple rules (mechanisms) can lead to very complicated
phenomenon.
function fractal_leaf(number_of_points)
%example: fractal_leaf(10000)
Mat1
Mat2
Mat3
Mat4
Vector1
Vector2
Vector3
Vector4
Prob1
Prob2

=
=
=
=
=
=
=
=
=
=

[0 0;0 0.16];
[0.85 0.04;-0.04 0.85];
[0.2 -0.26;0.23 0.22];
[-0.15 0.28;0.26 0.24];
[0;0];
[0;1.6];
[0;1.6];
[0;0.44];
0.01;
0.85;
73

Prob3
Prob4
P
x
y

=
=
=
=
=

0.07;
0.07;
[0;0];
zeros(1,number_of_points);
zeros(1,number_of_points);

prob
= rand(number_of_points,1);
for counter = 1:number_of_points
if prob(counter)<Prob1
P=Mat1*P+Vector1;
elseif prob(counter)<Prob1+Prob2
P=Mat2*P+Vector2;
elseif prob(counter)<Prob1+Prob2+Prob3
P=Mat3*P+Vector3;
else
P=Mat4*P+Vector4;
end
x(counter)=P(1);
y(counter)=P(2);
end
figure,plot(x,y,'r.')
axis equal, axis off

74

75

## 4.4 Making Movies

If you have a series of figures that show the state of a system at successive instants of time,
then you can use MATLAB to animate them. To do this you should first use the function
getframe to save each figure as a movie frame in an array, say M. Therefore, M would be an
array whose successive elements are the successive frames of the movie. You can then use the
function movie to animate your plots. The general format of the function movie is
>> movie(M,Number_of_times_movie_played,number_of_frames_per_second)

Example 1
The following function will produce a number of figures showing the successive positions of
a bullet, which has been fired at a given speed and at a given angle with the ground. These
figures will be saved in Matrix M and will later be shown as a movie. Save the following
function M-file as bullet_movie.m. Then run it as will be explained later.
function M = bullet_movie(initial_velocity,initial_angle,number_of_frames)
%The program bullet_movie.m will produce a set of figures of the position
%of a bullet, which can later be shown as a movie.
%
%The first input argument is the initial velocity of the bullet (m/sec)
%The second input argument is the angle with the ground at which the
%bullet is fired (degrees)
%The third input argument is the number of frames (figures) between the moment of %shooting and the
moment the bullet hits the ground.
%
%The output argument is a matrix whose elements are the
%figures to be used in the movie
%
%Example: bullet_matrix = bullet_movie(100,20,24);
%
%The horizontal and vertical coordinates of the bullet are calculated according to
%the following equations.
%xx = initial_velocity*cos(initial_angle)*time
%yy = initial_velocity*sin(initial_angle)*time -gravitational_constant*time^2/2;
g = 9.81;
%m/sec^2
initial_angle = initial_angle*pi/180; %convert the angle into radians
time_to_impact = 2*initial_velocity*sin(initial_angle)/g;
time = linspace(0,time_to_impact,number_of_frames);
%The horizontal coordinate as a function of time
xx = initial_velocity*cos(initial_angle)*time;
%The vertical coordinate as a function of time
yy = initial_velocity*sin(initial_angle)*time - g*time.^2/2;
%The range of the bullet; i.e. the horizontal distance of the point the bullet
%hits the ground.
max_xx = initial_velocity^2*sin(2*initial_angle)/g;
%maximum height of the bullet
max_yy = (initial_velocity*sin(initial_angle))^2/(2*g);
76

## %Calculate max_axis used for scaling the figures

max_axis = max([max_xx max_yy]);
for JJ=1:number_of_frames
plot(xx(JJ),yy(JJ),'o')
grid on
axis square
%use axis to make sure all figures have the same scale for xx and yy coordinates
axis([0 max_axis 0 max_axis])
M(JJ) = getframe;
end
Now type the following commands at MATLAB prompt
>> figure
>> bullet_matrix = bullet_movie(100,20,36);
>> movie(bullet_matrix,4,48)
The command bullet_matrix = bullet_movie(100,20,36) produces 36 figures,
displaying the position of the bullet at different times between the moment of shooting and
the moment the bullet hits the ground, and saves them in bullet_matrix. The command
movie(bullet_matrix,4,48) will show this series of pictures 4 times at the speed of
48
frames
per
second.
On
the
other
hand,
the
command
movie(bullet_matrix,5,12)will show the same series of figures 5 times and at the
speed of 12 frames per second. If in the command
>> movie(bullet_matrix,Number_of_times_movie_played,frames_per_second)

## the value of Number_of_times_movie_played is negative, each "play" would be

once forward and once backward. Try the following
>> movie(bullet_matrix,-5,120)

77

## Example 2 (dancing spring)

Save the following code in a program called spring_movie.m
function M = spring_movie(number_of_frames)
%The program spring_movie.m will produce a set of figures of a spring
%which expands and contracts.
%The only input argument is the number of frames (figures) for one cycle
%of the spring expansion and contraction.
%The output argument is a matrix whose elements are the figures
%to be used in the movie
%Example: spring_matrix = spring_movie(20);
number_of_rings = 4;
diameter = 2;
%diameter of the spring in meters
static_height = 1;
max_dynamic_height = 0.30;
oscillation_period = 5;
%Seconds
%Determine the x and y coordinates
polar_angle = 0:pi/60:number_of_rings*(2*pi);
time = linspace(0,oscillation_period,number_of_frames);
%to make sure all the figures have got the same scale
max_z = ceil((static_height+max_dynamic_height)*max(polar_angle));
angular_frequency = 2*pi/oscillation_period;
for JJ=1:number_of_frames
dynamic_height = max_dynamic_height*cos(angular_frequency*time(JJ));
zz = (static_height + dynamic_height)*polar_angle;
plot3(xx,yy,zz,'.')
grid on
axis([-1 1 -1 1 0 max_z])
M(JJ) = getframe;
end
Now type the following commands at the prompt
>> figure, spring_matrix = spring_movie(20);
Then try the following two commands to see the difference between them.
>> movie(spring_matrix,4,24)
>> movie(spring_matrix,12,120)

78

=====================================================
Module Code:
Module Name:

MATH286
Numerical and Statistical Analysis for
Engineering with Programming

## M286 Text Books:

[1] Griffiths D V and Smith I M, Numerical Methods for Engineers, Blackwell, 1991.
[2] Laurene Fausett, Applied Numerical Analysis Using MATLAB, Pearson 2008.
Reference Books: plus Distributed Notes (plus Web Notes from google.com + wiki)
[3] Moin P, Fundamentals of Engineering Numerical Analysis, Cambridge University
Press, 2001.
[4] Wilson HB, Turcotte LH, Advanced mathematics and mechanics applications using
MATLAB. CRC Press, 1997
[5] Ke Chen, Peter Giblin and Alan Irving , Mathematical Exploration with MATLAB,
Cambridge University Press, 1999.

## ================= Class Tests 48% + 52% Summer Exams =================

Acknowledgements
The M286 lecturers wish to thank
Dr. Nilanjan Chakraborty (MECH213) and
Dr. Hossein Najafian (CIVE272) for sharing their lecture notes and Prof. Ken Badcock for various
suggestions and discussions on the module, as well as other Maths and Engng lecturers in the past!