SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB
2 Functions and M Files
M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The collections of commands the script or program is all saved in a single file M files can be quickly and easily re run at any time no need to re type all commands in the command window Executed by entering the m file name on the command line or by clicking the Run button
M Files Some Good Practices 4 Start m files with a comment listing the file name. File names cannot contain spaces or special characters. Additional comments with a brief overall m file description and other details is useful. clear all clears all variables stored in the workspace. clc clears the command window you ll know if error messages are from the current run. Define constants to be used in equations. Parameters can be changed in a single place. Always comment your code. Err on the side of excessive comments.
Functions 5 Functions are a specific type of m file Function m files start with the word function Can accept input arguments and return outputs Useful for certain tasks that must be performed repeatedly Functions can be called from the command line, from within m files, or from within other functions Variables within a function are local in scope Internal variables not outputs are not saved to the workspace after execution Workspace variable not available inside a function, unless passed in as input arguments
Anatomy of a Function 6 Function m file must begin with the word function Help comments displayed when help is requested at the command line: Output(s) Function Name Input Argument(s) MATLAB commands that define the function Terminate the function with the word end Always comment your code
M Files vs. Functions 7 The text advocates exclusive use of functions I recommend using functions only for reusable, modular blocks of code with inputs and outputs I always start with an m file, and may call functions from there Scope of variables Inputs/Outputs M Files Global Facilitates debugging No All variables in memory at the time of execution are available. All variables remain in the workspace following execution. Reuse Yes Yes Help contents No Yes Functions Local Use debugger to access internal function variables Yes
Anonymous Functions 8 It is often desirable to create a function without having to create a separate function file for it Anonymous functions: Can be defined within an m file or at the command line Function data type is function_handle A pointer to the function Can accept inputs, return outputs May only contain a single MATLAB expression Useful for passing functions to functions E.g. using ode45.m (a built in MATLAB function) to solve a differential equation (a user defined function)
Anonymous Functions Syntax 9 fhandle = @(arglist) expression @ symbol generates a handle for the function Function name A variable of type function_handle Pointer to the function Function definition A single executable MATLAB expression E.g. x.^2+3*y; A list of input variables E.g. @(x,y); Note that outputs are not explicitly defined
Anonymous Functions Syntax 10 Simple function that returns half of the input value May have multiple inputs First order system response inputs: time constant, value of time Inputs may be vectors Outputs may be vectors as well
Passing Functions to Functions 11 We often want to perform MATLAB functions on other functions E.g. integration, roots finding, optimization, solution of differential equations these are function functions This is the real value of anonymous functions Define an anonymous function Pass the associated function handle to the function as an input Here, integrate the function, f, from 0 to 10 using MATLAB s quad.m function
Subfunctions 12 Function files may contain other functions in addition to the main function These are subfunctions Accessible only from within the function Filename must be the name of the main function
The MATLAB Path 13 User defined functions are available for execution from within m files or at the command line In order to be accessible functions must be stored in the file structure within the MATLAB path Present working directory is always included in the path Shown in the Current Folder subwindow in the desktop Type pwd at the command line just like in UNIX or Linux the present working directory is displayed This is the directory from which you are currently executing MATLAB
The MATLAB Path 14 All functions outside of the PWD user defined or built in must be in the path to be accessed Save frequentlyused user defined functions in one location and add to the path E.g., C:\Program Files\MATLAB\R2012b\toolbox\user\
15 Structured Programming
Non Sequential Code Structures 16 Most expressions in an m file are executed sequentially line by line in the order they appear Two types of non sequential code structures: Conditional statements code that is executed only if certain conditions are met if else switch Loops code that is repeated a specified number of times or while certain conditions are met for while
17 Conditional Statements if else statements Logical and relational operators switch case statements
The if Statement 18 The basic syntax: if condition statements end Statements are executed if condition is true Condition is a logical expression Either true (evaluates to 1) or false (evaluates to 0) Makes use of logical and relational operators May use a single line for a single statement: if condition, statement, end
Logical and Relational Operators 19 Operator Relationship or Logical Operation Example == Equal to x == b ~= Not equal to k ~= 0 < Less than t < 12 > Greater than a > -5 <= Less than or equal to 7 <= f >= Greater than or equal to (4+r/6) >= 2 ~ & or && or NOT negates the logical value of an expression AND both expressions must evaluate to true for result to be true OR either expression must evaluate to true for result to be true ~(b < 4*g) (t > 0)&&(c == 5) (p > 1) (m > 3)
The if else, if elseif Structures 20 If a condition is false, specify statements to execute or evaluate another condition if condition statements 1 else statements 2 end if condition statements 1 elseif condition 2 statements 2 else statements 3 end
The if else, if elseif Structures 21 Some examples: Note that && and are used for logical expressions involving scalars Short circuit operators second expression only evaluated if necessary
The switch Structure 22 A single test expression Branching determined by the value of the test expression switch testexpression case value 1 statements 1 case value 2 statements 2 otherwise end statements 3
The switch Structure 23 An example set the value of variable B to different values depending on the value of variable A:
24 Loops for loops while loops Vectorization
The for Loop 25 Segment of code that repeats a specified number of times for index = start:step:finish statements end index initialized to value of start If index finish, statements are executed index incremented by step at end, then compared to finish once again If index > finish, MATLAB exits the loop and moves to the next line of code
The for Loop Flowchart 26 START i = i 0 for i = i 0 :di:i f statements end i i f F END T Execute Loop Code i = i+di
The for Loop Example 27 Step through a vector element by element Note use of the length() function Inefficient way to do this more later Entire loop could be replaced by b = sign(a);
The while Loop 28 Segment of code that is repeated as long as a specified logical condition is true while condition statements end If the logical expression is true at the start of the loop, then all of the code within the loop is executed If the condition becomes false part way through the loop, MATLAB will exit upon return to the beginning of the structure
The while Loop Example 29 x values displayed: 19, 26, 33 x gets incremented beyond 30 x values displayed: 19, 26 break statement causes loop exit before executing all code
Avoiding Loops 30 Loops are inefficient and slow avoid them if possible Vectorization and MATLAB s ability to operate on arrays often makes loops even nested ones unnecessary Sometimes, however, loops cannot be avoided In some cases, a loop could be avoided, but doing so may be difficult and not worth the effort e.g. speed may not be an issue Loops are powerful tools, but always question their necessity
Avoiding Loops Vectorization 31 In MATLAB, arguments to functions can be vectors Could calculate five periods of a sinusoid like this: But, vectorization makes it much easier and more efficient:
Preallocation of Memory 32 Following loop generates a cumulative sum of the elements in a vector Size of the array, total, grows each loop iteration this is slow Better to preallocate memory for ultimate size of the array:
33 More about Functions Optional input arguments Default values Optional output arguments Passing parameters to function functions Error checking
Optional Input Arguments Default Values 34 Many built in MATLAB functions have optional input arguments If not specified, a default value is assumed User defined functions may also have optional input arguments Use MATLAB function nargin within a function to check the number of input arguments passed
Use of nargin Example 35 Input variable t is optional If not specified, a default value is used nargin is equal to the number of arguments specified when the function is called If only one input argument passed, generate a default time vector Otherwise, use the specified time vector
Error Checking 36 Use error( MsgString ) to exit a function and display a specified error message if error conditions are met
Optional Output Arguments nargout 37 Value of nargout is the number of output arguments passed to a function Output Tk is calculated only if nargout==2, i.e. if Tk is requested when the function is called
Passing Parameters to Function Functions 38 We often want to perform a function on another function Integrate a function, optimize a function, etc. May want the passed function to be parameterized Here, we want to integrate from to The function,, that will be passed to the integration function is defined by parameters and Want to be able to pass those parameters to the integration function as well Avoid having to redefine each time parameters change
Using Anonymous Functions for Passing Parameters 39 Several ways to pass parameters to function functions nested anonymous functions provide one option Say we want to use MATLAB s quad.m function to perform the integration on the previous slide y=quad(f,x0,x1); Problem here is that quad.m requires that f be a function solely of the variable of integration, x f is not only a function of the variable of integration, but also of the parameters, a and b
Nested Anonymous Functions 40 Anonymous function Defined by f(x,a,b) Solely a function of x First, define the complete integrand function Need not be an anonymous function Define the parameters Could be varied as part of a loop Call the function function, passing to it the nested anonymous function, which is a function only of x
Passing Parameters varargin 41 A second method for passing parameters to function functions Add a last input parameter varargin to function function definition When calling the passed function in the function function, include varargin{:} with its input arguments Best illustrated with an example: Define a function to calculate the root mean square (RMS) value of a function Want to be able to pass parameters for the passed function, along with the function handle, to the function function
Passing Parameters varargin 42 Input argument list in function function includes varargin When passed function is invoked in the function function all variables in varargin are passed to it Parameters f and A passed to rmsfunc as varargin All functions passed to rmsfunc are functions of one independent variable t, here but not all will have same parameters
43 File I/O
File I/O 44 It is often necessary to import data into MATLAB for processing and display Measured data collected with a data acquisition system Results from simulation in COMSOL, finite element modeling programs, circuit simulators, etc. Becoming more and more common for tools to be able to export data directly to MATLAB Often need to save data as text files to be read into MATLAB and stored as arrays for processing
Reading/Writing Excel Files 45 To import data from an Excel spreadsheet: data = xlsread(filename,sheet,range) Input arguments are strings enclose in single quotes, i.e. range specified by upper left and lower right cell numbers, e.g. C3:E22 To write data to an Excel spreadsheet: xlswrite(filename,array,sheet,range) Default is first worksheet, starting from cell A1
Read from an Excel File Example 46 Read data from a range of cells in an Excel spreadsheet Store all data as a matrix Store individual columns as separate vectors
Write to an Excel File Example 47 Data from spreadsheet is manipulated then appended to same Excel file Sheet and cell range into which data is written are specified
Reading Data from Text Files 48 Data can be read from text files: data = importdata(filename,delim,nheaderlines) filename and delim are strings enclose in single quotes delim is the delimiter between data entries in the text file, e.g.,, \t, nheaderlines is an integer the number of lines to skip at the beginning of the text file before reading numerical data into an array
Reading Text Files importdata( ) 49 Imported result stored in a structure Structures are arrays with named fields Fields may be different sizes and may contain different data types strings, integers, doubles, scalars, arrays, even other structures To access data within a particular field of a structure: x = structname.fieldname Can create structures and structure fields similarly: Structname.fieldname = x
Reading Text Files importdata( ) 50
Additional File I/O Functions 51 For more control of how MATLAB reads and writes to files, the following functions may be useful: fopen( ) fprintf( ) fread( ) fwrite( ) fclose( )
Exercise Create a Function Function 52 Exercise Use case switching for different statfunc cases Loop to find max value Don t use mean.m, max.m, or rms.m Create an anonymous function in a separate m file to test: 11 31 21