Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

Declare a Function in MATLAB: function Syntax, Files and Handles

Declare a function in MATLAB with the function keyword: syntax, file naming, local, nested and anonymous functions, and common errors.

Written and maintained by CASRAI Editorial Board

Last updated

Short answer: in MATLAB you declare a function with the lowercase keyword function on the first line of a function, followed by the output names, an equals sign, the function name and the input names in parentheses. Functions live in files, not at the command line, and the file name must match the name of the first function in the file. This page is for researchers and analysts who need to write their first reusable function, and it adds a comparison of the four places a function can live and a troubleshooting table for the errors that follow from getting that choice wrong.

What function declarations are used for in research

Analysis code tends to be repeated: the same cleaning step on every participant file, the same fit on every condition. Wrapping the step in a function gives it a name, defined inputs and outputs, and a single place to fix a bug. For the wider picture of what MATLAB is used for, see what MATLAB is used for.

Install or access (official source only)

MATLAB is a MathWorks product, so the install and the documentation both come from mathworks.com. Licence types and how an institution provides access are covered in MATLAB licensing. Nothing on this page depends on a particular toolbox: the function keyword is part of the base language.

How do I declare a function in MATLAB?

Create a new file whose name is the function name plus .m, and put the declaration on its first line. The keyword function is lowercase and required. The shape of the line depends on how many outputs you return:

Outputs Declaration line
One output function myOutput = myFunction(x)
Several outputs function [one,two,three] = myFunction(x)
No outputs function myFunction(x) (or function [] = myFunction(x))
No inputs The parentheses are optional

The function name starts with a letter and can contain letters, digits and underscores.

Step by step: a worked example

  1. Create a file named fact.m. The file name must match the first function in it.
  2. On the first line write the declaration: function f = fact(n).
  3. Add the body that assigns a value to the output f, then save the file in the current folder or on the MATLAB search path.
  4. Call it from the command line or from another file: y = fact(5).

The MathWorks page on creating functions in files uses exactly this fact example.

Which kind of function should I use?

Most pages cover each kind separately. Side by side, the choice is mostly about where the function needs to be callable from.

Kind Where it is defined Available to Notes
Function file (main function) Its own .m file; the first function in the file Anything on the path File name must match the function name
Local function After the main function in a function file, or inside a script Only code in that same file In scripts, each begins with function and ends with end
Nested function Inside another function Contained within its parent Requires end
Anonymous function One line, with @ Wherever the handle is passed Single executable statement; see lambda (anonymous) functions in MATLAB

Can I define a function in a function?

Yes. A nested function is a function written entirely inside its parent function and it needs an end. The first function in a function file is the main function, and any later ones are local functions that only code in that file can call. An end is required for every function in a file if any function in it contains a nested function.

How do I call a function in a script?

Call it by name with its inputs, assigning the outputs you want: y = fact(5). The function file must be in the current folder or on the search path. A script itself is called by its file name, for example mystats.

Local functions in scripts and the R2024a change

Before R2024a, local functions in a script had to sit at the end of the file, after the last script code. From R2024a, they can appear anywhere in scripts and live scripts except inside conditionals or loops. A script file cannot have the same name as a function defined in it.

How do I declare a variable in MATLAB?

A variable is created by assigning to it. For functions, the input and output variable names are the ones you put on the declaration line. An optional arguments block after the line validates inputs, for example x (1,:) {mustBeNumeric, mustBeFinite}. If a call violates it, MATLAB throws an error such as “Invalid input argument at position 1. Value must be finite.” Put required arguments before optional ones. Loops that fill variables are covered in loops in MATLAB and conditions in if statements in MATLAB.

Function handles and anonymous functions

For a short expression you do not need a file. sqr = @(x) x.^2; creates a handle, and a = sqr(5) returns 25. An anonymous function holds a single executable statement. With no inputs, t = @() datestr(now); d = t() runs it, while omitting the parentheses returns the handle without running it. Values of variables used in the expression are captured when the handle is created and persist even if you clear the variables, so make a new handle to pick up new values. Handles can be stored in a cell array and called as f{3}(x,y), and can be saved with save and load. Avoid eval, evalin, assignin and load inside the body. Cell arrays are covered in cell arrays in MATLAB.

Output and how to read it

A function returns whatever has been assigned to its named outputs when it finishes. Leave the semicolon off a call to print the result, or assign it to a variable as in y = fact(5). To format printed output, see fprintf in MATLAB.

Troubleshooting

Symptom Likely cause Fix
Function not found when called File not in the current folder or on the search path Save it in the current folder or add its folder to the path
File name and first function name differ File name differs from the first function name Rename the file to match the first function
Cannot define a function at the command line Functions are defined in files Put it in a function file, a script, or use an anonymous function
Local function in a script errors Placed before the end of the file in a release before R2024a, or inside a loop or conditional Move it to the end of the script, or outside conditionals and loops in R2024a and later
Missing end problems A nested function exists, but not every function ends with end Close every function in the file with end
Script and function share a name A script cannot have the same name as a function defined in it Rename one of them

Free alternatives

Software Type
GNU Octave Free numerical computing environment
Python with NumPy and SciPy Free general-purpose language with numerical libraries
Julia Free programming language for numerical computing

Syntax differs between these tools, so the declarations above apply to MATLAB only.

FAQ

How do I declare a function?

Start a function file with function [outputs] = name(inputs), using the lowercase keyword, and save the file with the same name as the function.

Can I define a function in a function?

Yes, as a nested function that ends with end, or as a local function later in the same file.

How do I call a function in a script?

Write its name with arguments, such as y = fact(5), with the function file on the path.

How to declare a variable in MATLAB?

Assign a value to a name. Function inputs and outputs are named on the declaration line.

Sources (official docs)

  • MathWorks, “Create Functions in Files”: https://www.mathworks.com/help/matlab/matlab_prog/create-functions-in-files.html (read 2026-11-07)
  • MathWorks, “function” reference: https://www.mathworks.com/help/matlab/ref/function.html (read 2026-11-07)
  • MathWorks, “Anonymous Functions”: https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html (read 2026-11-07)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Declare a Function in MATLAB: function Syntax, Files and Handles

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →