matlab chapter 3 - mars at umhbmars.umhb.edu/~wgt/engr1320/matlab/matlab chapter 3 - handout...
TRANSCRIPT
Matlab - Chapter 3 3/30/2009
1
MATLAB Ch 3 – Functions & FilesMATLAB Ch 3 – Functions & Files
EGR1302
Outline
IntroductionElementary mathematical operationsElementary mathematical operationsUser-defined functionsWorking with data files
Matlab - Chapter 3 3/30/2009
2
Introduction
Review from Ch 1MATLAB mathematical functions
Pair of parentheses after function name encloses function’s argumentCan be part of mathematical expression
Users can define functionsMATLAB has commands and functions for managing the work session
Introduction
MATLAB has many built-in functionsUsers may define functionsUsers may define functions
Convenient use Advanced function capability
Function handlesAnonymous functionsSubfunctionsSubfunctionsNested functions
MATLAB allows input/output of data files
Matlab - Chapter 3 3/30/2009
3
Section 3.1
ELEMENTARY MATHEMATICAL FUNCTIONS
Finding relevant functionsCommand – lookfor
Seeks the word in the help descriptions p pof the MATLAB help system
If user does not know the name of function>> lookfor imaginaryi - Imaginary unit.j - Imaginary unit.complex Construct complex resultcomplex - Construct complex result
from real and imaginary parts.
imag - Complex imaginary part.
Matlab - Chapter 3 3/30/2009
4
Finding relevant functions
Finding relevant functionsCommand – disp help
If user knows correct spelling of a p gMATLAB function
Same output as selecting complexhyperlink after using lookfor command
>> disp help complex
Matlab - Chapter 3 3/30/2009
5
Tables 3.1-1, 3.1-2, 3.1-3
List of some common mathematical functions (pp. 142, 146, 148)(pp , , )
Exponential & logarithmicComplex number NumericTrigonometricH b liHyperbolic
Example – complex functions
>> x=-3+4i;>> y=6-8i;y ;>> mag_x = abs(x)mag_x =
5>> mag_y = abs(y)mag_y =
10>> mag_product = abs(x*y)mag_product =
50
Matlab - Chapter 3 3/30/2009
6
>> angle_x = angle(x)angle x =
Example – complex functions
angle_x =2.2143
>> angle_y = angle(y)angle_y =
-0.9273>> sum_angles = angle_x + angle_ysum angles =_ g
1.2870>> angle_product = angle(x*y)angle_product =
1.2870
Section 3.2
USER-DEFINED FUNCTIONS
Matlab - Chapter 3 3/30/2009
7
Functions files
Differences between script & functions M-files
All functions variables are localValues available only within functionUseful when repeating a set of commands multiple times
Building blocks of larger programs
First line in function function definition line
List of inputs and outputs
Function definition line
Distinguishes function from scriptfunction[output vars]=func name(input vars)
function – must be lower caseOutput variables must be enclosed in square bracketsInput variables must be enclosed in parentheses
function[output vars] func_name(input vars)
parenthesesfunc_name must be same as name of M-file
Use exist function before naming a function
Matlab - Chapter 3 3/30/2009
8
Simple function examplefunction z = fun(x,y)u = 3*x;z = u + 6*y ^2;
>> z = fun(3,7)z =
303
>> fun(3,7)ans =
303
z = u + 6 y. 2; 303
>> y = [3 4 5];>> z = fun(y,7)z =
303 306 309
>> z??? Undefined function or variable 'z'.>> u??? Undefined function or variable 'u'.
Functions
Suppress output of function by putting semicolon after the function p gcallOnly order of arguments is important, not names of argumentsArrays can be used as input argumentsMay have more than one output
Matlab - Chapter 3 3/30/2009
9
2nd simple function examplefunction [A, C] = circle(r)A = pi*r.^2;C = 2*pi*r;
>> [A, C] = circle(4)A =
50 2655
>> r = [3 4 5];>> [A, C] = circle(r)A =
C = 2 pi r; 50.2655C =
25.1327
A =28.2743 50.2655 78.5398
C =18.8496 25.1327 31.4159
Variations in function lineOne input, one output:
Brackets are optional
Two inputs, one output
One inp t t o o tp ts
function [area_square] = square(side)OR
function area_square = square(side)
function [volume_box] = box(height,width,length)
One input, two outputs
No named output: function sqplot(side)function [area_circle,circumf] = circle(radius)
function sqplot(side)
Matlab - Chapter 3 3/30/2009
10
Comments in functions
Comment lines, starting with %, may be placed anywhere in function filep yIf user types help to obtain information about function
All comment lines immediately following function definition line up to first blank or executable line is displayedor executable line is displayed
If user types lookfor commandFirst comment line is displayed
Local variables
Names of input variables given in function are local to the function
Other variable names can be used when calling the function
All variables inside a function are erased after the function finishes executingexecuting
Except when the same variable names appear in the output variable list used in the function call
Matlab - Chapter 3 3/30/2009
11
Global variables
global command declares certain variables globalg
Their values are available to the basic workspace and to other functions that declare these variables global.
Any assignment to those variables in
global a x q
Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.
Finding the zeros of a function
function is a string containing the fzero(‘function’, x0)
g gname of the functionx0 is a user-supplied guess for the zero Returns a value of x that is near x0Identifies only points where the function crosses the x-axiscrosses the x axis
Not points where the function just touches the axis. >> fzero('cos',2)
ans =1.5708
Matlab - Chapter 3 3/30/2009
12
Using fzero with user-defined functions
To find the zeros of more complicated functions, it is more convenient to ,define the function in a function filefunction y = f1(x)y = x + 2*exp(-x) - 3;
>> x = fzero('f1',-1)x =x =
-0.5831>> x = fzero('f1',2)x =
2.8887
Finding the minimum of a function
function is a string containing thefminbnd(‘function’, x1,x2)
function is a string containing the name of the function
Returns a value of x that minimizes the function in the interval x1 ≤ x ≤ x2
>> fminbnd('cos', 0,4)ans =
3.1416
Matlab - Chapter 3 3/30/2009
13
Finding the minimum of a function
For functions of more than one variable
function is a string containing the name of the functionVector x0 is a guess that must be supplied by the user
fminsearch(‘function’, x0)
supplied by the user.
>> fminsearch('f4',[0,0])ans =
-0.7071 0.0000
function f = f4(x)f = x(1).*exp(-x(1).^2-x(2).^2);
Design optimization example
Example 3.2-2, p. 161
Matlab - Chapter 3 3/30/2009
14
Section 3.4
WORKING WITH DATA FILES
Importing data files
Typical ASCII fileHeader lines
One or more lines of textContain comments, creation date, column headings
DataArranged in rows & columnsEach number in a row may be separated
SpacesCommasTab
Matlab - Chapter 3 3/30/2009
15
Importing data files
Importing an externally generated file in ASCII format
Matlab can not import data that is separated (i.e., delimited) by commasTo import a comma-delimited ASCII file, some pre-processing is required
First, open data file in a text editor (e.g., st, ope data e a te t ed to (e g ,Notepad)Second, delete the text header linesThird, replace each comma with at least one space (i.e., use Replace function)
Importing data files
Importing an externally generated file in ASCII format
Matrix is generatedName of matrix is filename with extension stipped off
load filename
load tensile test txtThis command creates a matrix named “tensile_test”
load tensile_test.txt
Matlab - Chapter 3 3/30/2009
16
Importing data files
Excel spreadsheets may be imported into Matlab
Save Excel file in 2003 format (i.e., .xlsextension)
Imports file into array A
A = xlsread(‘filename’)
[A, B] = xlsread(‘filename’)Imports all numeric data into array A and all text data into array B
[ , ] ( )
Import Wizard
Allows for importing a variety of ASCII file formats
Space-delimited filesMixed text and numeric filesFiles with text headersFiles with non-space delimiters
CommasCommasSemi-colonsTabs
Matlab - Chapter 3 3/30/2009
17
Import Wizard
What you must know before you may import the data filep
How many data items are in each row?Are the data items numeric, text strings, or a mixture of both types?Does each row or column have a descriptive text header?descriptive text header?What character is used as the delimiter that separates items in each row into columns?
Import Wizard
CautionImport Wizard overwrites any existing p y gvariable in the workspace with no warning message!
Dialog boxes ask you to:Specify the name of the file you want to importimportSpecify the delimiter used in the fileSelect the variables that you want to import
Matlab - Chapter 3 3/30/2009
18
Import Wizard
End of Chapter 3
Matlab - Chapter 3 3/30/2009
19
Slides that I do not plan to use
Outline
IntroductionElementary mathematical operationsElementary mathematical operationsUser-defined functionsAdvanced function programmingWorking with data files
Matlab - Chapter 3 3/30/2009
20
Section 3.3
ADVANCED FUNCTION PROGRAMMING
Function handles
Create a function handle to any function by using the at sign, @, before the function name.
Name the handleUse the handle to reference the function
i i l t d f
>>sine_handle = @sin;sine_handle is a user-selected name for the handle
Matlab - Chapter 3 3/30/2009
21
Function handles
A common usePass the function as an argument to ganother functionExample - plot sin x over 0 ≤ x ≤ 6 as follows:
Cumbersome way to plot the sine function
>>plot([0:0.01:6],sine_handle,[0:0.01:6])
Cumbersome way to plot the sine functionHowever, the concept can be extended to create a general purpose plotting function that accepts a function as an input
Function handles
function x = gen_plot(fun_handle, _ _interval)plot(interval, fun_handle, interval)
You may call this function to plot the sin x over 0 ≤ x ≤ 6 as follows:>>gen_plot(sine_handle,[0:0.01:6])