MATH286_NotesS1P1 2 Matlab 2
-
Upload
kirubhakaran2000 -
Category
Documents
-
view
223 -
download
0
Transcript of MATH286_NotesS1P1 2 Matlab 2
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
1/79
MATH286 -- Part1 Semester1FURTHER 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 ........................................................................................................... 543.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
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
2/79
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 MATrixLABoratory. It started life in the mid 1980sas 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 Startbutton (at the bottom left hand side
of the screen); then on the Install University Applications.
Choose the Category of Mathematicsfrom the drop-down menu to refine the
list of available software. Then select MATLAB2008and click Run. This willplace 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 thefollowing 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 enterkey.
Command History Window: The Command History Windowdisplays 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 Windowand 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 popupmenu will be displayed that allows you to delete, to copy or to evaluate the
selected commands.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
3/79
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 areavailable. 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 MATLABToolbarat 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 DesktopMenuallows you to determine which of the above windows youwant to be active. You can always go back to the default desktop configuration
through the Desktop Menuby clicking on DesktopLayout and then by
clicking on the Default.
1.2 Arithmetic Operations and Variable AssignmentMATLAB 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 Javarequire "compilation" of your program first.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
4/79
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 ordinarycalculator. That is, we would enter the following command in the MATLAB
command window at the prompt (>>) and press the enterkey:
>> 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 OurCostby typing thefollowing:
>> 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 isevaluated, MATLAB does the followings:
It chooses a memory location to store the value in
It gives the nameOurCost
to the memory location
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
5/79
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 theactual memory location is. We can use the variable name OurCostinstead of
334 for further calculations. For example, if the rolling stock manufactureroffered 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 andsize), 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 morereadable. For example, compare Estimated_costwith 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 bothvalid variable names, but the first one is more readable. Also remember thatonly 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.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
6/79
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 3to 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 enterkey 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
Windowand double-click it with the left mouse button.
The following symbols are used for arithmetic operations
^ for exponentiation (raising to a power)
/ for division
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
7/79
* for multiplication
- for subtraction
+ for addition
A common mistake made by first-time programmers is to omit themultiplication 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) + 1X =
96.1905>>
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
8/79
MATLAB calculates Xin the following manner.
MATLAB gives precedence to parentheses, and if there are nested
parentheses, it gives precedence to the innermost one. So (23+14.7-4/6) = 37.0333 is calculated first. Therefore,X would be equal
toX = 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 operationsinside these parentheses: addition and division. MATLAB gives
precedence to division over addition, so it first calculates2/3 and then
adds the results to1 to come up with1.6667. SoX would beX =
2*1.6667 + 2.5*(3*37.0333/3.5 + 5) + 1. NowMATLAB 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 calculates3*37.0333 and then divides the result by3.5.
Finally, it adds5 to the outcome to come up with36.7428. SoX
would be equal toX = 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 then2.5*36.7428 = 91.8570. So
X would be equal toX = 3.3334 + 91.8570 + 1.
MATLAB now calculates X by first adding 91.8570 to 3.3334 and
then adding 1to the outcome. So Xwould 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 7ft, external
lengths of 20ftand a wall thickness of 0.08ft. We can use the followingcommands.
>> 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 piby default. You could reassign any value to pi, but it is not
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
9/79
good practice. It is best to leave the value of pi, i, jand epswhich have
pre-assigned values unchanged. Also remember that length is the name of afunction in MATLAB and you should avoid using it as a variable name. Instead
use a variation of it such as length1or garden_length, etc.
1.3 Vectors in MATLAB
In MATLAB, an arrayis a collection of data values organised into rows and
columns. Although an arrayis 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 termvectoris usually used to describe anarray with only one dimension. A vector can either be horizontal or vertical.
1.3.1 Horizontal VectorsA 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 Awould be assigned to C. The output wouldbe,
C =3
Now, suppose we wanted to compute values of the sinfunction over the range
0 to pi/2 in steps of 0.1*pi. (The functionsin 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 xmust be in radians).
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
10/79
>> 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 0.5878 0.8090 0.9511 1.0000
Again, you can access individual elements of xand yusing that elements indexnumber. For example,
>> x(2)ans =
0.3142
>> z = 1 + x(3)z =
1.6283
Colon Notation
The shorthanda:b:c means ato cin steps of b. That is, typing 2:3:12is
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:cis 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 1.5708
>> x(1:3)ans =
0 0.3142 0 .6283
>> cc = x([2, 4, 5])cc =
0.3142 0.9425 1.2566
>> y = sin(x)
y = 0 0.3090 0.5878 0.8090 0.9511 1.0000
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
11/79
>> y(3:-1:1)ans =
0.5878 0.3090 0
Here the array yis accessed from element 3to element 1in 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 2 3 4 5
b =1 3 5 7 9
>> c = [b a]c =
1 3 5 7 9 1 2 3 4 5
>> d = [a(1:2:5) 1 0 1]d =
1 3 5 1 0 1
Function linspaceLinspaceis a built-in MATLAB function. The expressionlinspace(X1,
X2, N) generates Nequally-spaced points between X1and X2, starting with
X1and 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 arraydoes nothave 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 1to element number 0of vector awill lead to
>> a(0) = 1??? Index into matrix is negative or zero.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
12/79
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 VectorsThus 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 =
7510
Alternatively, we can code the following
>> Vvect = [7510];
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 vectorX into a vertical
vector. On the other hand, ifX is already a vertical vector, it leaves X
unchanged, so that the vectorY would always be a vertical vector, regardless
of the state ofX.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
13/79
1.3.3 Operations on arraysThis can be divided into scalar-array operations and array-array operations. A
scalar is a number such as 5or 6.71.
Scalar-Array Operations
The operations +,-,*, and/ are performed "element by element" whenused between a scalar and an array. For example,
>> A = [1 2 3 4 5];
>> A - 2ans =
-1 0 1 2 3
>> Z = 2 * A - 1 %note the precedence of multiplication over subtraction
Z =1 3 5 7 9
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 + BP =
5 7 9
>> Q = A - BQ =
-3 -3 -3
>> C = A.*BC =
4 10 18
>> D = A./BD =
0.2500 0.4000 0.5000
>> E = A.^BE =
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
14/79
1 32 729
Also note the following commands involving a vector and a scalar
>> F = A.^2 but not A^2F =1 4 9
>> T=2.*A or 2*AT =
2 4 6
>> S=A./2 or A/2S =
0.5000 1.0000 1.5000
>> U=2./A but not 2/AU =
2.0000 1.0000 0.6667
1.4 Simple graphsOne of the strong points of MATLAB is its extensive and device-independent
plotting capabilities. To produce a two-dimensional plot, just create two vectorscontaining the same number of elements and then use the plotfunction
Example 1:
Plot the function y = x25x + 1, for 0 x 10The following three statements are sufficient to create the plot. The first
statement creates a vector of xvalues between 0 and 10 using the colon operator.
The second statement calculates the yvalues from the xvalues. Note that xis
an array and that we have to use array operators so that ywould be calculated
for each xvalue 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 plotwill create a figure window in which a plot of y versus x
will be displayed. The previous commands will lead to the following plot.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
15/79
We now need to improve this figure by adding labels to the xand yaxes and bygiving 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
Now type the following command and see what will happen
>> grid on
As you see grid onturns the grid lines on and grid offturn them off.
0 2 4 6 8 10-10
0
10
20
30
40
50
60
0 2 4 6 8 10-10
0
10
20
30
40
50
60
x
y
Graph of y(x) = x2- 5x + 1
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
16/79
Now type axis squareto make the plot square in size.
>> axis square
The final plot should be like this
If you use the function plotagain 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 zversus
t to be displayed in a new figure window, you should include the command
figurebefore plot. The function figurewill 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, useclose all
If you want to close a few figures try the following:%The following command will close figure 2.Other %figures will remain open.close(2)
0 2 4 6 8 10-10
0
10
20
30
40
50
60
x
y
Graph of y(x) = x2- 5x + 1
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
17/79
%The following command will close figures 3, 4 and5. %Other figures will remain open.close(3:5)
%The following commands will close figures 3, 5and %8. Other figures will remain open.close([3 5 8])close([3, 5, 8])close([3; 5; 8])
Exercises A
1. What is the difference between 2 + 3 * 5and (2 + 3)*5?
2. Write MATLAB commands to evaluate the following expressions:
)2/(cos34
2
)1.0sin(
15
312)7)(5(2
2
360
32
60
3.2
53
2
4
52
2
3. Write MATLAB commands to set the value of the variable r to 5. Then
calculate the circumference of a circle of radius rand assign the value to an
appropriate name.
4. Plot the function cos(x)versus x for xin the range of 0and 2. Label
the xand yaxes and give the plot a title. Use the colon notation to generate
the xvalues.
5. Plot the function x2+ 2x + sin(x) versus x for x in the range of 0
and 2.Label the xand yaxes and give the plot a title. Use the functionlinspaceto generate the xvalues.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
18/79
6. Now plot the function x2+ 2x + sin(x)versus xfor xin the range of
0and 3in a new figure window. Label the xand yaxes and give the plot
a title. Use the function linspaceto generate the xvalues. 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 linspaceyou
used before. Then edit it and press the enterkey. 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 toexecute 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 yelement-by-element using the operator .*. Repeat the
exercise but this time generate six yvalues between 10and 15. Why doyou get an error message?
8. Try the following commands. The results would be the following
beautiful graph. Learn more about the function polarby typing help
polar in the command window. The function sqrt(x) means the
square root of xand the function abs(x)means the absolute value of x.
can we use the function plotrather than polarto get a similar graph?
>> theta = linspace(0,2*pi,800);>> distance = sqrt(abs(2*sin(5*theta)));>> figure,polar(theta,distance,'*')>>
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
19/79
0.5
1
1.5
30
210
60
240
90
270
120
300
150
330
180 0
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
20/79
Solutions A
1. What is the difference between 2 + 3 * 5and (2 + 3)*5?
>> 2 + 3 * 5ans =
17>> (2 + 3)*5ans =
25
2. Write MATLAB commands to evaluate the following expressions:
)2/(cos34
2)1.0sin(
15
312
)7)(5(2
2
360
32
60
3.253
2
4
52
2
>> 3^2 + 5ans =
14
>> 2.3^(2+5)ans =340.4825
>> 60/(2+3)ans =
12
>> (60+3)/2ans =
31.5000
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
21/79
>> -2*5*-7ans =
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 rand assign the value to anappropriate name.
>> r=5;>> circle_circumference = 2*pi*rcircle_circumference =
31.4159
4. Plot the function cos(x)versus x for xin the range of 0and 2. Label
the xand yaxes and give the plot a title. Use the colon notation to generate
the xvalues.
>> 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')
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
22/79
>> grid on>> axis square
5. Plot the function x2+ 2x + sin(x) versus x for x in the range of 0
and 2.Label the xand yaxes and give the plot a title. Use the function
linspaceto generate the xvalues.
>> 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
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
cos(x)
Variation of cos(x) with x
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
23/79
6. Now plot the function x2+ 2x + sin(x)versus xfor xin the range of
0and 3in a new figure window. Label the xand yaxes and give the plot
a title. Use the function linspaceto generate the xvalues. Set the gridson and make the plot square in size.
As this exercise is very similar to the previous one, rather than typing allthe commands again, use the key to find the command linspaceyou
used before. Then edit it and press the enterkey. 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 toexecute 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
0 1 2 3 4 5 6 70
10
20
30
40
50
60
x
x2
+2x+sin(x)
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
24/79
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 yelement-by-element using the operator .*. Repeat the
exercise but this time generate six yvalues between 10and 15. Why doyou get an error message?
>> x = linspace(0,1,5)x =
0 0.2500 0.5000 0.7500 1.0000>> y = linspace(10,15,5)y =
10.0000 11.2500 12.5000 13.7500 15.0000
>> z = x.*yz =
0 2.8125 6.2500 10.3125 15.0000
>> y = linspace(10,15,6)y =
10 11 12 13 14 15
>> z = x.*y??? Error using ==> .*
Matrix dimensions must agree.
0 2 4 6 8 100
20
40
60
80
100
120
x
x2
+2x+sin(x)
Variation of x2+ 2x + sin(x) with x
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
25/79
8.
Try the following commands. The results would be the following
beautiful graph. Learn more about the function polarby typing help
polar in the command window. The function sqrt(x) means the
square root of xand the function abs(x)means the absolute value of x.
can we use the function plotrather than polarto 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 -1 -0.5 0 0.5 1 1.5-1.5
-1
-0.5
0
0.5
1
1.5
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
26/79
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 frompopulations 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 MATLABis 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
DefinitionA matrix is a two-dimensional array; i.e., it is a collection of numbers organisedinto 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-3matrix,
654
321A
in MATLAB, matrix Acan be entered as:
>> A = [1 2 3; 4 5 6];
or
>> A = [1 2 34 5 6];
Now, if you type Aat the command prompt, you will get the following response,
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
27/79
>> AA =
1 2 34 5 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 Ais,
>> AA =
1 2 34 5 9
Sub-matricesA 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 Awhich are in rows m to nand columns r to s. In the following
example, a sub-matrix defined by rows 1and 2and columns 1and 3of matrix
Ais extracted.
>> B = A(1:2,[1 3])B =
1 34 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
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
28/79
The 1 in A(1,:)refers to the first row of matrix Aand the :means all itscolumns. Similarly, the colon in the following command means all the rows of
matrix Aand 2refers to the second column.
>> A(:,2)ans =
25
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 7.8]Horizontal_vector =
1.0000 3.1500 7.8000
>> Vertical_vector = [1; 3.15; 7.8]Vertical_vector =
1.00003.15007.8000
A scalar (single number) is a one-by-one matrix. A scalar does not needbrackets. For example,
>> Gravitational_constant = 9.806;
Square brackets with no elements between them define an empty (null)
matrix. Use MATLABs help facilities to learn more about empty
matrices. For example,
>> Empty_matrix = []Empty _matrix =
[]
Combining matricesMatrices can be combined as long as their sizes are compatible. In the following
examples, matrices Aand Bhave been combined to create new matrices.
>> A = [1 2 3; 4 5 6];
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
29/79
>> B = [7 8; 9 10];>> C = [A B]C =
1 2 3 7 8
4 5 6 9 10or
>> [A(1:2,1:2); B]ans =
1 24 57 89 10
2.1.2 Elementary Matrix Operations
Operations involving matrices and scalarsIf a scalar is added to or subtracted from a matrix, it will be added to orsubtracted from all its elements. For example,
>> A = [1 2 3; 3 4 5];>> A+5ans =
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.60000.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];
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
30/79
>> 3./Aans =
3.0000 1.5000 1.00001.0000 0.7500 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.5B =
1.0000 5.6569 15.588515.5885 32.0000 55.9017
Element-by-element operations between matrices of the same sizeWe 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+Bans =
6 810 12
>> A-Bans =
-4 -4-4 -4
>> D = A .* BD =
5 1221 32
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
31/79
>> E = A./BE =
0.2000 0.33330.4286 0.5000
>> F = A.^BF =
1 642187 65536
Matrix multiplicationSuppose matrix Cis the product of matrix Aand matrix B. Then, by definition,
Cij would be equal to the dot product of rowi of matrix A and column j of
matrix B. For example,
2222122121221121
2212121121121111
2221
1211
2221
1211
*babababa
babababaBAC
bb
bb
Baa
aa
A
Thus, to multiply two matrices, they must be compatible; i.e.,
Number of columns in 1st matr ix = Number of rows in 2nd matr ix
Matrix multiplication in MATLAB is very simple. For example,
>> A = [1 2; 3 4]; B = [5 6; 7 8];>> C = A * BC =
19 2243 50
You can raise a square matrix to an integer power. For example, A^2 is
equivalent to A*Aand A^3is equivalent to A*A*A.
>> A= [1 2; 3 4];>> B = A^3B =
37 5481 118
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
32/79
Note the difference between A^3 (calculated above) and A.^3. The first
command raises matrix Ato the third power (A^3 = A*A*A) while the second
command raises each element of matrix Ato the third power.
>> B = A.^3B =
1 827 64
2.1.3 Matrix Inversion
Let Abe a square n-by-nmatrix. If there is another n-by-nmatrix B suchthat
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 Aand 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.1667 0.41670.6667 -0.3333 -0.3333-0.3333 0.6667 0.1667
Now calculate the product of A and A_inverse to confirm that the resultwould be equal to the identity matrix.
>> C = A*A_inverseC =
1.0000 -0.0000 -0.00000 1.0000 00 0 1.0000
One way to determine whether a matrix is non-singular is to evaluate itsdeterminant, which is a property of a square matrix. If the determinant is non-
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
33/79
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, thefollowing set of three linear equations
122462
432
21
32
321
XXXX
XXX
can be represented as
12
6
4
024
210
132
3
2
1
X
X
X
or, in a more compact form as
12
6
4
;;
024
210
132
3
2
1
B
X
X
X
XA
BXA
where Ais the matrix of coefficients, Bis the right-hand side vector, and Xis thesolution 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 Xiwhich
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];
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
34/79
>> A_inverse = inv(A);>> X = A_inverse * BX =
4.6667
-3.33334.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\BX =
4.6667-3.33334.6667
Now confirm the validity of the foregoing solution by multiplying Aby X. The
result should be equal to vector B.
>> A*Xans =
4.0000
6.000012.0000
2.1.5 Eigenvalues and Eigenvectors
Lets assume Ais a square matrix. If there is a scalar and a vector vsuch that
vvA
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 Vwhose 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 32 4 5
3 5 6
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
35/79
>> [V,D] = eig(A)V =
0.7370 0.5910 0.32800.3280 -0.7370 0.5910
-0.5910 0.3280 0.7370
D =-0.5157 0 0
0 0.1709 00 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
matrixA
is11.3448
and its corresponding eigenvector is the third column of
matrix V. Now, confirm that matrix Amultiplied by an eigenvector is equal to itscorresponding 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.16920.3048
which is equal to
>> D(1,1)*V(:,1)ans =
-0.3801-0.16920.3048
2.1.6 Matrix Transpose
If Bis the transpose of matrix A, then bij= aji. In other words, the first column of
matrix Bwould be the same as the first row of matrix Aand so on and so forth.
For example,
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
36/79
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]A =
1 2 33 4 5
6 7 912 13 14
>> B=A'B =
1 3 6 122 4 7 133 5 9 14
2.1.7 Special MatricesThe function zeros takes two arguments, m and n, and returns an m-by-nmatrix of zeros. For example,
>> Fox = zeros(3,5)Fox =
0 0 0 0 00 0 0 0 00 0 0 0 0
The function ones takes two arguments, m and n, and returns an m-by-nmatrix of ones. For example,
>> Fox = ones(3,5)Fox =
1 1 1 1 11 1 1 1 11 1 1 1 1
The function eye takes two arguments, m and n, and returns an m-by-nidentity matrix. An identity matrix is a matrix with 1s on the diagonal and zeroselsewhere. For example,
>> Fox = eye(3,5)Fox =
1 0 0 0 00 1 0 0 00 0 1 0 0
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
37/79
2.1.8 Functions which perform element-by-element operations on matricesMost 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 0.1411
>> x=[0 2 3; 4 5 pi/2]x =
0 2.0000 3.00004.0000 5.0000 1.5708
>> sin(x)ans =
0 0.9093 0.1411
-0.7568 -0.9589 1.0000
The most important MATLAB functions which work on an element-by-element
basis on the input matrix are
Function Description
abs(x) Absolute Value, |x|sqrt(x) Square Root, x log(x) Natural logarithm, loge
x
exp(x) Exponential, exsin(x) Sine with xin radians, sin(x)cos(x) Cosine with xin radians, cos(x)tan(x) Tangent with xin radians, tan(x)asin(x) Inverse Sine with the result in radians, sin- (x)acos(x) Inverse Cosine with the result in radians, cos- (x)atan(x) Inverse Tangent with the result in radians, tan-1(x)sinh(x) Hyperbolic Sinecosh(x) Hyperbolic Cosinetanh(x) Hyperbolic Tangent
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
38/79
asinh(x) Inverse Hyperbolic Sineacosh(x) Inverse Hyperbolic Cosineatanh(x) Inverse Hyperbolic Tangentround(x) Rounds x to the nearest integer
To get a more complete list of MATLAB elementary functions type help
elfunat the MATLAB prompt.
2.1.9 Functions length, size, sum, mean, max, minThere 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 thenumber 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 determinethe number of rows and columns of a matrix. Forexample,
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14]A =
1 2 33 4 56 7 9
12 13 14
>> [m,n] = size(A)m =
4n =
3
The command ones(size(A)) will produce a matrix whose
size is equal to the size of matrix A and whoseelements are equal to unity. For example,
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
39/79
>> A = [1 2 3; 3 4 5; 6 7 9; 12 13 14];>> B = ones(size(A))B =
1 1 11 1 11 1 11 1 1
Also note the following useful command
>> C = zeros(size(A))C =
0 0 0
0 0 00 0 00 0 0
The function sum can be used to calculate the sum of the elements of ahorizontal or a vertical vector. For example,
>> x=[1 3 5 7];>> sum_x = sum(x)
sum_x =16
When the function sumis applied to a matrix, it returns a row vector containingthe 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 33 4 56 7 912 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 Acolumn-by-column. On the other hand, sum(A,2)calculates the sums
of the matrix elements row-by-row. For example,
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
40/79
>> sum_A = sum(A,1)sum_A =
22 26 31
>> sum_A = sum(A,2)sum_A =6122239
If you want to calculate the sum of all the elements of a matrix, you can use the
function sumtwo 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, maxand minin a manner similar to the function
sum. Function meancalculates 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 33 4 56 7 912 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
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
41/79
>> 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 randomsamples 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, mand n, and returns an m-by-
n 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 equalchance of being picked up by the function rand. For example, the following
command will generate a 3-by-5matrix of random numbers between 0and 1.
>> xx = rand(3,5)
xx =0.6721 0.6813 0.5028 0.3046 0.68220.8381 0.3795 0.7095 0.1897 0.3028
0.0196 0.8318 0.4289 0.1934 0.5417
Note that when you use the function rand to simulate (i.e., pick up) random
numbers between 0and 1, your results will be different from that of xxabove.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.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
42/79
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 multiplythe simulated numbers (xx)by (b-a)and then add ato them. For example,
use the following commands to simulate random numbers between 10and 85.
>> a=10; b=85; xx=rand(3,5); yy=(b-a)*xx + a
yy =60.4103 61.0958 47.7110 32.8463 61.166772.8589 38.4611 63.2104 24.2240 32.7073
11.4730 72.3847 42.1669 24.5073 50.6255
If you want to simulate integers between 20and 150, then you will use thefollowing commands
>> a=-20; b=150; xx=rand(3,5);>> yy=(b-a)*xx+ayy =
72.6372 126.7859 100.3727 15.7428 91.0830121.2067 123.1127 102.5977 88.2388 136.0464109.0900 -12.1738 23.8156 -4.1077 77.3836
>> zz=round(yy)zz =
73 127 100 16 91121 123 103 88 136109 -12 24 -4 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 integernumbers. The function roundrounds a real number toward its nearest integer.For example,
>> round(119.1)ans =
119
>> round(-19.8)
ans =-20
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
43/79
Functions ceil, floorand fixare also used for rounding numbers. Type thefollowing 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, mand n, and returns an m-by-
n matrix of random numbers taken from a standardised Gaussian (normal)
distribution. (A standardised distribution is a distribution whose mean is zeroand 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-5matrix of random numbers from astandardised Gaussian distribution.
>> xx = randn(3,5)
xx = 2.0211 0.2723 -1.6106 -2.0889 -0.16240.5018 0.3368 -1.0075 1.0461 -0.1758-1.9983 0.1378 -0.5144 0.2153 1.1022
If you intend to simulate random numbers from a Gaussian distribution whose
standard deviation is sigma_xand whose mean is mean_x, then you shouldfirst 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.0901 -0.0858 -1.4038 0.22150.5058 0.6481 -0.3083 -0.7092 -1.33260.3299 1.7347 1.4596 0.6330 0.7305
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
44/79
>> y=sigma_x*x+mean_xy =
192.9581 173.1973 173.2833 146.9244 179.4303185.1164 187.9621 168.8337 160.8168 148.3489
181.5986 209.6938 204.1930 187.6603 189.6097
2.2.3 Simple Statistical Analysis
Functions to calculate mean and standard deviation of dataYou can use functions mean and std to calculate the mean and standard
deviation of an array of numbers. For example, simulate 1000numbers 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 normaldistribution 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 toanother one).
HistogramsHistograms are one of the tools used in the analysis of data. Given a one-
dimensional 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 uniformly-
distributed random numbers between 1000 and 10000 and draw their
histogram with 20bins.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
45/79
>> 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')
It should be noted that everyone of you will end up with a somewhat differenthistogram from the one shown above. This is because we are simulating random
numbers and everyones set of 2500random numbers will be different from therandom numbers simulated by other people.
Now repeat this exercise, but change the number of random numbers to 100and
then to 1,000,000and compare the resultant histograms. You will see that asthe 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 thenumber of items in different bins would vary significantly.
We will now simulate 10000random numbers from a normal distribution withmean 175and standard deviation of 20and plot its histogram with 15bins.
1000 2000 3000 4000 5000 6000 7000 8000 9000 100000
20
40
60
80
100
120
140
160
bins
numberofelementsineachbin
Histogram of uniformly-distributed data with 20 bins
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
46/79
>> 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.
Now repeat this exercise, but change the number of random numbers to100
and
then to 1,000,000and compare the resultant histograms.
Now type help histto 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 whichMATLAB commands in a program are executed.
100 150 200 2500
200
400
600
800
1000
1200
1400
1600
1800
2000
bins
numbe
rofelementsineachbin
Histogram of Gaussian data with 15 bins
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
47/79
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 executionof 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
dispcommandConsider the following example in which the variable aahas been first defined
and then its name has been typed at the command prompt. MATLAB displaysthe name of the array aaand also its value.
>> aa=[8.9 11];
>> aaaa =
8.90 11.00
disp(aa)displays the value of array aa, without printing the array name. Forexample,
>> disp(aa)8.90 11.00
or
>> disp(10)10.00
>> disp(20*pi)62.8319
If xin disp(x)is a character string, the text would be displayed. For example,
>> disp('20*pi')20*pi
Functionswho,whos and clear
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
48/79
The function who lists the variable names in current use (CommandWindow workspace).
The function whoslists 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 zclears the variables x, yand zfrom the memory.
Try these functions to see how they work.
The formatcommandWhen 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 thedecimal point. Furthermore, it may display numbers in scientific notation if they
are too large or too small. You can use the following format commands tomodify the way numbers are displayed.
format short 4 digits after decimal.format long 14 digits after decimal.format short e 5 digits plus exponent.format long e 15 digits plus exponent.format short g 5 total digits with or without exponent.format long g 15 total digits with or without exponent.format bank fixed format for dollars and cents.format + the symbols +, - and blank are printed for
positive, negative and zero elements.format default format. Same as format short.
spacing:format compact suppress extra line-feeds.format loose puts the extra line-feeds back in.
Try these commands to see how they work.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
49/79
3.2 CONDITIONAL CONTROL STRUCTURESFundamentalsConditional 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 usthat that the price of each box car depends on the number of items we purchase.
If we buy 3or less, the price is 22Keach; if we buy between 4and 10, the
price is 20Keach and finally, if we buy more than 10, the price is 19Keach.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.min 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 > 10cost = Low_price * number_of_cars;
elseif number_of_cars > 3cost = Medium_price * number_of_cars;
elsecost = 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 andwhich blocks to be skipped over.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
50/79
The ifconstruct has the following form
If (control expression 1)Statement
Statement block 1elseif (control expression 2)
StatementStatement block 2
elseStatementStatement block 3
end
Control expressions dictate which block of code will be executed. If control
expression1is True, then the program executes the statements in block
1and then skips to the first executable statement following the endstatement.
Otherwise the program checks for the status of controlexpression2. If
controlexpression2is True, then the program executes the statements
in block2and then skips to the first executable statement following the end
statement. If all the control expressions are False, then the program executesthe statements in the block associated with the elseclause.
There can be any number of elseifclauses (0or more) in an ifconstruct,
but there can be at most one elseclause. The control expression in each clausewill 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 blockof statements is executed, and the program skips to the first executable statement
following the endstatement. If all the control expressions are False, then the
program executes the statements in the block associated with the elseclause.If there is no else clause, then execution continues after the end statement
without executing any part of the ifconstruct.
Remember to indent the body of an ifconstruct by a few spaces to improve the
readability of the code.
Control expressions make use of relational and logical operators. These are now
explained.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
51/79
Relational operators
A relational operator compares two values and yields a Trueor Falseresult.MATLAB relational operators are:
Operator Meaning== Equal to
~= Not equal to
> Greater than
>= Greater than or equal to
< Less than
3 is True and the value of the
expression 53 is True and the expression 2==1+3 is
False. Therefore, the expression 5>3 & 2==1+3is False.
A logical statement containing the Oroperator (|) is Trueif one or both of its
arguments are True. In other words, it is only Falseif both its arguments are
False. That is,
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
52/79
expression
A
expression
B
expression
A | B
True True True
True False True
False True TrueFalse 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+5is True.
The Not(~) operator negates its argument. A Trueargument is made False
and a Falseargument is made True. That is,
expression
A
expression
~A
True False
False True
For example, the expression 2 == 1+5 is False. Therefore, the expression
~(2 == 1+5)is True.
ExampleWrite a MATLAB function to evaluate the value of z = f(x,y) for any
scalar values of xand y, where the function f(x,y)is defined as follows:
00
00
00
00
),(
22
2
2
yandxyx
yandxyx
yandxyx
yandxyx
yxf
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
% |% |x + y x>=0 & y>=0% |x + y^2 x>=0 & y
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
53/79
%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 ofthe %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
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
54/79
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 > 10cost = Low_price * number_of_cars;
elseif number_of_cars > 3cost = Medium_price * number_of_cars;
elsecost = 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_costnumber of cars cannot be negative
3.3 REPETATIVE CONTROL STRUCTURESLoops are MATLAB constructs that allow us to execute a block of statements
more than once. MATLAB provides two forms of loop constructs:
1.
The forloop, which repeatedly executes a block of statements a definitenumber of times.
2. The whileloop, which repeatedly executes a block of statements as longas some condition is satisfied.
The whilestructure is most appropriate when the number of iterations in the
loop is not known beforehand. In contrast, the for structure should be usedwhen the number of iterations is known.
We will now explain these two constructs in more detail.
3.3.1 The For loopFundamentals
The forloop will execute a block of statements a fixed number of times. Thegeneral form of the forloop is
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
55/79
for index = first:increment:last
statement
statement
end
statement
where index is called the loop variable (or loop index). The statements
between the forstatement and the endstatement are referred to as the body ofthe loop.
The loop variable (index) is initialised with the value first. Each time
through the forloop, incrementwill be added to index. The termination
condition is that indexwill be greater than lastif incrementis positive,
or smaller than lastif incrementis negative. The following two examples
will demonstrate how a forloop works.
>> for XX=1:0.5:4
disp(XX)end11.500022.500033.50004
and
>> for XX=5:-1:2disp(XX)
end5432
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
56/79
It should be noted that if the incrementis 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 11and 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 are all theodd %numbers between 11 and 46.XX = 11:2:46;
%determine the total number of elements in array XXN_XX = length(XX);
sum_of_terms = 0; %initialise sum_of_terms
for II = 1:N_XXsum_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_squareson 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 forloop is to be repeated. Also note
that sum_of_termsmust be given an initial value before the forloop starts.
The initial value of sum_of_termsmust be zero. This is so because in the
statement sum_of_terms = sum_of_terms + XX(II)^2, for II=1,
sum_of_termsmust be equal to XX(1)^2. This is only possible if the initial
value of sum_of_termsis 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 forloop should
not be changed anywhere within the loop. This will lead to strange errors which
are very difficult to find.
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
57/79
Nested LoopsIt 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.90for weight=50:10:90
bodymassindex = weight/height^2;disp([height weight bodymassindex])
endend
Now type body_mass_index_tableon the command line and you will getthe following results.
>> body_mass_index_tableheight weight bodymassindex1.5000 50.0000 22.22221.5000 60.0000 26.6667
1.5000 70.0000 31.11111.5000 80.0000 35.55561.5000 90.0000 40.00001.6000 50.0000 19.53121.6000 60.0000 23.43751.6000 70.0000 27.34371.6000 80.0000 31.25001.6000 90.0000 35.15621.7000 50.0000 17.30101.7000 60.0000 20.76121.7000 70.0000 24.22151.7000 80.0000 27.68171.7000 90.0000 31.14191.8000 50.0000 15.43211.8000 60.0000 18.51851.8000 70.0000 21.60491.8000 80.0000 24.69141.8000 90.0000 27.77781.9000 50.0000 13.85041.9000 60.0000 16.62051.9000 70.0000 19.39061.9000 80.0000 22.16071.9000 90.0000 24.9307
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
58/79
It is noted that in the first forloop the variable heightis incremented from
1.50 to 1.90 in steps of 0.1. Then, for each fixed value of height, the
variable weightwill change from 50to 90in steps of 10.
The break StatementThere are times when you want to break out of a loop because some special
condition has arisen. If a breakstatement is executed within the body of a loop,
execution of the program is transferred to the first statement after the endstatement of the loop. For example, save the following program astest_break.m
%This script file (test_break.m) demonstrates%the effect of a break statement in a for loop.
for ii=1:5yy = ii^5;if (yy > 1000)
breakenddisp('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 willget the following output.
>> test_breakii =
1ii =
2ii =
3MATLAB has finished executing the for loop
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
59/79
After executing the for loop, the loop index ii isequal 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 endstatement
of the for loop, which simply displays the message MATLAB has
finished executing the for loop. That explains why ii = 1,
ii = 2and ii = 3are printed inside the loop, while ii = 4 and ii =
5are not.
If the loops are nested, the break statement would only terminate the
innermost loop containing the breakstatement.
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 whileloop 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 whilestatement. If the control expressionis still True, the blockof statements inside the loop will be executed again. This process will be
repeated until the control expressionbecomes False. Once the control
expression becomes False, control is transferred to the first statement after the
endstatement. As an example, we can write a program to add up a number ofmeasurements 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.')
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
60/79
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:
>> add_up_numbersenter all the numbers you want to add up; then enter 0 to stop.
enter a number: 1.5x =
1.5000sum_x =
1.5000enter a number: 2.50x =
2.5000sum_x =
4enter a number: 3.786x =
3.7860sum_x =
7.7860enter a number: 0
x =0
sum_x =7.7860
Note that both sum_xand xmust be given initial values before the whileloop
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_xmust be equal to the entered value. This is only possible if the initial
value of sum_xis set equal to zero. On the other hand, the control expression ofthe whileloop says that the loop will be carried out only if xis different from
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
61/79
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 xvalue is entered at the keyboard.
Remember to indent statements inside a whileloop 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 yare two vectors of the
same length. The function f(x,y)is defined as follows:
00
00
00
00
),(
22
2
2
yandxyx
yandxyx
yandxyx
yandxyx
yxf
Also calculate the square root of the absolute value of z = f(x,y). Use a
forloop to solve this problem.
Solutionfunction [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
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
62/79
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 haveto %adjust the size of the variables z and square_root_of_abs_z ineach%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 followingtwo %commands are just used to establish the size of the variables zand %square_root_of_abs_z. Their real values will be calculatedinside %the for loop.z = zeros(1,n_points);
square_root_of_abs_z = zeros(1,n_points);
for ii=1:n_pointsif (x(ii)>=0 & y(ii)>=0)
z(ii) = x(ii) + y(ii);elseif(x(ii)>=0 & y(ii)
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
63/79
plot(x_values, y_values,style_option)
Various line styles, marker types and colours may be obtained
with style_optionwhere style_optionis a character string madefrom one element from any or all of the following 3 columns:
Colour Marker type Line stylesb blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * stary yellow s square
k black d diamondv triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example, plot(x,y,'c+:')plots yvs. xwith a cyan dotted line where
each data point is marked with a plus; plot(x,y,'bd')plots yvs. xwith ablue 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 secondtime 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.4of your handouts.
Function legendYou can use function legendto produce a legend on your plot. As an example,
try the following
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
64/79
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')
You can change the position of the legend with the mouse by first left clickingthe legend and then dragging it.
Function axisOnce you have produced a plot, you can use the function axisto change the x
and yaxes 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 xaxis is shown between 4and 6
and the lower and upper limits of the yaxis are 0and 300, respectively.
0 1 2 3 4 5 6 7 8 9 100
100
200
300
400
500
600
700
800
900
1000
2nd order polynomial
3rd order polynomial
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
65/79
In order to make figure number nyour active (current) figure, use the followingcommand
>> figure(n)
Functionfplot
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 aswith>> 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 FUNbetween the x-axis limits specified by [x_min x_max]. The
name of the function FUNmust 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],'.')
will lead to the following figure
4 4.2 4.4 4.6 4.8 5 5.2 5.4 5.6 5.8 6
0
50
100
150
200
250
300
2nd order polynomial
3rd order polynomial
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
66/79
It should be noted that the function fplot is adaptive, meaning that itcalculates 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 M-
file 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 toa %column vector. On the other hand, if X is alreadyvertical, %it will remain unchanged. In other words, use thefollowing %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 YY(:,2) = abs(X).^(pi/1.5); %the second column of Y
Now, Plot the function with the following statement:
>> fplot('fplot_example',[-20 20],'.')
-3 -2 -1 0 1 2 3-1
-0.5
0
0.5
1
1.5
2
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
67/79
>> axis square
As observed, both columns of the output matrix Yare plotted in the same figure.
In the foregoing command, the first input argument of the function fplotis the
name of the function to be plotted in single quotes, the second one is the rangeof the variable X and the third one is the symbol or the line type used in thegraph.
4.2 3-D PLOTS
Line plotsA three-dimensional line plot can be created with the function plot3. This
function is similar to the two dimensional plotfunction, 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')
-20 -15 -10 -5 0 5 10 15 20-100
0
100
200
300
400
500
600
x
Y1andY2
Function plotted by fplot
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
68/79
grid on, axis square
Surface plots, Mesh plots and Contour plotsA 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 independentvariables and the function fis used to calculate zfor 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
meshgridmakes 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 xxand yymatrices and also the following plot.
-1
-0.5
0
0.5
1
-1
-0.5
0
0.5
1
0
5
10
15
x (meters)
Three-dimensional line plot
y (meters)
z(meters)
-
7/24/2019 MATH286_NotesS1P1 2 Matlab 2
69/79
xx =1 2 3 41 2 3 41 2 3 4
1 2 3 41 2 3 41 2 3 41 2 3 4
yy =
2.0000 2.0000 2.0000 2.000