Chapter#6
Chapter#6
The function can be expressed in the form y = f(x) , where f(x) is usually a
mathematical expression in terms of x.
A value of y (output) is obtained when a value of x (input) is substituted in the
expression.
Many functions are programmed inside MATLAB as built-in functions, and can
be used in mathematical expressions simply by typing their name with an
argument examples are sin(x), cos(x), sqrt(x), and exp(x).
A user-defined function is a MATLAB program that is created by the user, saved
as a function file, and then can be used like a built-in function.
Function Definition Line
The first line in a function file must begin with a function definition line that has a list of inputs
and outputs. This line distinguishes a function M-file from a script M-file. Its syntax is as
follows:
Note that the output variables are enclosed in square brackets, while the input variables must be
enclosed with parentheses. The function name (here, name) should be the same as the file name
in which it is saved (with the .m extension).
Function definition line Comments
function [mpay,tpay] = loan(amount,rate,years) Three input arguments,
two
output arguments.
function [A] = RectArea(a,b) Two input arguments, one
output variables.
function trajectory(v,h,g) Three input arguments, no
output arguments.
How to construct and use an external function
First, create the Matlab program for an external function as a separate file. The filename has to be
This program defines a function, f(x) ≡ 2 x2 + 3 x + 7. The "outcome" in the program is a dummy
variable that is used to indicate the relation between the input parameter ("x") and the outcome after the
evaluation of the function. After an external function is defined, it can be used in a main program that
calls it. For example: mainprog1.m
A simple example is: cube = @ (x) x^3, which calculates the cube of the input argument.
Example of an anonymous function with one independent variable:
If x is expected to be an array, with the function calculated for each element,
then the function must be modified for element-by-element calculations.
Example of an anonymous function with several independent variables:
Then the anonymous function can be used for different values of x and y. For
example, typing HA(2,3) gives:
1) Write the following functions in the form of an anonymous function.
b) f(x,y) = 2x2-4xy+y2 Use the function to calculate for x=3 and y=4