------------------------------------------------------------------------- PHYS210: MATLAB PROGRAMMING Overview slides http://laplace.physics.ubc.ca/210/Doc/matlab/matlab-programming-overview.pdf CONTENTS (**) Denotes an advanced topic for self-study 1) Overview 1.0) Preliminaries 1.1) Principal modes of matlab programming 1.2) Matlab programming paradigms 2) Defining Matlab functions 2.1) Function definition: general forms 2.2) Function definition: examples 2.3) Displaying function definitions 3) Matlab control structures 3.1) Relational and logical operators 3.1.1) Relational operators 3.1.2) Logical operators 3.2) selection: the if-elseif-else-end statement 3.3) iteration (repetition / loops) 3.3.1) for-end loop 3.3.2) while-end loop 3.3.3) Nested loops 3.3.4) The break statement 3.3.5) The continue statement 3.4) The return statement 4) Matlab startup folder, path, startup file, "crash" files 4.1) Matlab startup folder: ~/Documents/MATLAB 4.2) Matlab path 4.3) Matlab startup file: startup.m 4.4) Matlab "crash" files 5) Displaying/outputing quantities in Matlab 5.1) more 5.2) disp 5.3) fprintf 5.3.1) Using fprintf to output to a file (**) 6) Inputing quantities in Matlab 6.1) input 6.2) fscanf: Get input from a file (**) 7) Simple 2D plotting with Matlab 8) Interfacing functions to Matlab's help command 9) Multiline comments 10) Cell arrays (**) ----------------------------------------------------------------------------- - Solutions to last lab's exercises available in ~phys210/matlabsolns/ex1.m ----------------------------------------------------------------------------- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1) OVERVIEW +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1.0) PRELIMINARIES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Refer to http://laplace.physics.ubc.ca/210/Doc/matlab/matlab-programming-overview.pdf for brief overview - OBSERVE: - Will often abbreviate Matlab as M below - Almost everything covered here should work in octave as well - ADVANCED TOPICS will be marked with (**). Refer to the text, online references, instructor/TAs ... for additional information as needed. o GETTING INTERACTIVE HELP IN MATLAB: The 'help' command >> help - Example >> help linspace o GETTING INTERACTIVE HELP IN MATLAB: The 'lookfor' command >> lookfor - The lookfor command returns a list of functions (including those that the user has defined), and their synposes, that have something to do with - Exmaple >> lookfor vector detrend - Remove a linear trend from a vector ... issorted - TRUE for sorted vector and matrices. iscolumn - True if input is a column vector. isrow - True if input is a row vector. isvector - True if input is a vector. . . . o SYNTAX HIGHLIGHTING There is a very useful feature in gedit (and many other text editors), known as syntax highlighting, in which text that defines a program (or function, script, ...) is automatically color-coded according to the syntax of the language being used. For example, when syntax highlighting enabled, reserved words will appear in a distinct color. This auto-coloring generally makes it easier to write syntactically correct programs. From the top menu bar in gedit use View -> Highlight Mode -> Scientific -> Octave to enable syntax highlighting for MATLAB (and, of course, octave) ----------------------------------------------------------------------------- EXERCISE: Assuming you are using gedit, set the highlighting mode as just described ----------------------------------------------------------------------------- o ERROR MESSAGES: - You may encounter the following messages if you mistype statements and/or refer to quantities that are not defined. A) Undefined quantities >> whatmeworry Undefined function or variable 'whatmeworry'. B) Typo that Matlab interprets as a command/function invocation >> xx = 32 >> yy = 16 % Typo ... meant to type 'xx-yy' or 'xx - yy' >> xx -yy Error: "xx" was previously used as a variable, conflicting with its use here as the name of a function or command. See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details. C) Combination of A) and B) >> zz cc Undefined function 'zz' for input arguments of type 'char'. o NOTES FOR POTENTIAL OCTAVE USERS - These notes have been written to ensure maximum portability/compatibility between Matlab and octave - HOWEVER, there are syntactic differences between the two that you may encounter when looking, for example, at on-line documentation for either of the languages - One example is that Matlab uses 'end' to end many programming constructs (function definitions, if-then-else statements, loops, etc.). octave also supports this syntax, but has additional reserved words (such as endfunction, endif, ...) that improve code readibility - DO NOT use octave's extensions if you want to preserve compatibility with Matlab ----------------------------------------------------------------------------- WE WILL NOT WORK THROUGH THE REMAINDER OF SECTION 1 OF THESE NOTES, SINCE MUCH OF THE MATERIAL IS COVERED IN THE OVERVIEW SLIDES AND/OR THE PREVIOUS LAB. HOWEVER, YOU MAY WANT TO QUICKLY READ THROUGH IT ON YOUR OWN AT SOME OTHER TIME. ----------------------------------------------------------------------------- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1.1) PRINCIPAL MODES OF MATLAB PROGRAMMING +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ i) M scripts (programs) - arbitrary sequence of M statements, including assignment stmnts control structures, etc. ii) M functions - analogous to Maple procedure - IMPORTANT: Matlab source code (scripts/programs/functions) MUST ALWAYS be prepared in text files having an extension, ".m", e.g. myscript.m somefcn.m - Then provided that either i) M is running in the directory containing the .m file ii) .m file is in M's PATH can execute statements in script, or execute specific function call simply by typing the prefix/stem of the .m file, i.e. the part of the file name before the '.m' >> myscript >> somefcn(arg1,arg2) (Assumes somefcn takes 2 arguments) - For time being will assume that i) is the case, and will return to path settings later - CRUCIAL!! Each script (program) or function that can be invoked from the M command line, or in a script, or in another function, etc. MUST BE DEFINED IN A SEPARATE FILE (different from approach we often adopted in Maple) - RECOMMENDED CODING PROCEUDRE - By all means experiment with M interactively, BUT - Prepare all scripts/functions in text files using your text editor - Keep editor window OPEN while you test your scripts/fcns, so that you can quickly make changes as needed, and reexecute without stopping/starting the editor - IMPORTANT: For functions, ALWAYS code a testing script at the same time or better, before, you code the function! - e.g. for somefcn(arg1,arg2), code script file tsomefcn.m somefcn(targ1,targ2) somefcn(targ3,targ4) . . . +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1.2) MATLAB PROGRAMMING PARADIGMS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - As with Maple, Matlab has support for both - FUNCTIONAL programmming - PROCEDURAL (IMPERATIVE) programmming - FUNCTIONAL programming - e.g. Rich set of constructors/operators for array creation/manipulation - PROCEDURAL programming - Data & Algorithms - Data - Arrays (general dimension) - Algorithms - Function definitions - Control structures ----------------------------------------------------------------------------- EXAMPLE: Writing and executing a simple Matlab script ----------------------------------------------------------------------------- - Open a terminal and change the working directory to ~/matlab (if you didn't make ~/matlab previously, make it now) % cd ~/matlab % pwd - Start Matlab from the command line (NOT FROM THE LAUNCHER!), and in the background % matlab & - Open your text editor and create the file ~/matlab/myscript1.m with contents as follows % This is a simple Matlab script file a = 10 b = [1 2 3 4] c = 1:2:9 d = [1 4 9 16]' e = sind(30) f = [1 2 3; 4 5 6] g = eye(2) - Save the file, then in matlab type >> myscript1 - You should see the following output: IF YOU DON'T, ASK FOR HELP! a = 10 b = 1 2 3 4 c = 1 3 5 7 9 d = 1 4 9 16 e = 0.5000 f = 1 2 3 4 5 6 g = 1 0 0 1 - Now modify myscript1.m by adding semi-colons to the end of lines 1, 3, 5 and 7 as follows % This is a simple Matlab script file a = 10; b = [1 2 3 4] c = 1:2:9; d = [1 4 9 16]' e = sind(30); f = [1 2 3; 4 5 6] g = eye(2); - Be sure to resave myscript1.m, then reexecute the script >> myscript1 - This time the output is b = 1 2 3 4 d = 1 4 9 16 f = 1 2 3 4 5 6 - So by putting a ';' at the end of the command we suppress output from the command when the script is executed, but, importantly, the command is still executed +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2) DEFINING MATLAB FUNCTIONS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ o Again, note that the overview slides briefly covers some of this material http://laplace.physics.ubc.ca/210/Doc/matlab/matlab-programming-overview.pdf +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2.1) FUNCTION DEFINITION: GENERAL FORMS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - NOTE: A Matlab function can return 0, 1, 2 ... values (as many values as you want), and each value can be a scalar, vector, array, ... - Adopt usual "meta" notation; denotes arbitrary seqence of M statements/commands. Generally will have one statement per line, but can have more using either ',' or ';' to separate statements (';' suppresses output) = "input argument" (formal argument) = "output argument" (may sometimes call "return value") - 0 output arguments function (, , ..., ) end - 1 output argument function = (, , ..., ) end - 2 output arguments function [ ] = (, , ..., ) end - n output arguments function [ ... ] = (, , ..., ) end - NOTES: - For all of the above forms, there can be 0 or more input arguments, - All of the inarg's and outarg's must be valid Matlab variable names - Don't need commas between outarg's but can include them if you wish - DO need commas between inarg's - All outarg's must be assigned a value before 1) the end of the function (implicit return) or 2) return statement is executed (explicit return) THIS IS HOW THE FUNCTION RETURNS VALUES - If there are mutiple outargs, then to "capture" all of them upon return from the function, the function invocation must be on the RHS of an assignment statement with a row vector of names on the LHS, e.g. [out1 out2] = fcn2(in1, in2) otherwise, only the FIRST outarg is returned - NOTE: Will usually want to end each statement in (i.e. in the body of the function) with ';' so that output doesn't appear on standard out (terminal) as function executes - NOTE: However, removing the ';' from selected lines provides a quick/convenient way of enabling tracing of that statement for, e.g., the purposes of debugging +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2.2) FUNCTION DEFINITION: EXAMPLES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ----------------------------------------------------------------------------- EXAMPLE 1: myadd ----------------------------------------------------------------------------- - myadd takes two scalar inargs, sc1 and sc2, and returns one scalar outarg with the value sc1 + sc2 - Create the file ~/matlab/myadd.m that contains the following 3 lines function res = myadd(sc1, sc2) res = sc1 + sc2; end - Be sure to end each line in the function definition with a ';' to suppress the output that normally would be generated - in this case there is only one such line - Also note the use of indentation to emphasize which statements are contained within the body of the function - Ensure that Matlab is (still) running in the directory ~/matlab - In Matlab, type >> myadd(2,3) - and you should see ans = 5 - NOTE: Observe how we assign the outarg 'res' the value 'sc1 + sc2', and since 'res' is defined to be the (single) inarg in the function header, this is the value that is returned from the function call - We can assign myadd's return value to a variable as follows >> val = myadd(3.0,pi) val = 6.1416 ----------------------------------------------------------------------------- IMPORTANT: When defining Matlab functions one MUST 1) Define only ONE function per source file (.m file) 2) Ensure that the name of the function and the name of the file match, e.g. myadd.m contains the definition of myadd foo.m containg the definition of foo . . . - If you do NOT follow this protocol---in particular if you include more than one function definition per file---then Matlab will not be able to find all of the necessary functions, and error messages will be issued. - For example, let's assume that myadd.m contains an extra definition for a function mysub as follows %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = myadd(sc1, sc2) res = sc1 + sc2; end function res = mysub(sc1, sc2) res = sc1 - sc2; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - Invoking myadd still works >> myadd(3.0,pi) ans = 6.1416 - But calling mysub doesn't --- instead, an error message appears >> mysub(3,2) Undefined function 'mysub' for input arguments of type 'double'. - QUESTION: Where should the definition of mysub go? ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- EXAMPLE 2: myaddsub ----------------------------------------------------------------------------- - myaddsub takes two scalar inargs, sc1 and sc2, and returns TWO scalar outargs with values, sc1 + sc2, sc1 - sc2 - Create the file ~/matlab/myaddsub.m that contains the 4 lines function [res1 res2] = myaddsub(sc1, sc2) res1 = sc1 + sc2; res2 = sc1 - sc2; end - IMPORTANT: Note the [] around the two output arguments, res1 and res2 - Now use the function in Matlab - First try >> myaddsub(2, 3) ans = 5 - Note how only a single value is returned - Now try >> [val1 val2] = myaddsub(2,3) val1 = 5 val2 = -1 and we see that TWO values are returned and assigned to the variables val1 and val2 - Again, in the definition of the function we MUST assign values to the outargs in order for the function to return the desired results ----------------------------------------------------------------------------- EXAMPLE 3: myvec ----------------------------------------------------------------------------- - myvec takes one integer inarg i1 and returns the TWO row vectors 1:i1 and i1:-1:1 (i1 should be >= 1, but we won't test for that) - Create the file ~/matlab/myvec.m containing function [vec1 vec2] = myvec(i1) vec1 = [1:i1]; vec2 = [i1:-1:1]; end - Now use the function, and be sure to use an assignment statement that has a vector with two names on the left hand side to ensure that we capture BOTH of the output arguments (each of which is a vector) >> [v1 v2] = myvec(5) - And the output should be v1 = 1 2 3 4 5 v2 = 5 4 3 2 1 ----------------------------------------------------------------------------- EXAMPLE 4: ----------------------------------------------------------------------------- - Here we see what again happens if we try to call a function that hasn't been defined in the file .m, where is the name of the function >> myvce(5) Undefined function 'myvce' for input arguments of type 'double'. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2.3) DISPLAYING FUNCTION DEFINITIONS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Use the Matlab command 'type' to display the definition of a function - First, try it for a user-defined function >> type myadd function res = myadd(sc1, sc2) res = sc1 + sc2; end - While for a built-in function, we will see ... >> type length 'length' is a built-in function. ----------------------------------------------------------------------------- EXERCISE: Working in your ~/matlab directory, create and test functions as follows (you can do the testing interactively). Be sure to save your definitions whenever you modify them. ----------------------------------------------------------------------------- A) myadd3 (define in ~/matlab/myadd3.m) - myadd3 takes 3 inargs (input args), x, y and z and returns their sum (one value) ----------------------------------------------------------------------------- B) myop4 (define in ~/matlab/myop4.m) ----------------------------------------------------------------------------- - myop4 takes 4 inargs (you choose the names!) and returns their sum and product (two values) - When you test this function, be sure to assign the return value to a two-element VECTOR of unknowns to ensure that both outargs are being computed properly. E.g. >> [val1 val2] = myop4(10, 4, 8, 16) ----------------------------------------------------------------------------- C) myarray2 (define in ~/matlab/myarray2.m) ----------------------------------------------------------------------------- - myarray2 takes 2 input args, m and n, and returns two values: 1) A uniformly spaced row vector of length 10, with first element = m, last element = n 2) A uniformly spaced column vector of length 10, with first element = n, last element = m +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ **) MATLAB PROGRAMMING: LAB 2 ----------------------------------------------------------------------------- - Solutions to last lab's exercises are available in ~phys210/matlabsolns/ex2.m ~phys210/matlabsolns/myadd3.m ~phys210/matlabsolns/myop4.m ~phys210/matlabsolns/myarray2.m ----------------------------------------------------------------------------- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3) MATLAB CONTROL STRUCTURES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ NOTE: We can (and will below) use all of the control structures interactively, but they will, of course, be much more useful when used in scripts and functions +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.1) Relational and Logical Operators +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - NOTE: In contrast to Maple which has a special Boolean type (true and false), Matlab follows the C-language approach of i) Returning the integers 0 for false and 1 for true when *evaulating* relational or logical expressions ii) Treating the value 0 (integer OR floating point) as false, and any non-zero value as true in contexts where relational/logical expressions are expected (e.g. if statements) --- i.e. although 0 is the unique "false value", and although comparisons and logical operations will always return 0 or 1, there is no unique "true value" - Among other things this means that i) Results from relational and logical operations can be used in arithmetic statements (which can be sometimes be useful, but should be considered (**)) ii) *Arbitrary* statements that return a scalar value can be used where relational/logical expressions are expected (**) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.1.1) M defines the following relational operators +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Operator Definition < Less than > Greater than <= Less than or equal >= Greater than or equal == Equal ~= Not equal - Note the use of tilde ~= for not equal, versus <> in Maple and != in C/C++ - These work in the usual fashion for scalars, but need to be careful when arrays are compared (**) - Examples: >> a = 1; b = 2; c = 3; >> a < 3 ans = 1 >> b > c ans = 0 >> a == c ans = 0 >> b ~= c ans = 1 (**) >> 32 * (a < 3) + 16 * (b == c) + 8 * (a == a) ans = 40 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.1.2) M defines the following logical operators +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Operator Definition & Logical AND | Logical OR ~ Logical NOT - Note that these are single character expressions, NOT 'and', 'or' and 'not' as in maple - Examples >> a = 1; b = 2; c = 3; >> (a < b) & (b < c) ans = 1 >> (a == 2) | (a == 3) ans = 0 >> ~(a < b) ans = 0 (**) >> ~30 ans = 0 >> ~~30 ans = 1 - NOTE: - There *is* a precedence order for all of the arithmetic and logical operators, but, as was the case for Maple, it is best to simply use parentheses to ensure you get the order you want +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.2) SELECTION: THE if-elseif-else-end STATEMENT +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - DEFNS: = Boolean expression (should be a scalar), also known as conditional expresssion = Statement sequence GENERAL FORM if elseif elseif . . . else end - NOTES: - DON'T USE 'then' after the 'if' in Matlab - USE elseif NOT elif (as in Maple) - can have arbitrary number of elseif clauses (0 or more) - else clause is optional - The if statement is terminated with end (M uses end to end pretty much everything) Examples: - Simplest form >> a = 2; b = 3; >> if a < b a + b end ans = 5 - Next simplest form >> a = 2; b = 3; >> if a == b a + b else a - b end ans = -1 - Form using 'elseif' >> aa = 2; >> if aa == 1 10 elseif aa == 2 20 else 30 end ans = 20 - NOTE: M also has a 'case' statement (**) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.3) ITERATION (REPETITION / LOOPS) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.3.1) for-end LOOP +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GENERAL FORM: = loop variable = expression that defines ROW vector for = end ----------------------------------------------------------------------------- TYPE 1: generated using colon notation = first value of = lvar increment (step) = last value of for = : : end or for = : end - defaults to 1 in the second case - As the loop executes, takes on the values , + , + 2 * , ... and where the last value of is always <= - , , don't have to be integers, but usually will want them to be to avoid possible problems with roundoff errors EXAMPLES: >> for k = 1 : 3 k end k = 1 k = 2 k = 3 >> for k = 4 : -1 : 2 k end k = 4 k = 3 k = 2 >> for k = 1 : 4 : 14 k end k = 1 k = 5 k = 9 k = 13 >> for k = 2 : 2 k end k = 2 >> for k = 2 : 1 k end - Note: NO OUTPUT in this case ----------------------------------------------------------------------------- TYPE 2: created using any other command/expression that defines/returns a row vector for = end EXAMPLES: >> for k = [1 7 13 sqrt(2)] k end k = 1 k = 7 k = 13 k = 1.4142 >> for a = linspace(2.0, 3.0, 6) a end a = 2.2000 a = 2.4000 a = 2.6000 a = 2.8000 a = 3 - Note what happens if we use a column vector as ... >> for a = linspace(2.0, 3.0, 6)' a end a = 2.0000 2.2000 2.4000 2.6000 2.8000 3.0000 ... i.e. the body of the loop is only executed once, and a is assigned the entire vector - IMPORTANT! DO NOT modify the loop variable within loop, you CAN do it without generating a syntax or run-time error, but results are unlikely to be what you expect/want. BE VERY CAREFUL ABOUT THIS POINT! ----------------------------------------------------------------------------- *** October 29 - Solutions to last lab's exercises are available in ~phys210/matlabsolns/myifC.m ~phys210/matlabsolns/myiffor.m ~phys210/matlabsolns/tfcns.m ----------------------------------------------------------------------------- - From within a terminal window, change to ~/matlab, and start matlab in the background % cd ~/matlab % matlab & +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.3.2) while-end LOOP +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - DEFNS: = Boolean / conditional expression = statement sequence - General form while end - NOTE: - The while loop executes until evaluates to 0 (false). If is 0 upon initial entry to the loop, the body of the loop does NOT execute. In other words, as long as is true, the looping will continue - It is up to you to do something within the loop so that, eventually, evaluates to 0 (false), or your program will be stuck in the proverbial "infinite loop" - Example: >> q = 1 while q <= 16 q = 2 * q end q = 2 q = 4 q = 8 q = 16 q = 32 - Note how the last assignment is 'q = 32'; this is because the test that determines whether the loop continues or not is 'q <= 16', Thus when q is assigned the value 16, the test still succeeds at the next iteration, so the last statement executed in the loop is q = 2 * 16 ----------------------------------------------------------------------------- 3.3.3) NESTED LOOPS ----------------------------------------------------------------------------- - All of the above loops can be nested, i.e. we can have loops within loops - Example: >> for ii = 1 : 2 for jj = 3 : -1 : 1 [ii jj] end end ans = 1 3 ans = 1 2 ans = 1 1 ans = 2 3 ans = 2 2 ans = 2 1 - Note that the inner loop (loop variable jj) executes "most rapidly"; for each iteration through the outer loop, ii = 1 , 2 in succession, the inner loop executes, jj = 3, 2, 1 in succession +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.3.4) THE break STATEMENT (**) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - break causes an immediate exit from the (innermost) loop where it is executed - Example (contrived!): >> q = 1 while q <= 16 q = 2 * q if q > 3 break end end q = 2 q = 4 - NOTE: - If break occurs outside a loop in a script or function it terminates the execution of the file +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.3.5) THE continue STATEMENT (**) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - continue is used within a loop to "short circuit" the execution of the loop body, and proceed to the next iteration - Example: (the M rem command is equivalent to mod in Maple, so rem(n,2) = 0 or 1 for n even or odd, respectively) >> for ii = 1:5 jj = ii if rem(ii,2) == 0 continue end jj = -ii end jj = 1 jj = -1 jj = 2 jj = 3 jj = -3 jj = 4 jj = 5 jj = -5 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3.4) THE return STATEMENT +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Ordinarily, a Matlab function returns (reverts control to invoking environment) when the end of the function definition is reached. This is the case for all of the functions that we have defined/studied thus far. - At times, it is convenient to be able to exit the function BEFORE the end of the definition: for example, we may want the function to check one or more of its input arguments for validity, and return immediately should a bad input be detected. - The Matlab return statement provides this functionality. Its syntax is simply return and when this statement is encountered --- anywhere in a function definition --- the function will exit immediately - IMPORTANT! It is crucial that all of the function's output arguments are assigned a value BEFORE any return statement is encountered. Thus, e.g., when we write functions that DO check their input arguments for validity, we should include assignment statements that a set all of the outargs to SOME values BEFORE any other statements in the body of the function. EXAMPLE: - Consider the following function, 'errorreturn', which takes two input arguments, and checks that the first argument is strictly positive - If it is the function returns the sum of the arguments - If it isn't the function prints an error message and exits function rval = errorreturn(a, b) % errorreturn returns the sum of its two inargs, providing that the first % is strictly positive, otherwise it prints an error message and % exits using the return statement. % Assign a "default" value to the output argument to ensure that it % IS defined before the function returns. rval = NaN; if a <= 0 % Print the error message and return fprintf('errorreturn: First argument must be > 0'); return; end % Return the normal value rval = a + b; end - Now I will use the function (this won't work for you, yet), first with valid arguments ... >> errorreturn(2.0, 3.0) ans = 5 ... and then with invalid ... >> errorreturn(-2.0, 3.0) errorreturn: First argument must be > 0 ans = NaN - There is no limit to the number of return statements in a given function, although it is good programming style to try to keep them to a minimum - Also, return can also be used in a script: when encountered in that context, control will typically revert to the command prompt (assuming that the script was started from the command prompt) ----------------------------------------------------------------------------- EXERCISES: Implement functions as follows ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- PRELIMINARIES ----------------------------------------------------------------------------- - Be sure to define each function in a SEPARATE file ~/matlab/.m, and ensure that your Matlab session is running in ~/matlab, or Matlab won't know what to do when you try to use the function - Your final forms of the definitions should have semi-colons at the end of every statement to suppress the output from their execution when the function is called - HOWEVER, as noted previously you may find it useful to omit the semi-colons until you have your functions debugged since this provides an easy way to see exactly what is being computed as the function executes - Whenever you make changes to any '.m' file, be sure to save it, but note that you don't have to "reload" or "re-read" anything in the Matlab session (as you need to do in Maple); you simply type the name of the function/script and the updated definition will be used. ----------------------------------------------------------------------------- EXERCISES per se ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- A) myifC (defined in ~/matlab/myifC.m) ----------------------------------------------------------------------------- - myifC takes 3 inargs and returns the largest of them (you wrote this function in maple!) - Remember that Matlab IS case sensitive, so be careful naming the file that contains this function definition ----------------------------------------------------------------------------- B) myiffor (defined in ~/matlab/myiffor.m) ----------------------------------------------------------------------------- - myiffor takes 3 inargs, j1, j2, j3, all of them integers and retuns one value - If j1 is positive, it returns a ROW VECTOR of length j2, each of whose elements is j3 - If j1 is negative it returns a COLUMN VECTOR of length l2, each of whose elements is j3 - If j1 is 0 it returns 0 - IMPORTANT: Although you can implement this function without using for loops, the purpose of the exercise is to give you practice in programming with loops, so do NOT create the vectors using the : operator or the linspace command - RECALL/HINT: A vector can be created simply by using the indexing operator; e.g. ... >> v(1) = pi ... creates a length-1 row vector whose first and only element is pi. Elements can then be added to the vector by additional assignments ... >> v(2) = 6 >> v(3) = cosd(45) etc. ----------------------------------------------------------------------------- C) TESTING ----------------------------------------------------------------------------- - Test your work by creating another Matlab source file (script) ~/matlab/tfcns.m that contains appropriate calls to the two functions - Note that a script can call any number of functions; Matlab will look for the definitions as needed (i.e. you only need to write ONE testing script) - Again, until a function is debugged you may find it useful NOT to end the statements in the function body with a semi-colon, so that you see an "execution trace"---however, the final versions of the functions SHOULD include the semi-colons. - The statements in the testing script should NOT end with a semi-colon, or you will not be able to see the results of your testing! - As usual, you can execute the script via >> tfcns +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4) Matlab Startup Folder, Path, Startup File, "Crash" Files +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4.1) Matlab Startup Folder +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Each Matlab session has a special folder (directory) associated with it, known as the Startup Folder, which on the lab machines is ~/Documents/MATLAB and which was automatically created for you when you executed Matlab for the first time - For our purposes, the Startup Folder is of interest since it will be where we store a file 'startup.m' that contains commands that will be executed whenever a Matlab session starts (analogous to ~/.bashrc for bash) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4.2) Matlab path +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Similarly to the bash's path, Matlab maintains a list of directories in which to look for .m files that corresponds to a script or function that we wish to execute - You can display the current path using ... >> path ... and when you execute that command, you should see something like ... MATLABPATH /home/phys210d/Documents/MATLAB /home/phys210d/matlab /opt/MATLAB/R2013a/toolbox/matlab/testframework /opt/MATLAB/R2013a/toolbox/matlab/optimfun /opt/MATLAB/R2013a/toolbox/matlab/codetools /opt/MATLAB/R2013a/toolbox/matlab/datafun . . . ... where your login will appear in place of 'phys210d' in the above - Note that the Startup Folder is in the path, as is /home/$LOGNAME/matlab; Matlab includes these in the path by default - Also, although it does not explictly appear, if we start Matlab from the command line, then the working directory from which we invoked Matlab will also be in the path This is why Matlab finds script/function definitions if the corresponding .m files are in the directory in which the Matlab session is executing (as we have done thus far). - We can add directories (components) to the path using the 'addpath' command - For example, open a terminal window and ensure that the working directory is your home % cd - Now start up Matlab ... % matlab and try to execute a simple demonstration function, 'hello', that is defined in the directory /home/phys210/matlab >> hello Undefined function or variable 'hello'. - We get the error message since there is no file hello.m containing a definition for the function hello in any of the directories specified in the path - We can add /home/phys210/matlab to the path using the 'addpath' command. Enter the following >> addpath('/home/phys210/matlab') - Note that it is safest to enclose the directory/folder name in single quotes - Now try 'hello' again >> hello Hello world! - Since you may (eventually) have Matlab source files in various directories and/or run Matlab in directories that don't contain all of the needed source files, it can become very inconvenient to have to explicitly use addpath every time you start Matlab - Naturally, there is a solution to this problem, and again it is similar to what is done for the shell (bash) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4.3) Matlab Startup File: startup.m +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - As mentioned above, if the Matlab startup folder (~/Documents/MATLAB) contains a file named ... startup.m ... then the statements/commands in that file will be executed every time Matlab starts (specifically, they will be executed BEFORE you are presented with the command prompt) - Let's create startup.m by copying the corresponding file from phys210's account to the directory ~/Documents/MATLAB - In a terminal window, execute the following % cd ~/Documents/MATLAB % cp ~phys210/Documents/MATLAB/startup.m . Note that the second argument to the cp command is . (dot) - Examine its contents % cat startup.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Startup file for Matlab ... Commands in this file are % executed at the start of every Matlab session %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% addpath('/home/phys210/matlab'); - So now, whenever Matlab starts up, '/home/phys210/matlab' will be added to the path - Let's test this --- first exit your current Matlab session >> exit - Be sure that you're in your home directory % cd - Start Matlab again % matlab and invoke hello >> hello Hello world! - NOTE: You can add other Matlab commands to startup.m as you wish --- for example, suppose that you wanted to use 'long' as the default start-up format for the display of values. You could add format long; to startup.m to accomplish this - Here's another example of invocation of a function which is now in your Matlab path (as previously, the function is defined in ~phys210/matlab) >> greetings Greetings, user phys210d! - We can view the definition of greetings using the type command >> type greetings function [] = greetings() fprintf('Greetings, user %s!\n',getenv('LOGNAME')); end - Finally, and again in complete analogy with the PATH setting in bash, if there is more than one file .m defining the function in the list or directories stored in Matlab's path, then the first one encountered as the directories are scanned is the one that is executed - VERY IMPORTANT!! The order in which different 'addpath' commands are executed is crucial since 'addpath' PREPENDS the specified folder/directory to the search path Thus if and both contain a definition for function 'foo' in a file 'foo.m' (i.e. both /foo.m and /foo.m exist), and we want the definition in , rather than that in , to be used when we type 'foo', then the correct ordering of 'addpath' commands is addpath(''); addpath(''); +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4.4) Matlab "crash" files +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - From time to time Matlab may terminate abnormally - In such instances, Matlab may generate a "crash" file, which can be useful for the developers/maintainers of the software to examine in case the "crash" is due to a bug. - These files will usually be deposited in your home directory, and will have names of the form matlab_crash_dump. - You can safely remove these if and when they appear. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5) Displaying/outputing quantities in Matlab +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5.1) more +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - The more command enables/disables output paging. This is analogous to the bash command 'more': press the space bar to advance a page, 'q' to quit. There is no provision to back up a page. - By default, paging is disabled at startup - Turn paging on >> more on - Turn paging off >> more off - Try the following >> more on >> eye(100) >> more off >> eye(100) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5.2) disp +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - This command produces simple output, with no user control over appearance. The form of the output is essentially the same seen with interactive definition/use of vbls/expresssions, except with outthe ' =' - Syntax disp() where is a SINGLE Matlab expression, i.e. something that can be assigned to a variable - Example >> a = [1:2:11] a = 1 3 5 7 9 11 >> disp(a) 1 3 5 7 9 11 - You can supply a character string to disp, which is useful for producing explanatory/diagnostic/tracing output in a function - Example >> disp('This is a message') This is a message +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 5.3) fprintf +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - With this function, the user has control over the output format, and more than one quantity can be output with a single function call Syntax fprintf(