% INTRODUCTION TO USING MATLAB % for MATLAB 7 % with TOOLBOXES % SYMBOLIC MATH % STATISTICS % modified and updated in May, 2008 % by Carol Horvitz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % WORKING IN MATH COMPUTER LAB %(note to instructor: increase fontsize in command window % choose: FILE from Menu bar, Preferences, Fonts, try setting to Tahoma 15) % GET files of interest onto the local computer or your portable data medium: % % 1) make a folder for today's session on the desktop/or on memory % stick or CD % 2) use web browser to go to the course website: % bio.miami.edu/horvitz/bil235/brasil08 % 3)click on m-files folder % 4)right click on filename of interest and choose "save link as" % 5)save file to folder on local computer or on memory stick or CD % 6)IF you have put it on the desktop for the session, be sure to save to % your own portable data medium before leaving the lab % NOW open MATLAB % 1) click on MATLAB % 2) in menu bar at top, use the button to the right of the window to navigate % to directory where your files are % ****IMPORTANT: YOU DO NEED TO HAVE THAT DIRECTORY % SHOWING IN THE WINDOW % TO USE FILES IN IT AND SAVE STUFF TO IT.****** %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % MATLAB lessons: % % First: GETTING OUT!!!! % % 'ctrl-C' breaks an ongoing operation % >> quit closes program % % Second: GETTING HELP!!!! % % command line help % >> help dsolve % >> help plot % menu bar help % click on Help % click on MATLAB Help % % Now for the rest of the tutorial % % 1) working directory and windows % command, editor, workspace, % command history, current directory % 2) working on the command line in the command window % 3) variables, expressions, statements % a)types of variables (all are matrices) % i) numeric % ii) strings % iii) symbolic % b)expressions may contain operators % 4) matrices % 5) numbers and arithmetic expressions % 6) matrix vs array operations % 7) vector and matrix manipulation % 8) do loops, relational and logical operators % 9) working with files % a) m-files: scripts % b) m-files: functions % i) user-defined % ii) built-in % c) mat-files: store values of variables % 10) simple graphics % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %MATH ECOLOGY LESSONS % (in later labs this will be filled in!) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %HOW TO USE m-SCRIPTS provided in the course: % 1) FOLLOW THE DIRECTIONS IN THE COMMENTS. % (some syntax in MATLAB has changed with different versions, % I have been updating the code; some lines of code will % differ from the resource material in the text books) % 2A) RUN THE COMMANDS INTERACTIVELY WITH THE "F9" COMMAND. % or % 2B) TYPE THE COMMANDS INTO THE COMMAND WINDOW TO PRACTICE COMPOSING % YOUR OWN SCRIPT % 3) ANSWER THE Questions BY FILLING IN THE ANSWERS IN COMMENT MODE. % 4) TRY OTHER STUFF AND ADD YOUR OWN COMMANDS AND COMMENTS. % 5) ADD YOUR NAME AND DATE TO THE TOP OF THE SCRIPT and save your customized % version of it. % 6) PRINT OUT THE REVISED SCRIPT THAT HAS YOUR COMMENTS IN IT FOR YOUR NOTEBOOK. % 7) Also print out FIGURES you have created for your notebook. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%original source of examples in this script%%%%%%%%%%%%%%%%%%%% % main reference for this tutorial is % Roughgarden, 1998, appendix, but this is updated to MATLAB 7 SYNTAX % Cavers, I. 1998, http://www.cs.ubc.ca.spider/cavers/MatlabGuide/ % 1) working directory and windows %IMPORTANT!!!!!!!!! % pick a working directory % point MATLAB to it (the window in the menu bar at top shows where you are) what %What files are in it? who %What variables are in the workspace? whos %What are the sizes and types of variables? why %What is the meaning of your existence? date % 2) working on the command line in the command window %use up and down arrows to cycle through previous commands %use the 'return','enter' to carry out the command: % translates your code into machine language and does the job % and prints the result % 3) variables, expressions, statements % variable name starts with a letter, can have 19 characters, including % underscore % x=2 y=2+3 z_1=x+y z_2=y-x z_3=x*y; %semicolon suppresses the printing of the result % but the job has been done, check it: whos z_3 % a)types of variables (all are matrices) % i) numeric % ii) strings % iii) symbolic % b)expressions may contain operators %character variables are denoted with single quotes students=['Antonio Aguiar Neto'] %declare symbolic variables for manipulation of symbols syms f g m =(f+g)^2 m2 = expand(m) f=4 eval(m) whos %you may now want to save all these variables with their current values, so %you can go for a coffee break and return and not have to re-calculate %them... here is where a special kind of file comes in a "mat-file" save resultsofmywork_5mai08 what %a mat-file has all the variables in it that were defined and active at the %time you issued the command save; it is a binary file, not a text file. %simulate a fresh start after your break by using the clear %command to remove all previously defined variables who %to get back your pre-break results: load resultsofmywork_5mai08 who clear all; %ok, let's go on... close all; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %highlight and run each set separately... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 4) matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% A=[ 1 2 4.5;8/2.0 6 5] A(2,3) rowthing=[1 2 3] colthing=[1; 2; 3;] %transpose [1 2 3]' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % some of Matlab's preset matrices % ones(7) zeros(7) eye(7) rand(7) % you can also have non square matrices of many of these ones(3,2) zeros(3,2) rand(3,2) %note rand generate random numbers between 0 and 1 % from a uniform distribution %note the semicolon at the end of the line suppresses printing the result unis=rand(1,100); figure(1) hist(unis) % for normally distributed random numbers norms=randn(1,100); figure(2) hist(norms) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % before going on close graphics windows and clear variables close all clear all %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %other convenient premade matrices and the use of the colon % refer to elements and manipulate matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %integer steps a=1:5 %any steps you choose abyhalfs=1:0.5:5 abytenths=1:0.1:5 abytwos=1:2:5 % some ways to extract particular elements from a matrix a=[1 2 3; 4 5 6; 7 8 9] bbysubscripts=[a(1,2:3); a(2,2:3)] bytriangle=triu(a) help triu abovediag=triu(a,1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % some ways to rearrange elements in a matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %the transpose is very useful transa=a' %what else can you do? %HTML help % for example...check out the symbolic math stuff % go to Help on the frame around the command window % symbolic math...compatibility... obs functions % check out the reference list of matlab commands % functions, by category, mathematics...choose a topic % e.g. "arrays and matrices", "operations and manipulations", "flipud" %cool we can flip the matrix around updowna=flipud(a) leftrighta=fliplr(a) % last let's work one example of referring to a elements % in a matrix of symbolic math entities % note that in my example I use the NEW syms declaration command % not available when Roughgarden wrote the book... so % my syntax is much less cumbersome... than % what is on Roughgarden, p. 434: mine has fewer quotes and brackets syms w x y z a=[w x; y z] %change the 2,2 element to z-squared a(2,2)=z^2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 5) numbers and arithmetic expressions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear all; close all; nums=[4 -189 .032 -2.21E-23 0.9772E18 0.00001] format short format short e format long format long e format + format %arithmetic operators 2+3 2-3 2*3 2^3 2/3 2\3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 6) matrix vs array operations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %element-by-element operations % precede one of the opertators by a period (.) clear all; close all; A=[1 2 3; 4 5 6]; B=[2 2 2; 3 3 5]; C=A.*B D=A.^2 %matrix multiplication %NOT commutative % number of rows of matrix on the left % must equal % number of columns of matrix on the right A*B % A has two rows, B has three columns, this won't work A*(B') % this will, B' has two columns syms a11 a12 a13 b11 b21 b31 %note the indices are (row,col) as below a=[a11 a12 a13] b=[b11; b21; b31;] c1=a*b %defined c2=b*a %also defined, but distinct from above %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 7) vector and matrix manipulation (see above) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 8) do loops, relational and logical operators %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %"Do Loops" clear all; close all; for i=1:3 %do something for each value of i.. % for example isq=i^2 isqrt=i^(1/2) end %i does not have to be an integer for i=1:0.5:3 %do something for each value of i.. % for example isq=i^2 isqrt=i^(1/2) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %intro for USE WITH "If..." and other logical issues x=[-2 2 0 -1 1 0 -3 3 0] %understand some ways matlab chooses elements logically % in logic 1= it is true, 0 = it is false %identifies the elements of x that are equal to 0 x==0 %identifies the elements of x that are not equal to 0 x~=0 %identifies the elements of x that are > 0 x>0 %identifies the elements of x that are < 0 x<0 %we will return to how to use these later in the course %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 9) working with files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 9a) m-files: scripts(such as this one) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 1) open a new window in the m-editor (or any text editor) % 2) write your commands in the window % 3) save the script using the menu bar FILE drop down menu in the _editor_ window % type name of script into window given to you by the drop down choice "save-as" myfirstscript % 4) invoke the whole set of commands from the command window myfirstscript %don't type the ".m" % OR % 5) open the file in the editor window and run it interactively by highlighting % certain lines and using F9 to execute them %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 9b) m-files: FUNCTIONS user-defined % % something you want to do over and over...instead of having to repeat the % long script each time...write a special m-file called a % function %you give it inputs, called "arguments" % if gives you results, called "outputs" % it does the details and intermediate steps in secret %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % example the pythagorean theorem % given the a and b sides of a triangle, find the c side % name it "hypot"... % "a" and "b" will be the arguments % "c" is the output function c=hypot(a,b) c=sqrt(a^2+b^2); %save this as a function: % open a new window for an m file % copy this into into and save it as "hypot" % so all you have to do on the command line is % name the function and % give the input argument %try it hypot(1,2) hypot(4,5) hypot(7.2,5.6) %"global" is a statement used to "de-classify" the secrets: the variables calculated and % defined and used in functions remain the same in the % command space and in the function space.. we'll see its use later %here is a more fun one to try % from Higham and Higham 2005, p. 15 function yprime = lorenzde(t,y) %LORENZDE lorenz equations yprime= [10*(y(2)-y(1)) 28*y(1)-y(2)-y(1)*y(3) y(1)*y(2)-8*y(3)/3] %copy this to its own user-defined function m-file, name the file 'lorenzde'. % open a blank m-file in the editor % copy these lines to it % save it as "lorenzde.m" %then use this function together % with the built-in function "ode45.m" as follows help ode45 tspan=[0 50]; % solve for times 0 to 50, inclusive yzero=[0;1;0]; % Specifies Initial conditions [t,y]=ode45(@lorenzde,tspan,yzero) %calls the function, sets time span, initial conditions plot(y(:,1),y(:,3)) xlabel('y_1') ylabel('y_2') title('Lorenz equations, phase plane plot', 'FontSize', 16) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 9b) m-files: FUNCTIONS: built-in, CREATED BY MATLAB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the function 'exp' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % exp is _not_ the number e in matlab. % it is the exponential function... e to the x %thus it is e raised to the power in the parentheses %%%%%%%%%%%%%%%%%%%%%%%%%%% clear all; close all; help exp exp(1) %so this makes the natural log funtion work as follows % recall that log to the base e % answers the question: to what power must we raise e to get the number log(exp(1)) % review some other logs log10(100) log10(1000) log2(4) log2(16) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %spread sheet functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %treats rows as observations, columns as variables %e.g.: dots on frog legs...each row is a frog, % the first column is left leg % the second column is right leg clear all; close all; dotsonlegs=[5 6; 4 5; 7 8;8 12] meandots=mean(dotsonlegs) sumdots=sum(dotsonlegs) mindots=min(dotsonlegs) maxdots=max(dotsonlegs) stddots=std(dotsonlegs) % hmm is this the with the n or the n-1 weighting? help std %oh...so now try the other weighting stddotsnweighting=std(dotsonlegs,1) %what about relationships between dots on right and left legs corrleftright=corrcoef(dotsonlegs(:,1),dotsonlegs(:,2)) covleftright=cov(dotsonlegs(:,1),dotsonlegs(:,2)) %note the variances are on the diagonal vardots=var(dotsonlegs) % a few other things: maxdotsbothlegs=max(max(dotsonlegs)) cumsumdots=cumsum(dotsonlegs) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Linear algebra functions % the most important thing for us will be the function that finds the eigenvalues % and eigenvectors of a matrix: no small feat... % routines at the core of this were the public domain fortran programs called % EISPAK %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear all; close all; a=[.2 0 0 23 25 .1 .1 0 0 0 0 0 .5 0 0 0 0 .2 .7 0 0 0 0 .2 .3] %there are two ways to to call this function vals=eig(a) [vecs,vals]=eig(a) %we will return to this in detail later in the course % Plotting basics (Roughgarden, p. 438) clear all close all a=1:10 b=2:2:20 figure(1) plot(a) figure(2) bar(a) figure(3) hist(a) figure(4) plot(a,b) figure(5) semilogy(b) %now add some stuff to figures %first close the old ones close all figure(1) plot(a) xlabel('vector index') ylabel('a') title ('plot a vector as the single argument') figure(2) bar(a) xlabel('vector index') ylabel('a') title('bar graph for a vector') figure(3) hist(a) xlabel('bin index') ylabel('frequency') title('histogram') figure(4) plot(a,b) xlabel('a') ylabel('b') title('plot y vs. x') figure(5) semilogy(b) xlabel('vector index') ylabel('log10(b)') title('plot a vector on a log scale') %there is a lot more you can do...we will learn some of it but for now: close all clear all %but before we go...there is also "ezplot" to see the form of a function ezplot('x^2') ezplot('exp(x)') ezplot('log(x)') % "differential equations..." (Roughgarden, p. 440) % we will do this two ways % symbolically % numerically %why? sometimes we know something about the rate of change % and we want to know what the pattern across time will look like... % for example % we may know that "populations grow at a rate proportional to their size" % the equation that says this is % Dn/dt = r * n % how can we see what happens over time given a certain starting point? %symbolically this problem is: dsolve('Dn=r*n', 'n(0)=a', 't') %numerically this problem can be addressed by writing a function % we can call it "expgrow" function ndot=expgrow(t,n) global r; %declares the r as a non-secret, global variable to be used in function and command space ndot=r*n; %open an new mfile %copy these lines there % save it as a user-defined function "expgrow.m" %NOW, use it in conjuction with built-in function 'ode23' help ode23 clear all global r; r=0.5; % try it for time series that goes from 0 to 10 and initial value=2 [t,n]=ode23('expgrow',[0,10],2) plot(t,n) xlabel('time') ylabel('population size') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Think of a biological problem % % Write your own function file % Write your own m-file script that calls the function % Solve the problem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%