section 2 programming with matlabweb.engr.oregonstate.edu/~webbky/mae4020_5020_files...all functions...

52
MAE 4020/5020 – Numerical Methods with MATLAB SECTION 2: PROGRAMMING WITH MATLAB

Upload: others

Post on 31-May-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

MAE 4020/5020 – Numerical Methods with MATLAB

SECTION 2: PROGRAMMING WITH MATLAB

Page 2: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

Functions and M‐Files2

K. Webb  MAE 4020/5020

Page 3: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

3

M‐Files

K. Webb  MAE 4020/5020

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

Page 4: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

4

M‐Files – Some Good Practices

K. Webb  MAE 4020/5020

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.

Always comment your code.Err on the side of excessive comments.

Define constants to be used in equations. Parameters can be changed in a single place.

Page 5: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

5

Functions

K. Webb  MAE 4020/5020

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

Page 6: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

6

Anatomy of a Function

K. Webb  MAE 4020/5020

Input Argument(s)

Function NameOutput(s)

Function m‐file must begin with the word ‘function’

Help comments –displayed when help is requested at the command line:

MATLAB commands that define the function

Terminate the function with the word ‘end’

Always comment your code

Page 7: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

7

M‐Files vs. Functions

K. Webb  MAE 4020/5020

M‐Files Functions

Scope of variables GlobalFacilitates debugging

LocalUse debugger to access internal function variables

Inputs/Outputs NoAll variables in memory at the time of execution are available. All variables remain in the workspace following execution.

Yes

Reuse Yes Yes

Help contents No Yes

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

Page 8: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

8

Anonymous Functions

K. Webb  MAE 4020/5020

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 outputsMay 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)

Page 9: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

9

Anonymous Functions ‐ Syntax

K. Webb  MAE 4020/5020

fhandle = @(arglist) expression

Function name  A variable of type function_handle

Pointer to the function

@ symbol generates a handle for 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

Page 10: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

10

Anonymous Functions ‐ Syntax

K. Webb  MAE 4020/5020

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

Page 11: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

11

Passing Functions to Functions

K. Webb  MAE 4020/5020

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

Page 12: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

12

Subfunctions

K. Webb  MAE 4020/5020

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

Page 13: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

13

The MATLAB Path

K. Webb  MAE 4020/5020

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

Page 14: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

14

The MATLAB Path

K. Webb  MAE 4020/5020

All functions outside of the PWD – user‐defined or built‐in – must be in the path to be accessed

Save frequently‐used user‐defined functions in one location and add to the path

E.g.,  C:\Program Files\MATLAB\R2012b\toolbox\user\

Page 15: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

Structured Programming15

K. Webb  MAE 4020/5020

Page 16: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

16

Non‐Sequential Code Structures

K. Webb  MAE 4020/5020

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

Page 17: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

• if…else statements• Logical and relational operators• switch…case statements

Conditional Statements17

K. Webb  MAE 4020/5020

Page 18: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

18

The if Statement

K. Webb  MAE 4020/5020

The basic syntax:if condition

statementsend

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

Page 19: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

19

Logical and Relational Operators

K. Webb  MAE 4020/5020

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

~ NOT– negates the logical value of an expression ~(b < 4*g)

& or && AND – both expressions must evaluate to true for result to be true (t > 0)&&(c == 5)

| or || OR – either expression must evaluate to true for result to be true (p > 1)||(m > 3)

Page 20: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

20

The if…else, if…elseif Structures

K. Webb  MAE 4020/5020

If a condition is false, specify statements to execute or evaluate another condition

if conditionstatements1

elsestatements2

end

if conditionstatements1

elseif condition2statements2

elsestatements3

end

Page 21: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

21

The if…else, if…elseif Structures

K. Webb  MAE 4020/5020

Some examples:

Note that && and || are used for logical expressions involving scalars Short‐circuit operators – second expression only evaluated if necessary

Page 22: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

22

The switch Structure

K. Webb  MAE 4020/5020

A single test expression Branching determined by the value of the test expression

switch testexpression

case value1statements1

case value2statements2

otherwise

statements3end

Page 23: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

23

The switch Structure

K. Webb  MAE 4020/5020

An example – set the value of variable B to different values depending on the value of variable A: 

Page 24: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

• for loops• while loops• Vectorization

Loops24

K. Webb  MAE 4020/5020

Page 25: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

25

The for Loop

K. Webb  MAE 4020/5020

Segment of code that repeats a specified number of times

for index = start:step:finishstatements

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

Page 26: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

26

The for Loop – Flowchart 

K. Webb  MAE 4020/5020

for i = i0:di:ifstatements

end

START i = i0

ExecuteLoopCode

i≤if

i = i+di

ENDF

T

Page 27: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

27

The for Loop – Example 

K. Webb  MAE 4020/5020

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);

Page 28: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

28

The while Loop

K. Webb  MAE 4020/5020

Segment of code that is repeated as long as a specified logical condition is true

while conditionstatements

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

Page 29: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

29

The while Loop – Example 

K. Webb  MAE 4020/5020

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

Page 30: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

30

Avoiding Loops

K. Webb  MAE 4020/5020

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 

Page 31: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

31

Avoiding Loops ‐ Vectorization

K. Webb  MAE 4020/5020

In MATLAB, arguments to functions can be vectors Could calculate five periods of a sinusoid like this:

But, vectorizationmakes it much easier and more efficient: 

Page 32: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

32

Preallocation of Memory

K. Webb  MAE 4020/5020

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 preallocatememory for ultimate size of the array:

Page 33: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

• Optional input arguments• Default values• Optional output arguments• Passing parameters to function functions• Error checking

More about Functions33

K. Webb  MAE 4020/5020

Page 34: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

34

Optional Input Arguments – Default Values

K. Webb  MAE 4020/5020

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

Page 35: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

35

Use of nargin – Example

K. Webb  MAE 4020/5020

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

Page 36: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

36

Error Checking

K. Webb  MAE 4020/5020

Use error(‘MsgString’) to exit a function and display a specified error message if error conditions are met

Page 37: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

37

Optional Output Arguments – nargout

K. Webb  MAE 4020/5020

Value of nargout is the number of output arguments passed to a function

Output Tk is calculated only if nargout==2, i.e. if Tkis requested when the function is called 

Page 38: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

38

Passing Parameters to Function Functions

K. Webb  MAE 4020/5020

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

Page 39: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

39

Using Anonymous Functions  for Passing Parameters

K. Webb  MAE 4020/5020

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

Page 40: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

40

Nested Anonymous Functions

K. Webb  MAE 4020/5020

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 xAnonymous function

• Defined by f(x,a,b)• Solely a function of x

Page 41: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

41

Passing Parameters – varargin

K. Webb  MAE 4020/5020

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

Page 42: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

42

Passing Parameters – varargin

K. Webb  MAE 4020/5020

Input argument list in function functionincludes 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

Page 43: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

File I/O43

K. Webb  MAE 4020/5020

Page 44: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

44

File I/O

K. Webb  MAE 4020/5020

It is often necessary to import data into MATLAB for processing and displayMeasured 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

Page 45: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

45

Reading/Writing Excel Files

K. Webb  MAE 4020/5020

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

Page 46: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

46

Read from an Excel File – Example 

K. Webb  MAE 4020/5020

Read data from a range of cells in an Excel spreadsheet

Store all data as a matrix Store individual columns as separate vectors

Page 47: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

47

Write to an Excel File – Example 

K. Webb  MAE 4020/5020

Data from spreadsheet is manipulated then appended to same Excel file

Sheet and cell range into which data is written are specified

Page 48: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

48

Reading Data from Text Files

K. Webb  MAE 4020/5020

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

Page 49: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

49

Reading Text Files – importdata(…)

K. Webb  MAE 4020/5020

Imported result stored in a structure Structures are arrays with named fields  Fieldsmay 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

Page 50: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

50

Reading Text Files – importdata(…)

K. Webb  MAE 4020/5020

Page 51: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

51

Additional File I/O Functions

K. Webb  MAE 4020/5020

For more control of how MATLAB reads and writes to files, the following functions may be useful:

fopen(…) fprintf(…) fread(…) fwrite(…) fclose(…)

Page 52: Section 2 Programming with MATLABweb.engr.oregonstate.edu/~webbky/MAE4020_5020_files...All functions outside of the PWD –user‐defined or built‐in –must be in the pathto be

52Exercise

Exercise – Create a Function Function

K. Webb  MAE 4020/5020

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