Functions and Files
Functions and Files
by
Mohamed Hussein
Lecture 4
Introduction to Matlab
Functions and Files
More Mathematical Functions
ceil (x) - round to the nearest integer
toward
fix (x) - round to the nearest integer
toward 0 (zero)
floor (x) - round to the nearest integer
toward -
round (x) - round toward the nearest integer
sign (x) - +1 (if x>0), 0 (if x=0) or -1 (if x<0)
sec (x) - secant x
csc (x) - cosecant x
asec (x) - arc-secant x
User-Defined Functions
User own developed function is created using M-file with the
following features:
A function file must begins with function definition line with list of
inputs and outputs. This distinguishes a function M-file from script
M-file.
function [output variables]=function_name(input variables)
* the square bracket is optional if only one output variable is used
All variables in a function file are local which means their values
only available within the function (not in Matlab Command
window)
The filename the function being saved should have the same name
as the function (example: for function calculate the filename should
be calculate.m)
Use the command exist to check the availability of a filename
User-Defined Functions
Create the following function file (M-file) and save as cylinder1.m
function [cyl_area,cyl_volume]=cylinder1(radius,height)
%function to calculate area and volume of a cylinder
cyl_area= (2.*pi.*radius) .* height;
cyl_volume= (pi.*radius .^2) .* height;
A=
V=
Global Variable
To use a variable as global (available in function/s and Command
Window), global command can be used. To realize this let’s create the
following area_circumf .m function file
>> [a c] = area_circumf(4)
a=
50.2655
c=
25.1327
Global Variable (cont.)
>> area
<error>
>> circumf
<error>
50.2655 25.1327
Global Variable (cont.)
Lets modify the cylinder1.m file and save it as sub_cylinder.m
function [cyl_ area,cyl_volume]=sub_cylinder(height)
%function to calculate area and volume of a cylinder
global area circumf
cyl_area= circumf.*height;
cyl_volume= area.*height;
>> [ A, V] = sub_cylinder(5)
A=
125.6637
V=
251.3274
Subfunction
A function can have subfunction/s within its M-file. For example the
function cylinder can be form from function sub_cylinder and
function area_circumf (without using the global variables).
function [cyl_area,cyl_volume]=cylinder2(cir_radius,height)
%function to calculate area and volume of a cylinder
[cir_area,cir_circumf]=circle(cir_radius)
cyl_area= cir_circumf.*height;
cyl_volume= cir_area.*height;
function [a_rea,c_ircumf]=circle(radius)
%function to calculate circle area and circumference
a_rea = pi.*radius.^2;
c_ircumf = 2.*pi.*radius;
Anonymous Function
Annonymous function is a simple function created without the need
to create a M-file. It can be created in Command Window or within
another function or script. The syntex for anonymus function is:
fhandle - @(input_args) expression.