MATLAB Ch 3 – Functions & Files

1 / 42

# MATLAB Ch 3 – Functions & Files - PowerPoint PPT Presentation

MATLAB Ch 3 – Functions & Files . EGR1302. Outline. Introduction Elementary mathematical operations User-defined functions Working with data files. Introduction. Review from Ch 1 MATLAB mathematical functions Pair of parentheses after function name encloses function’s argument

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## MATLAB Ch 3 – Functions & Files

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### MATLAB Ch 3 – Functions & Files

EGR1302

Outline
• Introduction
• Elementary mathematical operations
• User-defined functions
• Working with data files
Introduction
• Review from Ch 1
• MATLAB mathematical functions
• Pair of parentheses after function name encloses function’s argument
• Can be part of mathematical expression
• Users can define functions
• MATLAB has commands and functions for managing the work session
Introduction
• MATLAB has many built-in functions
• Users may define functions
• Convenient use
• Function handles
• Anonymous functions
• Subfunctions
• Nested functions
• MATLAB allows input/output of data files
Finding relevant functions
• Command – lookfor
• Seeks the word in the help descriptions of the MATLAB help system
• If user does not know the name of function

>> lookforimaginary

i - Imaginary unit.

j - Imaginary unit.

complex - Construct complex result

from real and imaginary

parts.

imag - Complex imaginary part.

Finding relevant functions
• Command – disp
• If user knows correct spelling of a MATLAB function
• Same output as selecting complex hyperlink after using lookfor command

>> dispcomplex

Tables 3.1-1, 3.1-2, 3.1-3
• List of some common mathematical functions (pp. 142, 146, 148)
• Exponential & logarithmic
• Complex number
• Numeric
• Trigonometric
• Hyperbolic
Example – complex functions

>> x=-3+4i;

>> y=6-8i;

>> mag_x = abs(x)

mag_x =

5

>> mag_y = abs(y)

mag_y =

10

>> mag_product = abs(x*y)

mag_product =

50

Example – complex functions

>> angle_x = angle(x)

angle_x =

2.2143

>> angle_y = angle(y)

angle_y =

-0.9273

>> sum_angles = angle_x + angle_y

sum_angles =

1.2870

>> angle_product = angle(x*y)

angle_product =

1.2870

Functions files
• Differences between script & functions M-files
• All functions variables are local
• Values available only within function
• Useful 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 script
• function – must be lower case
• Output variables must be enclosed in square brackets
• Input variables must be enclosed in parentheses
• func_namemust be same as name of M-file
• Use exist function before naming a function

function[output vars]=func_name(input vars)

Simple function example

function z = fun(x,y)

u = 3*x;

z = u + 6*y.^2;

>> z = fun(3,7)

z =

303

>> y = [3 4 5];

>> z = fun(y,7)

z =

303 306 309

>> fun(3,7)

ans =

303

>> z

??? Undefined function or variable 'z'.

>> u

??? Undefined function or variable 'u'.

Functions
• Suppress output of function by putting semicolon after the function call
• Only order of arguments is important, not names of arguments
• Arrays can be used as input arguments
• May have more than one output
Variations in function line
• One input, one output:
• Brackets are optional
• Two inputs, one output
• One input, two outputs
• No named output: function sqplot(side)

function [area_square] = square(side)

OR

function area_square = square(side)

function [volume_box] = box(height,width,length)

function sqplot(side)

2nd simple function example

function [A, C] = circle(r)

A = pi*r.^2;

C = 2*pi*r;

>> [A, C] = circle(4)

A =

50.2655

C =

25.1327

>> r = [3 4 5];

>> [A, C] = circle(r)

A =

28.2743 50.2655 78.5398

C =

18.8496 25.1327 31.4159

• Comment lines, starting with %, may be placed anywhere in function file
• If user types help to obtain information about function
• All comment lines immediately following function definition line up to first blank or executable line is displayed
• If user types lookfor command
• First 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 executing
• Except when the same variable names appear in the output variable list used in the function call
Global variables
• global command declares certain variables global
• Their values are available to the basic workspace and to other functions that declare these variables global.
• Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.

global a x q

Finding the zeros of a function
• function is a string containing the name of the function
• x0 is a user-supplied guess for the zero
• Returns a value of x that is near x0
• Identifies only points where the function crosses the x-axis
• Not points where the function just touches the axis.

fzero(‘function’, x0)

>> fzero('cos',2)

ans =

1.5708

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 file

function y = f1(x)

y = x + 2*exp(-x) - 3;

>> x = fzero('f1',-1)

x =

-0.5831

>> x = fzero('f1',2)

x =

2.8887

Finding the minimum of a function
• 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(‘function’, x1,x2)

>> fminbnd('cos', 0,4)

ans =

3.1416

Finding the minimum of a function
• For functions of more than one variable
• function is a string containing the name of the function
• Vector x0 is a guess that must be supplied by the user.

fminsearch(‘function’, x0)

function f = f4(x)

f = x(1).*exp(-x(1).^2-x(2).^2);

>> fminsearch('f4',[0,0])

ans =

-0.7071 0.0000

Design optimization example
• Example 3.2-2, p. 161
Importing data files
• Typical ASCII file
• One or more lines of text
• Data
• Arranged in rows & columns
• Each number in a row may be separated
• Spaces
• Commas
• Tab
Importing data files
• Importing an externally generated file in ASCII format
• Matlab can not import data that is separated (i.e., delimited) by commas
• To import a comma-delimited ASCII file, some pre-processing is required
• First, open data file in a text editor (e.g., Notepad)
• Second, delete the text header lines
• Third, 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 generated
• Name of matrix is filename with extension stipped off
• This command creates a matrix named “tensile_test”

Importing data files
• Excel spreadsheets may be imported into Matlab
• Save Excel file in 2003 format (i.e., .xlsextension)
• Imports file into array A
• 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 files
• Mixed text and numeric files
• Files with non-space delimiters
• Commas
• Semi-colons
• Tabs
Import Wizard
• What you must know before you may import the data file
• 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?
• What character is used as the delimiter that separates items in each row into columns?
Import Wizard
• Caution
• Import Wizard overwrites any existing variable in the workspace with no warning message!
• Dialog boxes ask you to:
• Specify the name of the file you want to import
• Specify the delimiter used in the file
• Select the variables that you want to import
Outline
• Introduction
• Elementary mathematical operations
• User-defined functions
• Working with data files
Function handles
• Create a function handle to any function by using the at sign, @, before the function name.
• Name the handle
• Use the handle to reference the function
• sine_handle is a user-selected name for the handle

>>sine_handle = @sin;

Function handles
• A common use
• Pass the function as an argument to another function
• Example - plot sin x over 0 £x £ 6 as follows:
• Cumbersome way to plot the sine function
• However, the concept can be extended to create a general purpose plotting function that accepts a function as an input

>>plot([0:0.01:6],sine_handle,[0:0.01:6])

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])
• or
• >>gen_plot(@sin,[0:0.01:6])