Professional Documents
Culture Documents
Functions-1 PDF
Functions-1 PDF
1
Objectives
• User-defined Functions
• Convert script files to function files
• Know how to make function files and understand the syntax used in making
function files
• Know how to make and use sub-functions
2
User-defined Functions
3
Scripts
• So far, the *.m files that I told you to make are scripts that require
inputs using the input command of matlab.
4
Functions
• Suppose we have 𝑧 = 𝑓 𝑥, 𝑦 = 𝑥 2 + 𝑦 − 1
• If we evaluate 𝑓 1, 2 , we get 1 2 + 2 − 1 = 1 + 2 − 1 = 2
• We can say that 𝑓 1, 2 = 2 which is also the value of 𝑧 for the given 𝑥, 𝑦
5
User-defined Functions
6
User-defined Functions
7
User-defined Functions
• Notice that the first line of the code always
starts with the word “function”
• Notes:
• You may opt to not have output and input
variables as long as the inputs are initialized
within the code and the output is displayed
using disp or fprintf commands.
• Always partner “function” with an “end”
statement as good programming practice.
8
Types of User-defined Functions
• You can make functions that:
9
Multiple Outputs
• You can also return multiple variables:
Returns
multiple
outputs if you
specify them
11
Subfunctions
NOTE: The filename of the function file must be the same as the
name of the main function, even when subfunctions are not present.
12
Subfunctions
• Some notes on Subfunctions:
1. Subfunctions cannot be called in the Command Window. They are only visible to
the other functions within the file.
2. Subfunctions can appear in any order, as long as the main function appears
first.
3. Local functions cannot access variables used by other functions unless you
pass them as arguments. Variables declared within any kind of function will not
appear in the workspace.
4. Local functions in the current file have precedence over functions in other
files. That is, when you call a function within a program file, MATLAB checks
whether the function is a local function before looking for other main functions.
13
Recursion/Recursive Calls
14
Recursion/Recursive Calls
• Recursion is when you call a function within itself.
15
Recursion/Recursive Calls
• Code of factorial using conditional statements and recursion.
16