Day 5
Day 5
• First create
a function
file.
Some pointers to write a
function
• There should be no space in the function name.
• File name and function name has to be same.
Calling the function
Function with multiple outputs
Function with multiple outputs
Function in a script file
Function in a script file
Multiple functions in a function
file
• Function avg is a local function. Local functions
are only available to other functions within the
same file.
Multiple functions in a function
file
Function with argument
validation
• Define a function that restricts input to a numeric
vector that contains no Inf or NaN elements.
• In the arguments code block, (1,:) indicates that x
must be a vector. The validation functions,
{mustBeNumeric, mustBeFinite}, restrict the
elements in x to numeric values that are not Inf or
NaN.
Function with argument
validation
Function with argument
validation
Different types of functions in
MATLAB
• Anonymous Functions
• Local Functions
• Nested Functions
• Private Functions
Anonymous Functions
Functions have their own workspace, separate from the base workspace.
Therefore, none of the calls to the function triarea overwrite the value of a in the
base workspace. Instead, the function assigns the results to variables a1, a2, and
a3.