Function Definitions

Users can define their own functions using the function keyword.

There are several valid declaration formats depending on the number of inputs and outputs.
  0 inputs 1 inputs N inputs
0 output function myfunc() function myfunc(in) function myfunc(in1, …, inN)
1 output function out=myfunc() function out=myfunc(in) function out=myfunc(in1, …, inN)
N outputs function [out1, …, outN]=myfunc() function [out1, …, outN]=myfunc(in) function [out1, …, outN]=myfunc(in1, …, inN)
For the 0 input cases, the ()’s are optional.

The name of the function (myfunc in this case) must be a valid identifier.

After the declaration comes the function body. This is a list of statements that will be executed when the function is called. A function is terminated by the end keyword.

Any input to the function can be used like normal variables. Changes to input variables are NOT reflected in the source at call time. This paradigm is referred to as pass-by-value. For example:
function halve(a)
      a=a/2
end
This function has no effect. It divides the local variable a by 2, but this change is not propagated outside of the function. (To do this, see the global keyword.)

Variable names (input or output) are also unique to the function. A single variable name can be used by multiple functions without conflict.

Input variable values are re-initialized at each function call. Any local variables created in the function are released when the function ends. They will then be recreated at each subsequent function call. To have local variable values retained between function calls, see the persistent keyword.

When the function ends, the value of the output variables are used for any assignment to the left of the function call.
function z=myfun(a)
      z=a-1
end
y=myfun(3) % y will have a value of 2

The function body can include calls to other functions. It can even include calls to itself. This is referred to as recursion.

function b=factorial(a)
      if a==1   
         b=1
      else   
         b=factorial(a-1)*a
      end
end

If a function is defined in its own file, the final (and only the final) end is optional.