Skip to content
MATLAB

Functions and Scripts

Define functions in separate files or at end of scripts.

By EZ4Code Team
functionanonymous

Code

% In a file named myfunc.m:
function [output1, output2] = myfunc(input1, input2)
  % MYFUNC Description
  output1 = input1 + input2;
  output2 = input1 * input2;
end

% Anonymous functions (inline)
square = @(x) x.^2;
square(5)  % 25
square([1 2 3])  % [1 4 9]

% Function handles
f = @sin;
f(pi/2)  % 1

% Multiple outputs
[a, b] = myfunc(3, 4);

Explanation

MATLAB functions must be in files matching the function name, or at the end of a script (R2016b+). Anonymous functions (@) are closures for short expressions. Function handles (@func) let you pass functions as arguments, enabling functional-style programming.

More MATLAB Snippets