MATLAB handout - Department of Mathematics and Statistics

advertisement
1
Department of Mathematics and Statistics
620-201 Probability
Brief Introduction to Using Matlab
1. What is Matlab?
MATLAB is a high-performance language for technical computing. Matlab can be used to do computation,
graphing and programming. The name MATLAB stands for matrix laboratory.
2. Starting Matlab
Start Matlab by clicking the Matlab icon on the taskbar (or double clicking the Matlab icon in the
Applications folder on your computer Desktop). The default Matlab Desktop opens as shown below:




The Command Window is used to issue individual commands to Matlab (using it rather like a
calculator). You can use this to start understanding different commands. However in labs we will
mainly use Matlab programs (M-files) to run a whole sequence of commands in one go.
The Current Directory & Workspace window shows the files in the current Matlab working
directory, and when selecting Workspace it lists the variables you have created.
The Command History window shows previous commands you have issued. You can access the
history to repeat a command without retyping or to copy commands into a program.
To quit Matlab, type quit in Command Window.
2
3. Creating vectors, matrices and data

Try the following commands (in bold) in Command Window one by one to see how vectors,
matrices and data are created and how to work with them. Note that the words after ‘%’ are
comments and explanations. Do not type them in.
>> 5 %Matlab evaluates the expression “5” and prints the answer but no variable is created.
ans =
5
>> [3 4 5] % A vector is created.
ans =
3 4
5
>> x=[3 4 5];
%
%
%
%
The vector [3 4 5] is saved in a variable called “x”.
Note the semicolon ‘;’ at the end, which tells Matlab to suppress the output.
Variable name in Matlab is case sensitive.
Check Workspace for x.
>> x
x=
3
4
5
>> y=[1 2 3 4; 5 6 7 8; 9 10 11 12] %A matrix ‘y’ with 3 rows and 4 columns is created.
y=
1 2 3 4
5 6 7 8
9 10 11 12
>> z=rand(2,5) % A 2 row by 5 column matrix of uniform random numbers between 0 and 1.
z=
0.4447 0.7919 0.7382 0.4057 0.9169
0.6154 0.9218 0.1763 0.9355 0.4103
>> w=randn(100,1)
>> hist(w)
%A column of 100 random numbers are generated from normal distribution
%with mean 0 and standard deviation 1. Type doc randn to seek help.
%Plot the histogram of w and see whether the histogram is bell-shaped.
%Type doc hist to seek help.
>> -1:0.5:1.5 % Patterned data. Useful for plotting functions on a grid, e.g. -3:0.01:3.
ans =
-1.0000
-0.5000
0
0.5000
1.0000
1.5000
>> u=0:0.01:3;
>> v=2*u;
>> plot(u,v)
%Check x and y in Workspace.
%Note Matlab opens a “Figure 1” window to plot the graph.
3

Subscripts, indices and attributes of data
%The 1st element of x.
>> x(1)
ans =
3
>> y(2,3)
%The element of y at row 2 and col. 3.
ans =
7
>> z<0.5
>> z(z<0.5)
>> y(1:2, [2 4])
%Elements of y at rows 1 to 2
% and columns 2 and 4.
ans =
2 4
6 8
>> b = [1 2];
>> x(b)
%Elements of x indexed by b,
% e.g. the 1st & 2nd ements of x.
% List those elements of z that are less
% than 0.5. This is useful in counting
% the # of heads in flipping coins.
ans =
0.4447
0.1763
0.4057
0.4103
>> size(y)
ans =
3
ans =
3 4
%Show which elements of z is less than 0.5.
ans =
1 0 0 1 0
0 0 1 0 1
% Note the answer is a logical array with 1 = True.
%Show that y has 3 rows, 4 columns
4
4. Simple calculations
>> 3.2+exp(-1)*(1/sin(2.3)+log(4.5))^2
ans =
6.1778
>> x1=[3 4 5];
>> x2=[6 7 8];
>> x1+x2
%Element-wise addition
ans =
9 11 13
>> x3=2+x1
x3 =
5
6
%Note Matlab treats 2 as a vector of 2’s and so adds 2 to every element of x1.
%Try x4=3*x1, x5=x1/3 and x6=3/x1 to see whether they work or not.
7
>> x1^2 % Note the operator ‘^’ is a matrix operator which requires that x1 must be a square matrix.
??? Error using ==> mpower
Matrix must be square.
>> x1.^2 % ‘.^’ is an array operator (or element-wise operator). Here it squares each element of x1.
ans =
9 16 25
>> x1.*x2 % ‘.*’ is element-wise multiplication
ans =
18 28 40
>> x1./x2
% ‘./’ is element-wise division.
ans =
0.5000 0.5714 0.6250
>> sum(x1.*x2)
% sum of all elements of x1.*x2.
% Try sum(y). What did you get?
% What about sum(sum(y))?
ans =
86
>> a=x1./x2;
>> prod(a)
% product of all elements of a.
ans =
0.1786
>> mean(a)
ans =
0.5655
% average of all elements of a.
Here we have seen the use of the
following arithmetic operators in
Matlab:
+
-
*
/
^
.*
./
.^
In particular, “.*”, “./” and “.^”
are element-wise operators.
4
Try the following in the Command Window:
>> 3==5 % “3==5” is false so returns
% a logic value 0 (0=False).
ans =
0
>> 3~=5 % 3 does not equal 5, thus “3~=5” is true
% and returns a logic value 1 (1=True).
ans =
1
>> x=[3 4 5];
>> x<=4 %The answer is that the first two
%elements of x are less than or equal to 4.
ans =
1
1
0
Relational operators.
Description
Code
Equal
==
Not equal
~=
Less than
<
Greater than
>
Less than or equal
<=
Greater than or equal >=
Try the following in the Command Window:
Logical operators.
Description
Element-wise logical AND
Element-wise logical OR
Logical NOT
Code
&
|
~
>> (3<4) &
ans =
1
>> (3<4) |
ans =
1
>> (3>4) |
ans =
0
>> (x > 3)
ans =
0
>> ~(x==3)
ans = 0
(4<5)
%This statement is true.
(4==5)
%True statement
(4==5)
%False statement
& (x < 5) %Only the 2nd element of x is
% greater than 3 and less than 5.
1
0
%Test which elements of x do not equal 3.
1
1
To seek help on an operator, type “doc operator_name” in the Command Window, e.g. “doc
== ” or “doc eq” for help on “==”. For a brief help, type “help operator_name”.
5. Getting help



If you know the name of the function or object you want help for, type “help name” or “doc
name” in the Command Window. Try “doc sum”, “doc +”, “help sum” and “help +” to see
what you get.
General help can be obtained by typing “doc”, “doc help”, “help”, “help help” etc in the
Command Window.
There are also video demonstrations in Matlab. Type “demo”, “demo matlab” and “demo
matlab desktop” in the Command Window and see what happens.
6. Graphs
Only three simple graphic functions ― plot, ezplot (ezsurf) and scatter ― are introduced here.
More graphic tools can be found using Matlab Help Browser. Functions plot and scatter are used to
plot data while ezplot is used to plot functions. While “doc plot”, “doc scatter” and “doc
ezplot” give the details, try the following commands to have a first look of these functions.
5
>> x=-3:0.2:3; y=exp(x).*(1-exp(x))./((1+exp(x)).^3);
% The y data are calculated from the x data using function y  e x (1  e x ) /(1  e x ) 3 .
>> plot(x,y, ‘+’) %points plot
>> plot(x,y) %line plot
0.1
0.1
0.08
0.08
0.06
0.06
0.04
0.04
0.02
0.02
0
0
-0.02
-0.02
-0.04
-0.04
-0.06
-0.06
-0.08
-0.08
-0.1
-3
-2
-1
0
1
2
3
>> plot(x,y,'-',x,y,'+')
-0.1
-3
-2
-1
>> scatter(x,y)
0.1
0.1
0.08
0.08
0.06
0.06
0.04
0.04
0.02
0
1
2
3
1
2
3
%scatter plot
0.02
0
0
-0.02
-0.02
-0.04
-0.04
-0.06
-0.06
-0.08
-0.08
-0.1
-3
-2
-1
0
1
2
3
>> ezplot('exp(x)*(1-exp(x))/(1+exp(x))^3', [-3,3])
-0.1
-3
-2
-1
0
>> ezsurf( 'x*y*exp(-(x^2+y^2))' )
exp(x). (1-exp(x))./(1+exp(x)). 3
x y exp(-(x 2+y 2))
0.1
0.08
0.2
0.06
0.04
0.1
0.02
0
0
-0.02
-0.1
-0.04
-0.06
-0.2
-0.08
2
-0.1
2
0
0
-3
-2
-1
0
x
1
2
-2
3
y
-2
x
Note: It can take quite a bit of effort to get well presented plots/graphs. In the labs plotting is mainly
organized for you in the pre-supplied programs.
6
7. M-files
Sometimes you may need to use a set of Matlab commands repeatedly with minor modifications. This set
of commands can be stored in an M-file, a file with extension .m. You don’t need to type them again,
rather you just call this M-file by typing its name in the Command Window. You can also run an M-file
by opening it in the Matlab editor and clicking the “Run” button. An M-file can be created by opening a
Matlab Editor by menu File > New > M-file and typing in the set of commands.
The following is an M-file called Lab1ExA.m which is available for downloading from the 620-201
Probability subject Webpage. Download this file (together with the file randunifd.m that will be “called”
from LablExA.m) from our Web page: open the page in Internet Explorer, right-button click on the
links to the files and choose Save Target As… Save the files in the MATLAB folder (which is the
default working directory for Matlab). [On the lab PC’s, My Documents = Students’ Documents = D\:]
%This program simulates 'nrep' throws of two fair dice
%and calculates the relative frequency of the events
% (A intersect B) and (A union B) where the events A and B are defined as
% A = first die shows a 1.
% B = sum of the scores is 7.
nreps=500;
AintersectB=0;
AunionB=0;
for i=1:nreps
dicethrows=randunifd(1,6,2);
sum=dicethrows(1)+dicethrows(2);
if dicethrows(1)== 1 & sum==7
AintersectB=AintersectB+1;
end
if dicethrows(1)== 1 | sum==7
AunionB=AunionB+1;
end
end
RelFreq_AintersectB=AintersectB/nreps
RelFreq_AunionB=AunionB/nreps
Now typing “Lab1ExA” in the Command
Window will return the result (the numbers
will probably be different!):
>> Lab1ExA
RelFreq_AintersectB =
0.0260
RelFreq_AunionB =
0.2840
Remarks:
1. The first 5 lines of the file Lab1ExA.m start with %. They are comment lines; such lines are nonexecutable and their objective is to provide explanatory notes to program readers.
2. The next 3 lines are assignment commands. They assign values to variables.
3. The next line “for i =1:nreps” starts a loop. It needs be paired with an end command. The
commands between for and its paired end will be executed nreps times, the value of i being
increased by 1 at each subsequent execution.
4. In addition to “for ……end”, another loop control command in Matlab is “while … … end” which
executes included commands until certain condition is reached. Try the following commands to see how
for loops and while loops work differently.
>> x=[0 0 0];
>> for i=1:3
x(i)=i^2
end
>> y=0; i=1;
>> while i<=3
y=i^2
i=i+1
end
5. Finally, there are two conditional control commands “if ……end” in Lab1ExA.m. The first one tells us
that the command “AintersectB=AintersectB+1;” is executed if the statement
“dicethrows(1)== 1 & sum==7” has a 1 (True) value. It is skipped otherwise.
6.
7
8. Functions
There are many built-in functions in Matlab. We can also create our own functions in Matlab using
 10 1 
Matlab Editor. The following is an example showing how to create function y      log( x ) and
 k 1 k 
execute it in Matlab.
 Open a Matlab Editor using menu File > New >M-file.
 Type in the following code in the Editor:
function y=f(x)
y=0;
for k=1:10
y=y+1/k;
end
if(x>0) y=y+log(x);
elseif(x<0) y=y+log(-x);
else y='x must not be 0';
end


Here again for and if are program control commands.
Matlab has 4 groups of program control commands:
 Conditional Control -- if, switch
 Loop Control -- for, while, continue, break
 Error Control -- try, catch
 Program Termination -- return
Type “doc if” and “doc for” etc in Command
Window to see details of these control commands.
Save the above codes into an M-file named ablog.m
Execute ablog.m in the Command Window by typing its name and input argument..
>> ablog(2)
ans =
3.6221
>> ablog(-3.5)
ans =
4.1817
>> ablog(0)
ans =
x must not be 0
Remark 1: A function is different from a main M-file in that
(a) There is a header line in each function (for ablog.m, it is “function y=f(x)” which
identifies the input arguments which will be passed to the function from the main M-file
which calls it.
(b) The code in a function has its own workspace and is kept separate from the main
Workspace. For example, the variables y and k in ablog.m are “local”: they have
nothing to do with the variables y and k, if existent, in the Command Window.
Remark 2: The list of built-in functions of Matlab can be found following Matlab Help Navigator
> Contents > MATLAB > Functions – Alphabetical List.
8
9. Finishing your work
Please quit Matlab after you have finished your prac class. To do that, type quit in Command Window
(exit would do the same trick; alternatively, you could also press Ctrl-Q or go to the Matlab Menu and
choose File > Exit MATLAB).
As other students will be using the computer lab machine you were working on, it is good practice to delete
YOUR files from that PC when you are finished. Of course, you may wish to save them for your future use
(say, on your USB-drive). Please note that all the files in the Students’ Documents folders are deleted each
weekend.
Download