School of Mathematics and Statistics 1 Department of Mathematics and Statistics MAST20004 Probability 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 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 tab 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. 2 • • Type demo matlab desktop in Command Window to access some demo videos (depending on your computer background you may wish to view “Desktop and Command Window” video). To quit Matlab, type quit in Command Window. 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 >> x=0:0.01:3; >> y=2*x; >> plot(x,y) %Check x and y in Workspace. %Note Matlab opens a “Figure 1” window to plot the graph. 3 • Subscripts, indices and attributes of data >> x(1) %The 1st element of x. ans = 3 >> y(2,3) %The element of y at row 2 and col. 3. ans = 7 >> 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 elements of x. ans = 3 4 >> z<0.5 %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. >> z(z<0.5) % 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 %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 %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. x3 = 5 6 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 ans = 86 + >> a=x1./x2; >> prod(a) % product of all elements of a. ans = 0.1786 >> mean(a) ans = 0.5655 Here we have seen the use of the following major arithmetic operators in Matlab: % average of all elements of a. - * / ^ .* ./ .^ 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 “==”. 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 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 . >> plot(x,y) %line plot >> plot(x,y, ‘+’) %points plot >> plot(x,y,'-',x,y,'+') >> scatter(x,y) >> ezplot('exp(x)*(1-exp(x))/(1+exp(x))^3', [-3,3]) >> ezsurf( 'x*y*exp(-(x^2+y^2))' ) %scatter plot 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, so that each time you need this set of commands, 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 on the “Maths and Stats lab materials” server, in the 620-201 Probability folder. You should first copy this program from the server into the StudentData (D:\) drive which is the default working directory for Matlab. %This program simulates 'nrep' throws of a two fair die %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. >> Lab1ExA RelFreq_AintersectB = 0.0260 RelFreq_AunionB = 0.2840 Remarks: 1. The first 5 lines of the file Lab1ExA.m are started with % and are comment lines. The comment lines are non-executable 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 control . It needs be paired with an end command. The commands between for and its paired end will be executed nreps times with i’s value being increased by 1 at each subsequent execution. 4. In addition to “for ……end”, another loop control command in Matlab is “while … … end” which endlessly executes the 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 Matlab Editor. The following is an example showing how to create function and 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 1. 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. 2. 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 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.