1 / 8

Scripts & Functions

Scripts & Functions. Scripts and functions are contained in .m-files A script contains a list of commands; when called, it runs these commands. It can access variables in the workspace. Any variables the script creates are retained in the workspace.

Télécharger la présentation

Scripts & Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Scripts & Functions • Scripts and functions are contained in .m-files • A script contains a list of commands; when called, it runs these commands. It can access variables in the workspace. Any variables the script creates are retained in the workspace. • A function begins with the function keyword. The name of the function must be identical to the file name. • Both functions and scripts are called by typing the file name. • Functions have a separate workspace, and can only “see” variables sent to it in the calling statement or those generated inside the function; conversely, variables generated inside the functions are not accessible from the workspace. • The global function can be used to define variables accessible in several workspaces. The variables must be defined with the same name and preceded by the global keyword in each workspace. • The number of input arguments is stored in nargin; the number of output arguments is stored in nargout. • After making any modifications, the file must be saved.

  2. Function Structure • A function has the following structure (scripts have a similar structure, but lack the first line): • Function definition line: this is the first line in the function, and defines the function’s name and its input and output parameters. • H1 line – this optional line contains a one-line description of the function. It begins with a % sign. • Help text – this optional line (or lines) should contain a more detailed description of the function, including the input and output arguments. All lines in this section start with %. • Function body – this is the list of commands which form the function. • Comments – comments (which are optional) can be placed at any point in the text, to explain it. They are preceded by the % sign. • Function help – when the help function is used with a user-defined function, it will return all the lines following the function definition line which begin with a % sign, until it reaches the first line without such a sign.

  3. The Function Definition Line • The function definition line is constructed as follows: function outputArguments=<functionName>(input Arguments) • Function names must fulfill the same conditions as variable names (therefore, the isvarname function can be used to check if a function name is valid). • The input arguments are the data passed to the function when it is called. They must be valid variables. When the function is called, the arguments in the calling statement are placed in the input argument variable in the corresponding position. The argument names must be separated by commas. • It is not necessary to assign data to all input arguments; however, if an argument is referred to without having been given a value, an error will occur. Also, an error will occur if too many input arguments are given. • Output arguments contain the data returned to the calling routine. If there is more than one output argument, they must be contained in brackets. • Output arguments contain the values they had when the function reaches its end. All arguments must have values at that point.

  4. Function Arguments (cont.) • The number of input and output arguments the function can be retrieved with the nargin and nargout functions. In the case of nargin, it checks how many arguments were actually supplied; decision functions may be used to determine alternate courses of action depending on how much data was supplied. • A variable number of input arguments can be handled with the varargin function. This functions is used by placing varargin in place of the (or some of the) input arguments in the function definition line. A cell array called varargin is formed, holding all the input arguments supplied, which can be accessed by index. • Similarly, the varargout function can be used to return a variable number of output arguments. The output argument in the function definition line must contain [varargout]. Before the function ends, all the output data must be placed in a cell array called varargout. • Both varargin and varargout can be in mixed argument lists, but they must be the last arguments in the list. For example, you could write function i=example(a,b,varargin) – the first two input arguments would be placed in a and b, and the rest in varargin.

  5. Decision Handling – the If statement • A decision making statement is one which executes different options depending on the result of a test • The if statement evaluates a logical expression (which can be true or false). If the statement is true, one sequence of commands is executed. • The elseif statement allows the use of a second test evaluation if the first if false, and executes a separate command sequence if it is true. • The else statement contains a sequence of commands which is executed if neither the condition in the if statement nor any of the conditions of the elseif statements is true • The if..elsif..else sequence is closed by an end keyword. • The == operator is used to test whether two scalars are identical or not. To test whether two matrices or vectors are identical, the isequal function is used. • Other useful functions are isempty (true if the matrix is empty), all (true if all of the matrix elements are nonzero), and any (true if any of the matrix elements are nonzero). • If two matrices (or vectors) are compared using ==, >, etc., the result is a matrix of the same size (both the original matrices must be identical in size) with ‘1’s where the statement is true and ‘0’s where it is false. The statement as a whole is considered true only if all the comparisons are true • Logical operators such as & (and), | (or), and ~ (not) can also be used

  6. Decision Handling – the Switch statement • The switch statement allows several conditions on a variable to be tested (it is similar to using an if..elseif structure). • Each possibility is determined by the case statement. • The sequence after the otherwise statement executes if no other case was true. • The entire statement is closed by an end keyword

  7. Loops • A loop is a section of code that repeats a number of times. • A for loop repeats for every one of the elements in its index vector. • During each iteration, the current element of the vector is loaded to the index variable. • A while loop continues executing so long as a condition is true. • The sequence is closed by the end keyword • Loops can be nested.

  8. Debugging • MatLab contains several functions and tools to assist debugging. • The F12 key can be used to set (or remove) breakpoints. These are marked by a red dot to the right of the line, and will cause a function to stop execution when it reaches the breakpoint. When the program stops due to a breakpoint, it is in keyboard mode (marked by a K>> prompt). In that state, the function workspace rather than the normal workspace is available, and function variables can be examined or changed. • Once keyboard mode is entered, the F10 key can be used to step through the function line-by-line. Each press of the key will advance program execution by one line, and then return to keyboard mode. • Keyboard mode can be entered deliberately by placing a keyboard command in the function. • Keyboard mode can be exited with the return function or the F5 key. • By using the Stop if Error/Warning option (in the Debug menu), the function can be forced to enter keyboard mode rather than stopping when it encounters an error. This allows the programmer to examine the variable values and determine the cause of the error. • The try function is also a useful debugging tool. Its structure is a try keyword, followed by a block of code, followed by a catch keyword, followed by another block of code, and followed by end. Normally, only the section of code between the try and catch keywords is executed. However, if an error is encountered there, execution of that code block stops and the function jumps to the code block following the catch keyword

More Related