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
Advanced function capability
Function
handles
Anonymous functions
Subfunctions
Nested functions
MATLAB allows input/output of data
files
Section 3.1
ELEMENTARY
MATHEMATICAL FUNCTIONS
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
>> lookfor imaginary
i
- Imaginary unit.
j
- Imaginary unit.
complex - Construct complex result
from real and imaginary
parts.
imag
- Complex imaginary part.
Finding relevant functions
Finding relevant functions
Command – disp
If user knows correct spelling of a
MATLAB function
Same
output as selecting complex
hyperlink after using lookfor command
>> disp complex
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
Section 3.2
USER-DEFINED FUNCTIONS
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[output vars]=func_name(input vars)
function – must be lower case
Output variables must be enclosed in
Input variables must be enclosed in
square brackets
parentheses
func_name must be same as name of
M-file
Use
exist function before naming a function
Simple function example
function z = fun(x,y)
u = 3*x;
z = u + 6*y.^2;
>> fun(3,7)
ans =
303
>> z = fun(3,7)
z=
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
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
function [area_square] = square(side)
OR
function area_square = square(side)
Two inputs, one output
function
[volume_box] = box(height,width,length)
One input, two outputs
function [area_circle,circumf] = circle(radius)
No named output: function sqplot(side)
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
Comments in functions
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.
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
fzero(‘function’, x0)
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('cos',2)
ans =
1.5708
Using fzero with userdefined 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
fminbnd(‘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
Finding the minimum of a
function
For functions of more than one
variable
fminsearch(‘function’, x0)
function is a string containing the
name of the function
Vector x0 is a guess that must be
supplied by the user.
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
Section 3.4
WORKING WITH DATA FILES
Importing data files
Typical ASCII file
Header lines
One
or more lines of text
Contain comments, creation date, column
headings
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
load filename
Matrix is generated
Name
of matrix is filename with extension
stipped off
load tensile_test.txt
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., .xls
extension)
A = xlsread(‘filename’)
Imports
file into array A
[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 files
Mixed text and numeric files
Files with text headers
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
Import Wizard
End of Chapter 3
Slides that I do not plan to
use
Outline
Introduction
Elementary mathematical operations
User-defined functions
Advanced function programming
Working with data files
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 handle
Use the handle to reference the function
>>sine_handle = @sin;
sine_handle
the handle
is a user-selected name for
Function handles
A common use
Pass the function as an argument to
another function
Example - plot sin x over 0 x 6 as
follows:
>>plot([0:0.01:6],sine_handle,[0:0.01:6])
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
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])
© Copyright 2026 Paperzz