Function declaration

 
function [y1,...,yN] = myfun(x1,...,xM)

The above syntax declares a function named myfun that accepts inputs x1,...,xMx_1,...,x_M and returns outputs y1,...,yNy_1,...,y_N.

This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

You can save your function in a function file or a script file. A function file contains only function definitions. The name of the function file should match the name of the first function in the file. The function defined can be accessed only if you cd or addpath the directory which contains the function file.

Files can include multiple local functions or nested functions.

For readability, use the end keyword to indicate the end of each function in a file. The end keyword becomes necessary in some cases when using local functions or nested functions.

Function with One Output

% File: squareThisNumber.m
function y = squareThisNumber(x)
    y = x^2;
end
a = squareThisNumber(5)
>>  a = 25

Function with Multiple Outputs

% File: squareAndCubeThisNumber.m
function [y1,y2] = squareAndCubeThisNumber(x)
    y1 = x^2;
    y2 = x^3;
end
[a,b] = squareAndCubeThisNumber(5)
>>
  a = 25
  b = 125

Multiple Functions in a Function File

% File: squareAndCubeThisNumber2.m
function [y1,y2] = squareAndCubeThisNumber2(x)
    y1 = powerThisNumber(x,2);
    y2 = powerThisNumber(x,3);
end

function y = powerThisNumber(x,e)
    y = x^e;
end
[a,b] = squareAndCubeThisNumber2(5)
>>
  a = 25
  b = 125

Other examples:

% Sanity check for input argument
function y = average(x)
    if ~isvector(x)
        error('Input must be a vector')
    end
    y = sum(x)/length(x);
end