Professional Documents
Culture Documents
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.
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
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
Wed receive
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
+ for addition
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
>>
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).
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
0.3142
0 .6283
1.5708
1.2566
0.5878
0.8090
0.9511
1.0000
10
>> y(3:-1:1)
ans =
0.5878
0.3090
>> 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
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
>> 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
>> 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
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
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
3,
Exercises A
1.
2.
3.
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.
6.
18
90
1.5
120
60
1
150
30
0.5
180
210
330
240
300
270
19
Solutions A
1.
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.
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.
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.
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
x 2 + 2x + sin(x)
100
80
60
40
20
0
0
10
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
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
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]
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
>> 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
>> 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
[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
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
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
34
0.3280
0.5910
0.7370
D =
-0.5157
0
0
0
0.1709
0
0
0
11.3448
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
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
0.9093
0.1411
3.0000
1.5708
>> sin(x)
ans =
0
-0.7568
0.9093
-0.9589
0.1411
1.0000
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)
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
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
40
>> mean(mean(A))
ans =
6.5833
>> max(max(A))
ans =
14
>> min(min(A))
ans =
1
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
-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
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')
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
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.
Now type help hist to learn more about this function.
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
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.
short
long
short e
long e
short g
long g
bank
+
format
spacing:
format compact
format loose
48
49
else
Statement
Statement
end
block 1
block 2
block 3
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
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
%
%
%
%
%
%
%
f(x,y) =
|
|x +
|x +
|x^2
|x^2
|
y
y^2
+ y
+ y^2
52
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
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
are
all
the
%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.
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
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
made. Save the following script file in a file called add_up_numbers.m.
%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
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:
>> add_up_numbers
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
the readability of the code.
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
of your handouts.
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
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
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])
65
1.5
0.5
-0.5
-1
-3
-2
-1
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
15
z (meters)
10
0
1
0.5
1
0.5
0
0
-0.5
y (meters)
-0.5
-1
-1
x (meters)
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
4.5
3.5
2.5
1.5
2.5
3.5
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
71
1.5
0.5
-0.5
-1
-1.5
-2
-2
-1.5
-1
-0.5
0.5
1.5
72
1.5
0.5
-0.5
-1
-1.5
-2
-2
-1.5
-1
-0.5
0.5
1.5
=
=
=
=
=
=
=
=
=
=
[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
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
77
78
=====================================================
Module Code:
Module Name:
MATH286
Numerical and Statistical Analysis for
Engineering with Programming
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!