Main Content

Function Basics

Create functions, including anonymous, local, and nested functions

Functions contain sequential commands and can accept inputs and return outputs. Named functions must be defined within a program file and not at the command line. To define a function, use the syntax

function [y1,...,yN] = myfun(x1,...,xM)
where y1,...,yN are outputs, x1,...,xM are inputs, and myfun is the function name. For more information, see Create Functions in Files.

MATLAB Language Syntax

functionDeclare function name, inputs, and outputs


Create Functions in Files

This example shows how to create a function in a program file.

Add Help for Your Program

Help text appears in the Command Window when you use the help function. Create help text for your program by inserting comments at the beginning.

Configure the Run Button for Functions

Run functions that require some initial setup from the Editor by configuring the Run button.

Types of Functions

There are several types of functions available with MATLAB®, including local functions, nested functions, private functions, and anonymous functions.

Function Precedence Order

To determine which function to call when multiple functions in the current scope have the same name, MATLAB uses function precedence order.

Indexing into Function Call Results

This topic describes how to dot index into temporary variables created by function calls.


Variables in Nested and Anonymous Functions

Variables used within nested and anonymous functions must be present in the text of the code. If you add a variable to the workspace of an anonymous function, a nested function, or a function that contains a nested function dynamically, MATLAB issues an error.