Overview
• Functions in MATLAB are similar to mathematical
functions
• Why would we want to write functions in MATLAB?
• Modularize code that is used often (e.g.
quadratic formula )
• Abstract segments of code to make longer
programs easier to read
• Intuition
• Think of a function as a black box that
performs some function. You feed the function input
(arguments) and it returns you a result. You don't care what's inside the
function. All you
care about is the result. For example, you have all used the inv command in
MATLAB to
find the inverse of a matrix. Generally speaking, we don't care how the function
computed
the inverse of our matrix. In this example the original matrix is the functions
input.
• Comp onents of a function
• Function name – unique name that describes
the function (e.g. tan, exp, sqrt)
• Arguments – input supplied to the function
• Return value(s) – output of the function
• Example:

Creating User-defined Functions (Gilat 6.1 – 6.10)
Function files are really similar to script files in
MATLAB but with a more rigidly defined overall
structure (i.e. function name, input, and output). If you already have a script
file that you would like to
transform into a function file, fol low this example :
Example 1
Starting with a script file that calculates the roots of a quadratic
equation via the quadratic formula:
a=-2;
b=3;
c=5;
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
When the script file is run it outputs the following:
x1 =
-1
x2 =
2.5000
To transform this script file into a function we need to
identify the inputs and outputs. In this example,
the inputs are a, b, and c, and the outputs are roots: x1 and x2. After these
defined in our minds, we
add the following line to the beginning of the script file.
function [x1, x2] = quadratic_equation (a,b,c)
a=-2;
b=3;
c=5;
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
Now we need to delete the lines in the file that hard-code
values for a , b, and c.
function [x1, x2] = quadratic_equation (a,b,c)
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
We now have a working quadratic equation function, but it
is still partially incomplete because
traditionally functions don't output anything to the screen. So, we have to put
semicolons at the end of
each line.
function [x1, x2] = quadratic_equation (a,b,c)
x1=(-b+sqrt(b^2-4*a*c))/(2*a);
x2=(-b-sqrt(b^2-4*a*c))/(2*a);
One more important thing to note, in MATLAB a functions
name must be the same as the name the file
is saved under. This means that are function must be saved as “quadratic_equation.m”.
Any other
name and MATLAB will produce an error. We can now call our function from the
command line.
>> [x1 x2]=quadratic_equation(-2,3,5)
x1 =
-1
x2 =
2.5000
Example 2
Modified #11
Compute the equivalent resistance if the resistors are connected in series (i.e.
Req = R1 + R2 + ... + Rn)
Function file:
function REQ = req(R)
REQ = sum (R);
>> R=[50, 75, 300, 60, 500, 180, 200];
>> REQ=req(R)
REQ =
1365