Functions and Scripts
*********************

Complicated Octave programs can often be simplified by defining functions. Functions can be defined directly on the command line during interactive Octave sessions, or in external files, and can be called just like built-in functions.

Introduction to Function and Script Files
=========================================

There are seven different things covered in this section.

 1. Typing in a function at the command prompt.

 2. Storing a group of commands in a file --- called a script file.

 3. Storing a function in a file---called a function file.

 4. Subfunctions in function files.

 5. Multiple functions in one script file.

 6. Private functions.

 7. Nested functions.

Both function files and script files end with an extension of .m, for MATLAB compatibility.  If you want more than one independent functions in a file, it must be a script file (see Script Files), and to use these functions you must execute the script file before you can use the functions that are in the script file.

Defining Functions
==================

In its simplest form, the definition of a function named NAME looks like this:

     function NAME
       BODY
     endfunction

A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit.  Functions share the same pool of names as variables.

The function BODY consists of Octave statements.  It is the most important part of the definition, because it says what the function should actually do.

For example, here is a function that, when executed, will ring the bell on your terminal (assuming that it is possible to do so):

     function wakeup
       printf ("\a");
     endfunction

The printf statement (see Input and Output) simply tells Octave to print the string "\a".  The special character \a stands for the alert character (ASCII 7).  See Strings.

Once this function is defined, you can ask Octave to evaluate it by typing the name of the function.

Normally, you will want to pass some information to the functions you define.  The syntax for passing parameters to a function in Octave is

     function NAME (ARG-LIST)
       BODY
     endfunction

where ARG-LIST is a comma-separated list of the function's arguments.  When the function is called, the argument names are used to hold the argument values given in the call.  The list of arguments may be empty, in which case this form is equivalent to the one shown above.

To print a message along with ringing the bell, you might modify the wakeup to look like this:

     function wakeup (message)
       printf ("\a%s\n", message);
     endfunction

Calling this function using a statement like this

     wakeup ("Rise and shine!");

will cause Octave to ring your terminal's bell and print the message Rise and shine!, followed by a newline character (the \n in the first argument to the printf statement).

In most cases, you will also want to get some information back from the functions you define.  Here is the syntax for writing a function that returns a single value:

     function RET-VAR = NAME (ARG-LIST)
       BODY
     endfunction

The symbol RET-VAR is the name of the variable that will hold the value to be returned by the function.  This variable must be defined before the end of the function body in order for the function to return a value.

Variables used in the body of a function are local to the function.  Variables named in ARG-LIST and RET-VAR are also local to the function.  See Global Variables, for information about how to access global variables inside a function.

For example, here is a function that computes the average of the elements of a vector:

     function retval = avg (v)
       retval = sum (v) / length (v);
     endfunction

If we had written avg like this instead,

     function retval = avg (v)
       if (isvector (v))
         retval = sum (v) / length (v);
       endif
     endfunction

and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this:

     error: value on right hand side of assignment is undefined

because the body of the if statement was never executed, and retval was never defined.  To prevent obscure errors like this, it is a good idea to always make sure that the return variables will always have values, and to produce meaningful error messages when problems are encountered.  For example, avg could have been written like this:

     function retval = avg (v)
       retval = 0;
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

There is still one remaining problem with this function.  What if it is called without an argument?  Without additional error checking, Octave will probably print an error message that won't really help you track down the source of the error.  To allow you to catch errors like this, Octave provides each function with an automatic variable called nargin.  Each time a function is called, nargin is automatically initialized to the number of arguments that have actually been passed to the function.  For example, we might rewrite the avg function like this:

     function retval = avg (v)
       retval = 0;
       if (nargin != 1)
         usage ("avg (vector)");
       endif
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

Octave automatically reports an error for functions written in .m file code if they are called with more arguments than expected.  Octave does not automatically report an error if a function is called with too few arguments, since functions in general may have default arguments, but any attempt to use a variable that has not been given a value will result in an error. Functions can check the arguments they are called with to avoid such problems and to provide more context-specific error messages.

 -- N =: nargin ()
 -- N =: nargin (FCN)
     Report the number of input arguments to a function.

     Called from within a function, return the number of arguments passed to the function.  At the top level, return the number of command line arguments passed to Octave.

     If called with the optional argument FCN---a function name or handle---return the declared number of arguments that the function can accept.

     If the last argument to FCN is VARARGIN the returned value is negative.  For example, the function union for sets is declared as

          function [y, ia, ib] = union (a, b, varargin)

          and

          nargin ("union")
          => -3

     Programming Note: nargin does not work on compiled functions (.oct files) such as built-in or dynamically loaded functions. nargout, narginchk, varargin, inputname

 -- NAMESTR =: inputname (N)
 -- NAMESTR =: inputname (N, IDS_ONLY)
     Return the name of the N-th argument to the calling function.

     If the argument is not a simple variable name, return an empty string. Examples which will return "" are numbers (5.1), expressions (Y/2), and cell or structure indexing (C{1} or S.FIELD).

     inputname is only useful within a function.  When used at the command line or within a script it always returns an empty string.

     By default, return an empty string if the N-th argument is not a valid variable name.  If the optional argument IDS_ONLY is false, return the text of the argument even if it is not a valid variable name.  This is an Octave extension that allows the programmer to view exactly how the function was invoked even when the inputs are complex expressions. nargin, narginchk

 -- VAL =: silent_functions ()
 -- OLD_VAL =: silent_functions (NEW_VAL)
 -- OLD_VAL =: silent_functions (NEW_VAL, "local")
     Query or set the internal variable that controls whether internal output from a function is suppressed.

     If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

Returning from a Function
=========================

The body of a user-defined function can contain a return statement. This statement returns control to the rest of the Octave program.  It looks like this:

     return

Unlike the return statement in C, Octave's return statement cannot be used to return a value from a function.  Instead, you must assign values to the list of return variables that are part of the function statement.  The return statement simply makes it easier to exit a function from a deeply nested loop or conditional statement.

Here is an example of a function that checks to see if any elements of a vector are nonzero.

     function retval = any_nonzero (v)
       retval = 0;
       for i = 1:length (v)
         if (v (i) != 0)
           retval = 1;
           return;
         endif
       endfor
       printf ("no nonzero elements found\n");
     endfunction

Note that this function could not have been written using the break statement to exit the loop once a nonzero value is found without adding extra logic to avoid printing the message if the vector does contain a nonzero element.

 -- return:
     When Octave encounters the keyword return inside a function or script, it returns control to the caller immediately.  At the top level, the return statement is ignored.  A return statement is assumed at the end of every function definition.

Multiple Return Values
======================

Unlike many other computer languages, Octave allows you to define functions that return more than one value.  The syntax for defining functions that return multiple values is

     function [RET-LIST] = NAME (ARG-LIST)
       BODY
     endfunction

where NAME, ARG-LIST, and BODY have the same meaning as before, and RET-LIST is a comma-separated list of variable names that will hold the values returned from the function.  The list of return values must have at least one element.  If RET-LIST has only one element, this form of the function statement is equivalent to the form described in the previous section.

Here is an example of a function that returns two values, the maximum element of a vector and the index of its first occurrence in the vector.

     function [max, idx] = vmax (v)
       idx = 1;
       max = v (idx);
       for i = 2:length (v)
         if (v (i) > max)
           max = v (i);
           idx = i;
         endif
       endfor
     endfunction

In this particular case, the two values could have been returned as elements of a single array, but that is not always possible or convenient.  The values to be returned may not have compatible dimensions, and it is often desirable to give the individual return values distinct names.

It is possible to use the nthargout function to obtain only some of the return values or several at once in a cell array. See Cell Array Objects.

 -- ARG =: nthargout (N, FCN, ...)
 -- ARG =: nthargout (N, NTOT, FCN, ...)
     Return the Nth output argument of the function specified by the function handle or string FCN.

     Any additional arguments are passed directly to FCN.  The total number of arguments to call FCN with can be passed in NTOT; by default NTOT is N.  The input N can also be a vector of indices of the output, in which case the output will be a cell array of the requested output arguments.

     The intended use of nthargout is to avoid intermediate variables. For example, when finding the indices of the maximum entry of a matrix, the following two compositions of nthargout

          M = magic (5);
          cell2mat (nthargout ([1, 2], @ind2sub, size (M),
                               nthargout (2, @max, M(:))))
          => 5   3

     are completely equivalent to the following lines:

          M = magic (5);
          [~, idx] = max (M(:));
          [i, j] = ind2sub (size (M), idx);
          [i, j]
          => 5   3

     It can also be helpful to have all output arguments collected in a single cell array as the following code demonstrates:

          USV = nthargout ([1:3], @svd, hilb (5));

     nargin, nargout, varargin, varargout, isargout

In addition to setting nargin each time a function is called, Octave also automatically initializes nargout to the number of values that are expected to be returned.  This allows you to write functions that behave differently depending on the number of values that the user of the function has requested.  The implicit assignment to the built-in variable ans does not figure in the count of output arguments, so the value of nargout may be zero.

The svd and hist functions are examples of built-in functions that behave differently depending on the value of nargout.  For example, hist will draw a histogram when called with no output variables, but if called with outputs it will return the frequency counts and/or bin centers without creating a plot.

It is possible to write functions that only set some return values.  For example, calling the function

     function [x, y, z] = f ()
       x = 1;
       z = 2;
     endfunction

as

     [a, b, c] = f ()

produces:

     a = 1

     b = [](0x0)

     c = 2

along with a warning.

 -- N =: nargout ()
 -- N =: nargout (FCN)
     Report the number of output arguments from a function.

     Called from within a function, return the number of values the caller expects to receive.  At the top level, nargout with no argument is undefined and will produce an error.

     If called with the optional argument FCN---a function name or handle---return the number of declared output values that the function can produce.

     If the final output argument is VARARGOUT the returned value is negative.

     For example,

          f ()

     will cause nargout to return 0 inside the function f and

          [s, t] = f ()

     will cause nargout to return 2 inside the function f.

     In the second usage,

          nargout (@histc)   # or nargout ("histc") using a string input

     will return 2, because histc has two outputs, whereas

          nargout (@imread)

     will return -2, because imread has two outputs and the second is VARARGOUT.

     Programming Note.  nargout does not work for built-in functions and returns -1 for all anonymous functions. nargin, varargout, isargout, nthargout

Variable-length Return Lists
============================

It is possible to return a variable number of output arguments from a function using a syntax that's similar to the one used with the special varargin parameter name.  To let a function return a variable number of output arguments the special output parameter name varargout is used.  As with varargin, varargout is a cell array that will contain the requested output arguments.

As an example the following function sets the first output argument to 1, the second to 2, and so on.

     function varargout = one_to_n ()
       for i = 1:nargout
         varargout{i} = i;
       endfor
     endfunction

When called this function returns values like this

     [a, b, c] = one_to_n ()
          => a =  1
          => b =  2
          => c =  3

If varargin (varargout) does not appear as the last element of the input (output) parameter list, then it is not special, and is handled the same as any other parameter name.

 -- [R1, R2, ..., RN] =: deal (A)
 -- [R1, R2, ..., RN] =: deal (A1, A2, ..., AN)

     Copy the input parameters into the corresponding output parameters.

     If only a single input parameter is supplied, its value is copied to each of the outputs.

     For example,

          [a, b, c] = deal (x, y, z);

     is equivalent to

          a = x;
          b = y;
          c = z;

     and

          [a, b, c] = deal (x);

     is equivalent to

          a = b = c = x;

     Programming Note: deal is often used with comma-separated lists derived from cell arrays or structures.  This is unnecessary as the interpreter can perform the same action without the overhead of a function call.  For example:

          c = {[1 2], "Three", 4};
          [x, y, z] = c{:}
          =>
             x =

                1   2

             y = Three
             z =  4

     cell2struct, struct2cell, repmat

Variable-length Argument Lists
==============================

Sometimes the number of input arguments is not known when the function is defined.  As an example think of a function that returns the smallest of all its input arguments.  For example:

     a = smallest (1, 2, 3);
     b = smallest (1, 2, 3, 4);

In this example both a and b would be 1.  One way to write the smallest function is

     function val = smallest (arg1, arg2, arg3, arg4, arg5)
       BODY
     endfunction

and then use the value of nargin to determine which of the input arguments should be considered.  The problem with this approach is that it can only handle a limited number of input arguments.

If the special parameter name varargin appears at the end of a function parameter list it indicates that the function takes a variable number of input arguments.  Using varargin the function looks like this

     function val = smallest (varargin)
       BODY
     endfunction

In the function body the input arguments can be accessed through the variable varargin.  This variable is a cell array containing all the input arguments.  See Cell Arrays, for details on working with cell arrays.  The smallest function can now be defined like this

     function val = smallest (varargin)
       val = min ([varargin{:}]);
     endfunction

This implementation handles any number of input arguments, but it's also a very simple solution to the problem.

A slightly more complex example of varargin is a function print_arguments that prints all input arguments.  Such a function can be defined like this

     function print_arguments (varargin)
       for i = 1:length (varargin)
         printf ("Input argument %d: ", i);
         disp (varargin{i});
       endfor
     endfunction

This function produces output like this

     print_arguments (1, "two", 3);
          -| Input argument 1:  1
          -| Input argument 2: two
          -| Input argument 3:  3

 -- [REG, PROP] =: parseparams (PARAMS)
 -- [REG, VAR1, ...] =: parseparams (PARAMS, NAME1, DEFAULT1, ...)
     Return in REG the cell elements of PARAM up to the first string element and in PROP all remaining elements beginning with the first string element.

     For example:

          [reg, prop] = parseparams ({1, 2, "linewidth", 10})
          reg =
          {
            [1,1] = 1
            [1,2] = 2
          }
          prop =
          {
            [1,1] = linewidth
            [1,2] = 10
          }

     The parseparams function may be used to separate regular numeric arguments from additional arguments given as property/value pairs of the VARARGIN cell array.

     In the second form of the call, available options are specified directly with their default values given as name-value pairs.  If PARAMS do not form name-value pairs, or if an option occurs that does not match any of the available options, an error occurs.

     When called from an m-file function, the error is prefixed with the name of the caller function.

     The matching of options is case-insensitive.

     varargin, inputParser

Ignoring Arguments
==================

In the formal argument list, it is possible to use the dummy placeholder ~ instead of a name.  This indicates that the corresponding argument value should be ignored and not stored to any variable.

     function val = pick2nd (~, arg2)
       val = arg2;
     endfunction

The value of nargin is not affected by using this declaration.

Return arguments can also be ignored using the same syntax.  For example, the sort function returns both the sorted values, and an index vector for the original input which will result in a sorted output.  Ignoring the second output is simple---don't request more than one output.  But ignoring the first, and calculating just the second output, requires the use of the ~ placeholder.

     x = [2, 3, 1];
     [s, i] = sort (x)
     =>
     s =

        1   2   3

     i =

        3   1   2

     [~, i] = sort (x)
     =>
     i =

        3   1   2

When using the ~ placeholder, commas---not whitespace---must be used to separate output arguments.  Otherwise, the interpreter will view ~ as the logical not operator.

     [~ i] = sort (x)
     parse error:

       invalid left hand side of assignment

Functions may take advantage of ignored outputs to reduce the number of calculations performed.  To do so, use the isargout function to query whether the output argument is wanted.  For example:

     function [out1, out2] = long_function (x, y, z)
       if (isargout (1))
         ## Long calculation
         ...
         out1 = result;
       endif
       ...
     endfunction

 -- TF =: isargout (K)
     Within a function, return a logical value indicating whether the argument K will be assigned to a variable on output.

     If the result is false, the argument has been ignored during the function call through the use of the tilde (~) special output argument.  Functions can use isargout to avoid performing unnecessary calculations for outputs which are unwanted.

     If K is outside the range 1:max (nargout), the function returns false.  K can also be an array, in which case the function works element-by-element and a logical array is returned.  At the top level, isargout returns an error. nargout, varargout, nthargout

Default Arguments
=================

Since Octave supports variable number of input arguments, it is very useful to assign default values to some input arguments.  When an input argument is declared in the argument list it is possible to assign a default value to the argument like this

     function NAME (ARG1 = VAL1, ...)
       BODY
     endfunction

If no value is assigned to ARG1 by the user, it will have the value VAL1.

As an example, the following function implements a variant of the classic ``Hello, World'' program.

     function hello (who = "World")
       printf ("Hello, %s!\n", who);
     endfunction

When called without an input argument the function prints the following

     hello ();
          -| Hello, World!

and when it's called with an input argument it prints the following

     hello ("Beautiful World of Free Software");
          -| Hello, Beautiful World of Free Software!

Sometimes it is useful to explicitly tell Octave to use the default value of an input argument.  This can be done writing a : as the value of the input argument when calling the function.

     hello (:);
          -| Hello, World!

Validating Arguments
====================

Octave is a weakly typed programming language.  Thus it is possible to call a function with arguments, that probably cause errors or might have undesirable side effects.  For example calling a string processing function with a huge sparse matrix.

It is good practice at the head of a function to verify that it has been called correctly.  Octave offers several functions for this purpose.

Validating the number of Arguments
----------------------------------

In Octave the following idiom is seen frequently at the beginning of a function definition:

     if (nargin < min_#_inputs || nargin > max_#_inputs)
       print_usage ();
     endif

which stops the function execution and prints a message about the correct way to call the function whenever the number of inputs is wrong.

Similar error checking is provided by narginchk and nargoutchk.

 -- narginchk: (MINARGS, MAXARGS)
     Check for correct number of input arguments.

     Generate an error message if the number of arguments in the calling function is outside the range MINARGS and MAXARGS.  Otherwise, do nothing.

     Both MINARGS and MAXARGS must be scalar numeric values.  Zero, Inf, and negative values are all allowed, and MINARGS and MAXARGS may be equal.

     Note that this function evaluates nargin on the caller.

     nargoutchk, error, nargout, nargin

 -- nargoutchk: (MINARGS, MAXARGS)
 -- MSGSTR =: nargoutchk (MINARGS, MAXARGS, NARGS)
 -- MSGSTR =: nargoutchk (MINARGS, MAXARGS, NARGS, "string")
 -- MSGSTRUCT =: nargoutchk (MINARGS, MAXARGS, NARGS, "struct")
     Check for correct number of output arguments.

     In the first form, return an error if the number of arguments is not between MINARGS and MAXARGS.  Otherwise, do nothing.  Note that this function evaluates the value of nargout on the caller so its value must have not been tampered with.

     Both MINARGS and MAXARGS must be numeric scalars.  Zero, Inf, and negative are all valid, and they can have the same value.

     For backwards compatibility, the other forms return an appropriate error message string (or structure) if the number of outputs requested is invalid.

     This is useful for checking to that the number of output arguments supplied to a function is within an acceptable range. narginchk, error, nargout, nargin

Validating the type of Arguments
--------------------------------

Besides the number of arguments, inputs can be checked for various properties.  validatestring is used for string arguments and validateattributes for numeric arguments.

 -- VALIDSTR =: validatestring (STR, STRARRAY)
 -- VALIDSTR =: validatestring (STR, STRARRAY, FUNCNAME)
 -- VALIDSTR =: validatestring (STR, STRARRAY, FUNCNAME, VARNAME)
 -- VALIDSTR =: validatestring (..., POSITION)
     Verify that STR is an element, or substring of an element, in STRARRAY.

     When STR is a character string to be tested, and STRARRAY is a cell array of strings of valid values, then VALIDSTR will be the validated form of STR where validation is defined as STR being a member or substring of VALIDSTR.  This is useful for both verifying and expanding short options, such as "r", to their longer forms, such as "red".  If STR is a substring of VALIDSTR, and there are multiple matches, the shortest match will be returned if all matches are substrings of each other.  Otherwise, an error will be raised because the expansion of STR is ambiguous.  All comparisons are case insensitive.

     The additional inputs FUNCNAME, VARNAME, and POSITION are optional and will make any generated validation error message more specific.

     Examples:

          validatestring ("r", {"red", "green", "blue"})
          => "red"

          validatestring ("b", {"red", "green", "blue", "black"})
          => error: validatestring: multiple unique matches were found for 'b':
             blue, black

     strcmp, strcmpi, validateattributes, inputParser

 -- validateattributes: (A, CLASSES, ATTRIBUTES)
 -- validateattributes: (A, CLASSES, ATTRIBUTES, ARG_IDX)
 -- validateattributes: (A, CLASSES, ATTRIBUTES, FUNC_NAME)
 -- validateattributes: (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME)
 -- validateattributes: (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME, ARG_IDX)
     Check validity of input argument.

     Confirms that the argument A is valid by belonging to one of CLASSES, and holding all of the ATTRIBUTES.  If it does not, an error is thrown, with a message formatted accordingly.  The error message can be made further complete by the function name FUN_NAME, the argument name ARG_NAME, and its position in the input ARG_IDX.

     CLASSES must be a cell array of strings (an empty cell array is allowed) with the name of classes (remember that a class name is case sensitive).  In addition to the class name, the following categories names are also valid:

     "float"
          Floating point value comprising classes "double" and "single".

     "integer"
          Integer value comprising classes (u)int8, (u)int16, (u)int32, (u)int64.

     "numeric"
          Numeric value comprising either a floating point or integer value.

     ATTRIBUTES must be a cell array with names of checks for A. Some of them require an additional value to be supplied right after the name (see details for each below).

     "<="
          All values are less than or equal to the following value in ATTRIBUTES.

     "<"
          All values are less than the following value in ATTRIBUTES.

     ">="
          All values are greater than or equal to the following value in ATTRIBUTES.

     ">"
          All values are greater than the following value in ATTRIBUTES.

     "2d"
          A 2-dimensional matrix.  Note that vectors and empty matrices have 2 dimensions, one of them being of length 1, or both length 0.

     "3d"
          Has no more than 3 dimensions.  A 2-dimensional matrix is a 3-D matrix whose 3rd dimension is of length 1.

     "binary"
          All values are either 1 or 0.

     "column"
          Values are arranged in a single column.

     "decreasing"
          No value is NAN, and each is less than the preceding one.

     "diag"
          Value is a diagonal matrix.

     "even"
          All values are even numbers.

     "finite"
          All values are finite.

     "increasing"
          No value is NAN, and each is greater than the preceding one.

     "integer"
          All values are integer.  This is different than using isinteger which only checks its an integer type.  This checks that each value in A is an integer value, i.e., it has no decimal part.

     "ncols"
          Has exactly as many columns as the next value in ATTRIBUTES.

     "ndims"
          Has exactly as many dimensions as the next value in ATTRIBUTES.

     "nondecreasing"
          No value is NAN, and each is greater than or equal to the preceding one.

     "nonempty"
          It is not empty.

     "nonincreasing"
          No value is NAN, and each is less than or equal to the preceding one.

     "nonnan"
          No value is a NaN.

     "nonnegative"
          All values are non negative.

     "nonsparse"
          It is not a sparse matrix.

     "nonzero"
          No value is zero.

     "nrows"
          Has exactly as many rows as the next value in ATTRIBUTES.

     "numel"
          Has exactly as many elements as the next value in ATTRIBUTES.

     "odd"
          All values are odd numbers.

     "positive"
          All values are positive.

     "real"
          It is a non-complex matrix.

     "row"
          Values are arranged in a single row.

     "scalar"
          It is a scalar.

     "size"
          Its size has length equal to the values of the next in ATTRIBUTES. The next value must is an array with the length for each dimension.  To ignore the check for a certain dimension, the value of NaN can be used.

     "square"
          Is a square matrix.

     "vector"
          Values are arranged in a single vector (column or vector).

     isa, validatestring, inputParser

As alternatives to validateattributes there are several shorter convenience functions to check for individual properties.

 -- mustBeFinite: (X)

     Require that input X is finite.

     Raise an error if any element of the input X is not finite, as determined by isfinite (x).

     mustBeNonNan, isfinite

 -- mustBeGreaterThan: (X, C)

     Require that input X is greater than C.

     Raise an error if any element of the input X is not greater than C, as determined by X > C.

     mustBeGreaterThanOrEqual, mustBeLessThan, gt

 -- mustBeGreaterThanOrEqual: (X, C)

     Require that input X is greater than or equal to C.

     Raise an error if any element of the input X is not greater than or equal to C, as determined by X >= C.

     mustBeGreaterThan, mustBeLessThanOrEqual, ge

 -- mustBeInteger: (X)

     Require that input X is integer-valued (but not necessarily integer-typed).

     Raise an error if any element of the input X is not a finite, real, integer-valued numeric value, as determined by various checks.

     mustBeNumeric

 -- mustBeLessThan: (X, C)

     Require that input X is less than C.

     Raise an error if any element of the input X is not less than C, as determined by X < C.

     mustBeLessThanOrEqual, mustBeGreaterThan, lt

 -- mustBeLessThanOrEqual: (X, C)

     Require that input is less than or equal to a given value.

     Raise an error if any element of the input X is not less than or equal to C, as determined by X <= C.

     mustBeLessThan, mustBeGreaterThanOrEqual, le

 -- mustBeMember: (X, VALID)

     Require that input X is a member of a set of given valid values.

     Raise an error if any element of the input X is not a member of the set VALID, as determined by ismember (X).

     Programming Note: char inputs may behave strangely because of the interaction between chars and cellstrings when calling ismember on them.  But it will probably "do what you mean" if you just use it naturally. To guarantee operation, convert all char arrays to cellstrings with cellstr.

     mustBeNonempty, ismember

 -- mustBeNegative: (X)

     Require that input X is negative.

     Raise an error if any element of the input X is not negative, as determined by X < 0.

     mustBeNonnegative

 -- mustBeNonempty: (X)

     Require that input X is nonempty.

     Raise an error if the input X is empty, as determined by isempty (X).

     mustBeMember, mustBeNonzero, isempty

 -- mustBeNonNan: (X)

     Require that input X is non-NaN.

     Raise an error if any element of the input X is NaN, as determined by isnan (X).

     mustBeFinite, mustBeNonempty, isnan

 -- mustBeNonnegative: (X)

     Require that input X is not negative.

     Raise an error if any element of the input X is negative, as determined by X >= 0.

     mustBeNonzero, mustBePositive

 -- mustBeNonpositive: (X)

     Require that input X is not positive.

     Raise an error if any element of the input X is positive, as determined by X <= 0.

     mustBeNegative, mustBeNonzero

 -- mustBeNonsparse: (X)

     Require that input X is not sparse.

     Raise an error if the input X is sparse, as determined by issparse (X).

     issparse

 -- mustBeNonzero: (X)

     Require that input X is not zero.

     Raise an error if any element of the input X is zero, as determined by X == 0.

     mustBeNonnegative, mustBePositive

 -- mustBeNumeric: (X)

     Require that input X is numeric.

     Raise an error if the input X is not numeric, as determined by isnumeric (X).

     mustBeNumericOrLogical, isnumeric

 -- mustBeNumericOrLogical: (X)

     Require that input X is numeric or logical.

     Raise an error if the input X is not numeric or logical, as determined by isnumeric (X) || islogical (X).

     mustBeNumeric, isnumeric, islogical

 -- mustBePositive: (X)

     Require that input X is positive.

     Raise an error if any element of the input X is not positive, as determined by X > 0.

     mustBeNonnegative, mustBeNonzero

 -- mustBeReal: (X)

     Require that input X is real.

     Raise an error if the input X is not real, as determined by isreal (X).

     mustBeFinite, mustBeNonNan, isreal

Parsing Arguments
-----------------

If none of the preceding validation functions is sufficient there is also the class inputParser which can perform extremely complex input checking for functions.

 -- P =: inputParser ()
     Create object P of the inputParser class.

     This class is designed to allow easy parsing of function arguments.  The class supports four types of arguments:

      1. mandatory (see addRequired);

      2. optional (see addOptional);

      3. named (see addParameter);

      4. switch (see addSwitch).

     After defining the function API with these methods, the supplied arguments can be parsed with the parse method and the results accessed with the Results accessor.

 -- inputParser.Parameters:
     Return the list of parameter names already defined.  (read-only)

 -- inputParser.Results:
     Return a structure with argument names as fieldnames and corresponding values.  (read-only)

 -- inputParser.Unmatched:
     Return a structure similar to Results, but for unmatched parameters.  (read-only) See the KeepUnmatched property.

 -- inputParser.UsingDefaults:
     Return cell array with the names of arguments that are using default values.  (read-only)

 -- inputParser.FunctionName: = NAME
     Set function name to be used in error messages; Defaults to empty string.

 -- inputParser.CaseSensitive: = BOOLEAN
     Set whether matching of argument names should be case sensitive; Defaults to false.

 -- inputParser.KeepUnmatched: = BOOLEAN
     Set whether string arguments which do not match any Parameter are parsed and stored in the Unmatched property; Defaults to false.  If false, an error will be emitted at the first unrecognized argument and parsing will stop.  Note that since Switch and Parameter arguments can be mixed, it is not possible to know the type of the unmatched argument.  Octave assumes that all unmatched arguments are of the Parameter type and therefore must be followed by a value.

 -- inputParser.PartialMatching: = BOOLEAN
     Set whether argument names for Parameter and Switch options may be given in shortened form as long as the name uniquely identifies an option; Defaults to true.  For example, the argument 'opt' will match a parameter 'opt_color', but will fail if there is also a parameter 'opt_case'.

 -- inputParser.StructExpand: = BOOLEAN
     Set whether a structure passed to the function is expanded into parameter/value pairs (parameter = fieldname); Defaults to true.

     The following example shows how to use this class:

          function check (varargin)
            p = inputParser ();                      # create object
            p.FunctionName = "check";                # set function name
            p.addRequired ("pack", @ischar);         # mandatory argument
            p.addOptional ("path", pwd(), @ischar);  # optional argument

            ## Create anonymous function handle for validators
            valid_vec = @(x) isvector (x) && all (x >= 0) && all (x <= 1);
            p.addOptional ("vec", [0 0], valid_vec);

            ## Create two arguments of type "Parameter"
            vld_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
            p.addParameter ("type", "linear", vld_type);
            vld_tol = @(x) any (strcmp (x, {"low", "medium", "high"}));
            p.addParameter ("tolerance", "low", vld_tol);

            ## Create a switch type of argument
            p.addSwitch ("verbose");

            p.parse (varargin{:});  # Run created parser on inputs

            ## The rest of the function can access inputs by using p.Results.
            ## For example, get the tolerance input with p.Results.tolerance
          endfunction

          check ("mech");           # valid, use defaults for other arguments
          check ();                 # error, one argument is mandatory
          check (1);                # error, since ! ischar
          check ("mech", "~/dev");  # valid, use defaults for other arguments

          check ("mech", "~/dev", [0 1 0 0], "type", "linear");  # valid

          ## following is also valid.  Note how the Switch argument type can
          ## be mixed in with or before the Parameter argument type (but it
          ## must still appear after any Optional arguments).
          check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");

          ## following returns an error since an Optional argument, 'path',
          ## was given after the Parameter argument 'type'.
          check ("mech", "type", "linear", "~/dev");

     Note 1: A function can have any mixture of the four API types but they must appear in a specific order.  Required arguments must be first and can be followed by any Optional arguments.  Only the Parameter and Switch arguments may be mixed together and they must appear following the first two types.

     Note 2: If both Optional and Parameter arguments are mixed in a function API then once a string Optional argument fails to validate it will be considered the end of the Optional arguments.  The remaining arguments will be compared against any Parameter or Switch arguments.

     nargin, validateattributes, validatestring, varargin

Function Files
==============

Except for simple one-shot programs, it is not practical to have to define all the functions you need each time you need them.  Instead, you will normally want to save them in a file so that you can easily edit them, and save them for use at a later time.

Octave does not require you to load function definitions from files before using them.  You simply need to put the function definitions in a place where Octave can find them.

When Octave encounters an identifier that is undefined, it first looks for variables or functions that are already compiled and currently listed in its symbol table.  If it fails to find a definition there, it searches a list of directories (the path) for files ending in .m that have the same base name as the undefined identifier. (The .m suffix was chosen for compatibility with MATLAB.)  Once Octave finds a file with a name that matches, the contents of the file are read.  If it defines a single function, it is compiled and executed.  See Script Files, for more information about how you can define more than one function in a single file.

When Octave defines a function from a function file, it saves the full name of the file it read and the time stamp on the file.  If the time stamp on the file changes, Octave may reload the file.  When Octave is running interactively, time stamp checking normally happens at most once each time Octave prints the prompt.  Searching for new function definitions also occurs if the current working directory changes.

Checking the time stamp allows you to edit the definition of a function while Octave is running, and automatically use the new function definition without having to restart your Octave session.

To avoid degrading performance unnecessarily by checking the time stamps on functions that are not likely to change, Octave assumes that function files in the directory tree OCTAVE-HOME/share/octave/VERSION/m will not change, so it doesn't have to check their time stamps every time the functions defined in those files are used.  This is normally a very good assumption and provides a significant improvement in performance for the function files that are distributed with Octave.

If you know that your own function files will not change while you are running Octave, you can improve performance by calling ignore_function_time_stamp ("all"), so that Octave will ignore the time stamps for all function files.  Passing "system" to this function resets the default behavior.

 -- edit: NAME
 -- edit: FIELD VALUE
 -- VALUE =: edit ("get", FIELD)
 -- VALUE =: edit ("get", "all")
     Edit the named function, or change editor settings.

     If edit is called with the name of a file or function as its argument it will be opened in the text editor defined by EDITOR.

       * If the function NAME is available in a file on your path, then it will be opened in the editor.  If no file is found, then the m-file variant, ending with ".m", will be considered.  If still no file is found, then variants with a leading "@" and then with both a leading "@" and trailing ".m" will be considered.

       * If NAME is the name of a command-line function, then an m-file will be created to contain that function along with its current definition.

       * If NAME.cc is specified, then it will search for NAME.cc in the path and open it in the editor.  If the file is not found, then a new .cc file will be created.  If NAME happens to be an m-file or command-line function, then the text of that function will be inserted into the .cc file as a comment.

       * If NAME.ext is on your path then it will be edited, otherwise the editor will be started with NAME.ext in the current directory as the filename.

          Warning: You may need to clear NAME before the new definition is available.  If you are editing a .cc file, you will need to execute mkoctfile NAME.cc before the definition will be available.

     If edit is called with FIELD and VALUE variables, the value of the control field FIELD will be set to VALUE.

     If an output argument is requested and the first input argument is get then edit will return the value of the control field FIELD.  If the control field does not exist, edit will return a structure containing all fields and values.  Thus, edit ("get", "all") returns a complete control structure.

     The following control fields are used:

     author
          This is the name to put after the "## Author:" field of new functions.  By default it guesses from the gecos field of the password database.

     email
          This is the e-mail address to list after the name in the author field.  By default it guesses <$LOGNAME@$HOSTNAME>, and if $HOSTNAME is not defined it uses uname -n.  You probably want to override this.  Be sure to use the format user@host.

     license

          gpl
               GNU General Public License (default).

          bsd
               BSD-style license without advertising clause.

          pd
               Public domain.

          "text"
               Your own default copyright and license.

          Unless you specify pd, edit will prepend the copyright statement with "Copyright (C) YYYY Author".

     mode
          This value determines whether the editor should be started in async mode (editor is started in the background and Octave continues) or sync mode (Octave waits until the editor exits).  Set it to "sync" to start the editor in sync mode.  The default is "async" (see system).

     editinplace
          Determines whether files should be edited in place, without regard to whether they are modifiable or not.  The default is true. Set it to false to have read-only function files automatically copied to home, if it exists, when editing them.

     home
          This value indicates a directory that system m-files should be copied into before opening them in the editor.  The intent is that this directory is also in the path, so that the edited copy of a system function file shadows the original.  This setting only has an effect when editinplace is set to false.  The default is the empty matrix ([]), which means it is not used.  The default in previous versions of Octave was ~/octave.

     EDITOR, path

 -- mfilename: ()
 -- mfilename: ("fullpath")
 -- mfilename: ("fullpathext")
     Return the name of the currently executing file.

     The base name of the currently executing script or function is returned without any extension.  If called from outside an m-file, such as the command line, return the empty string.

     Given the argument "fullpath", include the directory part of the filename, but not the extension.

     Given the argument "fullpathext", include the directory part of the filename and the extension. inputname, dbstack

 -- VAL =: ignore_function_time_stamp ()
 -- OLD_VAL =: ignore_function_time_stamp (NEW_VAL)
     Query or set the internal variable that controls whether Octave checks the time stamp on files each time it looks up functions defined in function files.

     If the internal variable is set to "system", Octave will not automatically recompile function files in subdirectories of OCTAVE-HOME/share/VERSION/m if they have changed since they were last compiled, but will recompile other function files in the search path if they change.

     If set to "all", Octave will not recompile any function files unless their definitions are removed with clear.

     If set to "none", Octave will always check time stamps on files to determine whether functions defined in function files need to recompiled.

Manipulating the Load Path
--------------------------

When a function is called, Octave searches a list of directories for a file that contains the function declaration.  This list of directories is known as the load path.  By default the load path contains a list of directories distributed with Octave plus the current working directory.  To see your current load path call the path function without any input or output arguments.

It is possible to add or remove directories to or from the load path using addpath and rmpath.  As an example, the following code adds ~/Octave to the load path.

     addpath ("~/Octave")

After this the directory ~/Octave will be searched for functions.

 -- addpath: (DIR1, ...)
 -- addpath: (DIR1, ..., OPTION)
 -- OLDPATH =: addpath (...)
     Add named directories to the function search path.

     If OPTION is "-begin" or 0 (the default), prepend the directory name(s) to the current path.  If OPTION is "-end" or 1, append the directory name(s) to the current path.  Directories added to the path must exist.

     In addition to accepting individual directory arguments, lists of directory names separated by pathsep are also accepted.  For example:

          addpath ("dir1:/dir2:~/dir3")

     The newly added paths appear in the load path in the same order that they appear in the arguments of addpath.  When extending the load path to the front, the last path in the list of arguments is added first.  When extending the load path to the end, the first path in the list of arguments is added first.

     For each directory that is added, and that was not already in the path, addpath checks for the existence of a file named PKG_ADD (note lack of .m extension) and runs it if it exists.

     path, rmpath, genpath, pathdef, savepath, pathsep

 -- PATHSTR =: genpath (DIR)
 -- PATHSTR =: genpath (DIR, SKIPDIR1, ...)
     Return a path constructed from DIR and all its subdirectories.

     The path does not include package directories (beginning with +), old-style class directories (beginning with @), private directories, or any subdirectories of these types.

     If additional string parameters are given, the resulting path will exclude directories with those names. path, addpath

 -- rmpath: (DIR1, ...)
 -- OLDPATH =: rmpath (DIR1, ...)
     Remove DIR1, ... from the current function search path.

     In addition to accepting individual directory arguments, lists of directory names separated by pathsep are also accepted.  For example:

          rmpath ("dir1:/dir2:~/dir3")

     For each directory that is removed, rmpath checks for the existence of a file named PKG_DEL (note lack of .m extension) and runs it if it exists.

     path, addpath, genpath, pathdef, savepath, pathsep

 -- savepath:
 -- savepath: FILE
 -- STATUS =: savepath (...)
     Save the unique portion of the current function search path to FILE.

     The list of folders that are saved in FILE does not include the folders that are added for Octave's own functions, those that belong to Octave packages (see pkg load), and those added via command line switches.

     If FILE is omitted, Octave looks in the current directory for a project-specific .octaverc file in which to save the path information.  If no such file is present then the user's configuration file ~/.octaverc is used.

     If successful, savepath returns 0.

     The savepath function makes it simple to customize a user's configuration file to restore the working paths necessary for a particular instance of Octave.  Assuming no filename is specified, Octave will automatically restore the saved directory paths from the appropriate .octaverc file when starting up.  If a filename has been specified then the paths may be restored manually by calling source FILE. path, addpath, rmpath, genpath, pathdef

 -- path: ()
 -- STR =: path ()
 -- STR =: path (PATH1, ...)
     Modify or display Octave's load path.

     If NARGIN and NARGOUT are zero, display the elements of Octave's load path in an easy to read format.

     If NARGIN is zero and nargout is greater than zero, return the current load path.

     If NARGIN is greater than zero, concatenate the arguments, separating them with pathsep.  Set the internal search path to the result and return it.

     No checks are made for duplicate elements. addpath, rmpath, genpath, pathdef, savepath, pathsep

 -- VAL =: pathdef ()
     Return the default path for Octave.

     The path information is extracted from one of four sources. The possible sources, in order of preference, are:

      1. .octaverc

      2. ~/.octaverc

      3. <OCTAVE_HOME>/.../<version>/m/startup/octaverc

      4. Octave's path prior to changes by any octaverc file.

     path, addpath, rmpath, genpath, savepath

 -- VAL =: pathsep ()
     Query the character used to separate directories in a path. filesep

 -- rehash: ()
     Reinitialize Octave's load path directory cache.

 -- FNAME =: file_in_loadpath (FILE)
 -- FNAME =: file_in_loadpath (FILE, "all")
     Return the absolute name of FILE if it can be found in the list of directories specified by path.

     If no file is found, return an empty character string.

     When FILE is already an absolute name, the name is checked against the file system instead of Octave's loadpath.  In this case, if FILE exists it will be returned in FNAME, otherwise an empty string is returned.

     If the first argument is a cell array of strings, search each directory of the loadpath for element of the cell array and return the first that matches.

     If the second optional argument "all" is supplied, return a cell array containing the list of all files that have the same name in the path. If no files are found, return an empty cell array. file_in_path, dir_in_loadpath, path

 -- PATHSTR =: restoredefaultpath ()
     Restore Octave's path to its initial state at startup.

     The re-initialized path is returned as an output. path, addpath, rmpath, genpath, pathdef, savepath, pathsep

 -- PATHSTR =: command_line_path ()
     Return the path argument given to Octave at the command line when the interpreter was started (--path ARG).

     path, addpath, rmpath, genpath, pathdef, savepath, pathsep

 -- DIRNAME =: dir_in_loadpath (DIR)
 -- DIRNAME =: dir_in_loadpath (DIR, "all")
     Return the absolute name of the loadpath element matching DIR if it can be found in the list of directories specified by path.

     If no match is found, return an empty character string.

     The match is performed at the end of each path element.  For example, if DIR is "foo/bar", it matches the path element "/some/dir/foo/bar", but not "/some/dir/foo/bar/baz" "/some/dir/allfoo/bar".  When DIR is an absolute name, rather than just a path fragment, it is matched against the file system instead of Octave's loadpath.  In this case, if DIR exists it will be returned in DIRNAME, otherwise an empty string is returned.

     If the optional second argument is supplied, return a cell array containing all name matches rather than just the first. file_in_path, file_in_loadpath, path

 -- CURRENT_ENCODING =: mfile_encoding ()
 -- mfile_encoding: (NEW_ENCODING)
 -- OLD_ENCODING =: mfile_encoding (NEW_ENCODING)
     Query or set the encoding that is used for reading m-files.

     The input and output are strings naming an encoding, e.g., "utf-8".

     This encoding is used by Octave's parser when reading m-files unless a different encoding was set for a specific directory containing m-files using the function dir_encoding or in a file .oct-config in that directory.

     The special value "system" selects the encoding that matches the system locale.

     If the m-file encoding is changed after the m-files have already been parsed, the files have to be parsed again for that change to take effect.  That can be triggered with the command clear all.

     Additionally, this encoding is used to load and save files with the built-in editor in Octave's GUI.

     dir_encoding

 -- CURRENT_ENCODING =: dir_encoding (DIR)
 -- dir_encoding: (DIR, NEW_ENCODING)
 -- dir_encoding: (DIR, "delete")
 -- OLD_ENCODING =: dir_encoding (DIR, NEW_ENCODING)
     Query or set the ENCODING that is used for reading m-files in DIR.

     The per-directory encoding overrides the (globally set) m-file encoding, see mfile_encoding.

     The string DIR must match how the directory would appear in the load path.

     The NEW_ENCODING input must be a valid encoding identifier or "delete".  In the latter case, any per-directory encoding is removed and the (globally set) m-file encoding will be used for the given DIR.

     The currently or previously used encoding is returned only if an output argument is requested.

     The directory encoding is automatically read from the file .oct-config when a new path is added to the load path (for example with addpath). To set the encoding for all files in the same folder, that file must contain a line starting with "encoding=" followed by the encoding identifier.

     For example to set the file encoding for all files in the same folder to ISO 8859-1 (Latin-1), create a file .oct-config with the following content:

          encoding=iso8859-1

     If the file encoding is changed after the files have already been parsed, the files have to be parsed again for that change to take effect.  That can be done with the command clear all.

     addpath, path, mfile_encoding

Subfunctions
------------

A function file may contain secondary functions called subfunctions.  These secondary functions are only visible to the other functions in the same function file.  For example, a file f.m containing

     function f ()
       printf ("in f, calling g\n");
       g ()
     endfunction
     function g ()
       printf ("in g, calling h\n");
       h ()
     endfunction
     function h ()
       printf ("in h\n")
     endfunction

defines a main function f and two subfunctions.  The subfunctions g and h may only be called from the main function f or from the other subfunctions, but not from outside the file f.m.

 -- SUBFCN_LIST =: localfunctions ()
     Return a list of all local functions, i.e., subfunctions, within the current file.

     The return value is a column cell array of function handles to all local functions accessible from the function from which localfunctions is called.  Nested functions are not included in the list.

     If the call is from the command line, an anonymous function, or a script, the return value is an empty cell array.

     functions

Private Functions
-----------------

In many cases one function needs to access one or more helper functions.  If the helper function is limited to the scope of a single function, then subfunctions as discussed above might be used.  However, if a single helper function is used by more than one function, then this is no longer possible.  In this case the helper functions might be placed in a subdirectory, called "private", of the directory in which the functions needing access to this helper function are found.

As a simple example, consider a function func1, that calls a helper function func2 to do much of the work.  For example:

     function y = func1 (x)
       y = func2 (x);
     endfunction

Then if the path to func1 is <directory>/func1.m, and if func2 is found in the directory <directory>/private/func2.m, then func2 is only available for use of the functions, like func1, that are found in <directory>.

Nested Functions
----------------

Nested functions are similar to subfunctions in that only the main function is visible outside the file.  However, they also allow for child functions to access the local variables in their parent function.  This shared access mimics using a global variable to share information --- but a global variable which is not visible to the rest of Octave.  As a programming strategy, sharing data this way can create code which is difficult to maintain.  It is recommended to use subfunctions in place of nested functions when possible.

As a simple example, consider a parent function foo, that calls a nested child function bar, with a shared variable X.

     function y = foo ()
       x = 10;
       bar ();
       y = x;

       function bar ()
         x = 20;
       endfunction
     endfunction

     foo ()
      => 20

Notice that there is no special syntax for sharing X.  This can lead to problems with accidental variable sharing between a parent function and its child.  While normally variables are inherited, child function parameters and return values are local to the child function.

Now consider the function foobar that uses variables X and Y.  foobar calls a nested function foo which takes X as a parameter and returns Y.  foo then calls bat which does some computation.

     function z = foobar ()
       x = 0;
       y = 0;
       z = foo (5);
       z += x + y;

       function y = foo (x)
         y = x + bat ();

         function z = bat ()
           z = x;
         endfunction
       endfunction
     endfunction

     foobar ()
         => 10

It is important to note that the X and Y in foobar remain zero, as in foo they are a return value and parameter respectively.  The X in bat refers to the X in foo.

Variable inheritance leads to a problem for eval and scripts.  If a new variable is created in a parent function, it is not clear what should happen in nested child functions.  For example, consider a parent function foo with a nested child function bar:

     function y = foo (to_eval)
       bar ();
       eval (to_eval);

       function bar ()
         eval ("x = 100;");
         eval ("y = x;");
       endfunction
     endfunction

     foo ("x = 5;")
         => error: can not add variable "x" to a static workspace

     foo ("y = 10;")
         => 10

     foo ("")
         => 100

The parent function foo is unable to create a new variable X, but the child function bar was successful.  Furthermore, even in an eval statement Y in bar is the same Y as in its parent function foo.  The use of eval in conjunction with nested functions is best avoided.

As with subfunctions, only the first nested function in a file may be called from the outside.  Inside a function the rules are more complicated.  In general a nested function may call:

 0. Globally visible functions

 1. Any function that the nested function's parent can call

 2. Sibling functions (functions that have the same parents)

 3. Direct children

As a complex example consider a parent function ex_top with two child functions, ex_a and ex_b.  In addition, ex_a has two more child functions, ex_aa and ex_ab.  For example:

     function ex_top ()
       ## Can call: ex_top, ex_a, and ex_b
       ## Can NOT call: ex_aa and ex_ab

       function ex_a ()
         ## Can call everything

         function ex_aa ()
           ## Can call everything
         endfunction

         function ex_ab ()
           ## Can call everything
         endfunction
       endfunction

       function ex_b ()
         ## Can call: ex_top, ex_a, and ex_b
         ## Can NOT call: ex_aa and ex_ab
       endfunction
     endfunction

Overloading and Autoloading
---------------------------

Functions can be overloaded to work with different input arguments.  For example, the operator '+' has been overloaded in Octave to work with single, double, uint8, int32, and many other arguments.  The preferred way to overload functions is through classes and object oriented programming (see Function Overloading).  Occasionally, however, one needs to undo user overloading and call the default function associated with a specific type.  The builtin function exists for this purpose.

 -- [...] =: builtin (F, ...)
     Call the base function F even if F is overloaded to another function for the given type signature.

     This is normally useful when doing object-oriented programming and there is a requirement to call one of Octave's base functions rather than the overloaded one of a new class.

     A trivial example which redefines the sin function to be the cos function shows how builtin works.

          sin (0)
            => 0
          function y = sin (x), y = cos (x); endfunction
          sin (0)
            => 1
          builtin ("sin", 0)
            => 0

A single dynamically linked file might define several functions.  However, as Octave searches for functions based on the functions filename, Octave needs a manner in which to find each of the functions in the dynamically linked file.  On operating systems that support symbolic links, it is possible to create a symbolic link to the original file for each of the functions which it contains.

However, there is at least one well known operating system that doesn't support symbolic links.  Making copies of the original file for each of the functions is undesirable as it increases the amount of disk space used by Octave.  Instead Octave supplies the autoload function, that permits the user to define in which file a certain function will be found.

 -- AUTOLOAD_MAP =: autoload ()
 -- autoload: (FUNCTION, FILE)
 -- autoload: (..., "remove")
     Define FUNCTION to autoload from FILE.

     The second argument, FILE, should be an absolute filename or a file name in the same directory as the function or script from which the autoload command was run.  FILE should not depend on the Octave load path.

     Normally, calls to autoload appear in PKG_ADD script files that are evaluated when a directory is added to Octave's load path.  To avoid having to hardcode directory names in FILE, if FILE is in the same directory as the PKG_ADD script then

          autoload ("foo", "bar.oct");

     will load the function foo from the file bar.oct.  The above usage when bar.oct is not in the same directory, or usages such as

          autoload ("foo", file_in_loadpath ("bar.oct"))

     are strongly discouraged, as their behavior may be unpredictable.

     With no arguments, return a structure containing the current autoload map.

     If a third argument "remove" is given, the function is cleared and not loaded anymore during the current Octave session.

     PKG_ADD

Function Locking
----------------

It is sometime desirable to lock a function into memory with the mlock function.  This is typically used for dynamically linked functions in oct-files or mex-files that contain some initialization, and it is desirable that calling clear does not remove this initialization.

As an example,

     function my_function ()
       mlock ();
       ...
     endfunction

prevents my_function from being removed from memory after it is called, even if clear is called.  It is possible to determine if a function is locked into memory with the mislocked, and to unlock a function with munlock, which the following code illustrates.

     my_function ();
     mislocked ("my_function")
     => ans = 1
     munlock ("my_function");
     mislocked ("my_function")
     => ans = 0

A common use of mlock is to prevent persistent variables from being removed from memory, as the following example shows:

     function count_calls ()
       mlock ();
       persistent calls = 0;
       printf ("count_calls() has been called %d times\n", ++calls);
     endfunction

     count_calls ();
     -| count_calls() has been called 1 times

     clear count_calls
     count_calls ();
     -| count_calls() has been called 2 times

mlock might also be used to prevent changes to an m-file, such as in an external editor, from having any effect in the current Octave session; A similar effect can be had with the ignore_function_time_stamp function.

 -- mlock: ()
     Lock the current function into memory so that it can't be removed with clear. munlock, mislocked, persistent, clear

 -- munlock: ()
 -- munlock: (FCN)
     Unlock the named function FCN so that it may be removed from memory with clear.

     If no function is named then unlock the current function. mlock, mislocked, persistent, clear

 -- TF =: mislocked ()
 -- TF =: mislocked (FCN)
     Return true if the named function FCN is locked in memory.

     If no function is named then return true if the current function is locked. mlock, munlock, persistent, clear

Function Precedence
-------------------

Given the numerous different ways that Octave can define a function, it is possible and even likely that multiple versions of a function, might be defined within a particular scope.  The precedence of which function will be used within a particular scope is given by

 1. Subfunction A subfunction with the required function name in the given scope.

 2. Private function A function defined within a private directory of the directory which contains the current function.

 3. Class constructor A function that constructs a user class as defined in chapter Object Oriented Programming.

 4. Class method An overloaded function of a class as in chapter Object Oriented Programming.

 5. Command-line Function A function that has been defined on the command-line.

 6. Autoload function A function that is marked as autoloaded with see autoload.

 7. A Function on the Path A function that can be found on the users load-path.  There can also be Oct-file, mex-file or m-file versions of this function and the precedence between these versions are in that order.

 8. Built-in function A function that is a part of core Octave such as numel, size, etc.

Script Files
============

A script file is a file containing (almost) any sequence of Octave commands.  It is read and evaluated just as if you had typed each command at the Octave prompt, and provides a convenient way to perform a sequence of commands that do not logically belong inside a function.

Unlike a function file, a script file must not begin with the keyword function.  If it does, Octave will assume that it is a function file, and that it defines a single function that should be evaluated as soon as it is defined.

A script file also differs from a function file in that the variables named in a script file are not local variables, but are in the same scope as the other variables that are visible on the command line.

Even though a script file may not begin with the function keyword, it is possible to define more than one function in a single script file and load (but not execute) all of them at once.  To do this, the first token in the file (ignoring comments and other white space) must be something other than function.  If you have no other statements to evaluate, you can use a statement that has no effect, like this:

     # Prevent Octave from thinking that this
     # is a function file:

     1;

     # Define function one:

     function one ()
       ...

To have Octave read and compile these functions into an internal form, you need to make sure that the file is in Octave's load path (accessible through the path function), then simply type the base name of the file that contains the commands.  (Octave uses the same rules to search for script files as it does to search for function files.)

If the first token in a file (ignoring comments) is function, Octave will compile the function and try to execute it, printing a message warning about any non-whitespace characters that appear after the function definition.

Note that Octave does not try to look up the definition of any identifier until it needs to evaluate it.  This means that Octave will compile the following statements if they appear in a script file, or are typed at the command line,

     # not a function file:
     1;
     function foo ()
       do_something ();
     endfunction
     function do_something ()
       do_something_else ();
     endfunction

even though the function do_something is not defined before it is referenced in the function foo.  This is not an error because Octave does not need to resolve all symbols that are referenced by a function until the function is actually evaluated.

Since Octave doesn't look for definitions until they are needed, the following code will always print bar = 3 whether it is typed directly on the command line, read from a script file, or is part of a function body, even if there is a function or script file called bar.m in Octave's path.

     eval ("bar = 3");
     bar

Code like this appearing within a function body could fool Octave if definitions were resolved as the function was being compiled.  It would be virtually impossible to make Octave clever enough to evaluate this code in a consistent fashion.  The parser would have to be able to perform the call to eval at compile time, and that would be impossible unless all the references in the string to be evaluated could also be resolved, and requiring that would be too restrictive (the string might come from user input, or depend on things that are not known until the function is evaluated).

Although Octave normally executes commands from script files that have the name FILE.m, you can use the function source to execute commands from any file.

 -- source: (FILE)
 -- source: (FILE, CONTEXT)
     Parse and execute the contents of FILE.

     Without specifying CONTEXT, this is equivalent to executing commands from a script file, but without requiring the file to be named FILE.m or to be on the execution path.

     Instead of the current context, the script may be executed in either the context of the function that called the present function ("caller"), or the top-level context ("base"). run

Publish Octave Script Files
---------------------------

The function publish provides a dynamic possibility to document your script file.  Unlike static documentation, publish runs the script file, saves any figures and output while running the script, and presents them alongside static documentation in a desired output format.  The static documentation can make use of Publishing Markup to enhance and customize the output.

 -- publish: (FILE)
 -- publish: (FILE, OUTPUT_FORMAT)
 -- publish: (FILE, OPTION1, VALUE1, ...)
 -- publish: (FILE, OPTIONS)
 -- OUTPUT_FILE =: publish (FILE, ...)

     Generate a report from the Octave script file FILE in one of several output formats.

     The generated reports interpret Publishing Markup in section comments, which is explained in detail in the GNU Octave manual.  Section comments are comment blocks that start with a line with double comment character.

     Assume the following example, using some Publishing Markup, to be the contents of the script file pub_example.m:

          ## Headline title
          #
          # Some *bold*, _italic_, or |monospaced| Text with
          # a <https://www.octave.org link to *GNU Octave*>.
          ##

          # "Real" Octave commands to be evaluated
          sombrero ()

          %% MATLAB comment style ('%') is supported as well
          %
          % * Bulleted list item 1
          % * Bulleted list item 2
          %
          % # Numbered list item 1
          % # Numbered list item 2

     To publish this script file, type publish ("pub_example.m").

     When called with one input argument, a HTML report is generated in a subdirectory html relative to the current working directory.  Any Octave commands in pub_example.m are evaluated in a separate context and any figures created while executing the script file are included in the report.

     Using publish (FILE, OUTPUT_FORMAT) is equivalent to the function call using a structure

          OPTIONS.format = OUTPUT_FORMAT;
          publish (FILE, OPTIONS)

     which is described below.  The same holds for using option/value pairs

          OPTIONS.OPTION1 = VALUE1;
          publish (FILE, OPTIONS)

     The structure OPTIONS can have the following field names.  If a field name is not specified, the default value is used:

       * format --- Output format of the published script file, one of

          html (default), doc, latex, ppt, pdf, or xml.

          The output formats doc, ppt, and xml are not currently supported.  To generate a doc report, open a generated html report with your office suite.

          In Octave custom formats are supported by implementing all callback subfunctions in a function file named __publish_<custom format>_output__.m.  To obtain a template for the HTML format type:

               edit (fullfile (fileparts (which ("publish")), ...
                     "private", "__publish_html_output__.m"))

       * outputDir --- Full path of the directory where the generated report will be located.  If no directory is given, the report is generated in a subdirectory html relative to the current working directory.

       * stylesheet --- Not supported, only for MATLAB compatibility.

       * createThumbnail --- Not supported, only for MATLAB compatibility.

       * figureSnapMethod --- Not supported, only for MATLAB compatibility.

       * imageFormat --- Desired format for any images produced while evaluating the code.  The allowed image formats depend on the output format:

            * html, xml --- png (default), any image format supported by Octave

            * latex --- epsc2 (default), any image format supported by Octave

            * pdf --- jpg (default) or bmp, note MATLAB uses  bmp as default

            * doc or ppt --- png (default), jpg, bmp, or tiff

       * maxWidth and maxHeight --- Maximum width (height) of the produced images in pixels.  An empty value means no restriction.  Both values must be set in order for the option to work properly.

          [] (default), integer value ≥ 0

       * useNewFigure --- Use a new figure window for figures created by the evaluated code.  This avoids side effects with already opened figure windows.

          true (default) or false

       * evalCode --- Evaluate code of the Octave source file

          true (default) or false

       * catchError --- Catch errors while evaluating code and continue

          true (default) or false

       * codeToEvaluate --- Octave commands that should be evaluated prior to publishing the script file.  These Octave commands do not appear in the generated report.

       * maxOutputLines --- Maximum number of output lines from code evaluation which are included in output.

          Inf (default) or integer value > 0

       * showCode --- Show the evaluated Octave commands in the generated report

          true (default) or false

     The option output OUTPUT_FILE is a string with path and file name of the generated report.

     grabcode

The counterpart to publish is grabcode:

 -- grabcode: FILENAME
 -- grabcode: URL
 -- CODE_STR =: grabcode (...)

     Grab the code from a report created by the publish function.

     The grabbed code inside the published report must be enclosed by the strings ##### SOURCE BEGIN ##### and ##### SOURCE END #####. The publish function creates this format automatically.

     If no return value is requested the code is saved to a temporary file and opened in the default editor.  NOTE: The temporary file must be saved to a new filename or the code will be lost.

     If an output is requested the grabbed code will be returned as string CODE_STR.

     Example:

          publish ("my_script.m");
          grabcode ("html/my_script.html");

     The example above publishes my_script.m to the default location html/my_script.html.  Next, the published Octave script is grabbed to edit its content in a new temporary file.

     publish

Publishing Markup
-----------------

Using Publishing Markup in Script Files
.......................................

To use Publishing Markup, start by typing ## or %% at the beginning of a new line.  For MATLAB compatibility %%% is treated the same way as %%.

The lines following ## or %% start with one of either # or % followed by at least one space.  These lines are interpreted as section.  A section ends at the first line not starting with # or %, or when the end of the document is reached.

A section starting in the first line of the document, followed by another start of a section that might be empty, is interpreted as a document title and introduction text.

See the example below for clarity:

     %% Headline title
     %
     % Some *bold*, _italic_, or |monospaced| Text with
     % a <https://www.octave.org link to GNU Octave>.
     %%

     # "Real" Octave commands to be evaluated
     sombrero ()

     ## Octave comment style supported as well
     #
     # * Bulleted list item 1
     # * Bulleted list item 2
     #
     # # Numbered list item 1
     # # Numbered list item 2

Text Formatting
...............

Basic text formatting is supported inside sections, see the example given below:

     ##
     # *bold*, _italic_, or |monospaced| Text

Additionally two trademark symbols are supported, just embrace the letters TM or R.

     ##
     # (TM) or (R)

Sections
........

A section is started by typing ## or %% at the beginning of a new line.  A section title can be provided by writing it, separated by a space, in the first line after ## or %%.  Without a section title, the section is interpreted as a continuation of the previous section. For MATLAB compatibility %%% is treated the same way as %%.

     some_code ();

     ## Section 1
     #
     ## Section 2

     some_code ();

     ##
     # Still in section 2

     some_code ();

     %%% Section 3
     %
     %

Preformatted Code
.................

To write preformatted code inside a section, indent the code by three spaces after # at the beginning of each line and leave the lines above and below the code blank, except for # at the beginning of those lines.

     ##
     # This is a syntax highlighted for-loop:
     #
     #   for i = 1:5
     #     disp (i);
     #   endfor
     #
     # And more usual text.

Preformatted Text
.................

To write preformatted text inside a section, indent the code by two spaces after # at the beginning of each line and leave the lines above and below the preformatted text blank, except for # at the beginning of those lines.

     ##
     # This following text is preformatted:
     #
     #  "To be, or not to be: that is the question:
     #  Whether 'tis nobler in the mind to suffer
     #  The slings and arrows of outrageous fortune,
     #  Or to take arms against a sea of troubles,
     #  And by opposing end them?  To die: to sleep;"
     #
     #  --"Hamlet" by W. Shakespeare

Bulleted Lists
..............

To create a bulleted list, type

     ##
     #
     # * Bulleted list item 1
     # * Bulleted list item 2
     #

to get output like

  * Bulleted list item 1

  * Bulleted list item 2

Notice the blank lines, except for the # or % before and after the bulleted list!

Numbered Lists
..............

To create a numbered list, type

     ##
     #
     # # Numbered list item 1
     # # Numbered list item 2
     #

to get output like

 1. Numbered list item 1

 2. Numbered list item 2

Notice the blank lines, except for the # or % before and after the numbered list!

Including File Content
......................

To include the content of an external file, e.g., a file called my_function.m at the same location as the published Octave script, use the following syntax to include it with Octave syntax highlighting.

Alternatively, you can write the full or relative path to the file.

     ##
     #
     # <include>my_function.m</include>
     #
     # <include>/full/path/to/my_function.m</include>
     #
     # <include>../relative/path/to/my_function.m</include>
     #

Including Graphics
..................

To include external graphics, e.g., a graphic called my_graphic.png at the same location as the published Octave script, use the following syntax.

Alternatively, you can write the full path to the graphic.

     ##
     #
     # <<my_graphic.png>>
     #
     # <</full/path/to/my_graphic.png>>
     #
     # <<../relative/path/to/my_graphic.png>>
     #

Including URLs
..............

Basically, a URL is written between an opening < and a closing > angle.

     ##
     # <https://www.octave.org>

Text that is within these angles and separated by at least one space from the URL is a displayed text for the link.

     ##
     # <https://www.octave.org GNU Octave>

A link starting with <octave: followed by the name of a GNU Octave function, optionally with a displayed text, results in a link to the online GNU Octave documentations function index.

     ##
     # <octave:DISP The display function>

Mathematical Equations
......................

One can insert LaTeX inline math, surrounded by single $ signs, or displayed math, surrounded by double $$ signs, directly inside sections.

     ##
     # Some shorter inline equation $e^{ix} = \cos x + i\sin x$.
     #
     # Or more complicated formulas as displayed math:
     # $$e^x = \lim_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}.$$

HTML Markup
...........

If the published output is a HTML report, you can insert HTML markup, that is only visible in this kind of output.

     ##
     # <html>
     # <table style="border:1px solid black;">
     # <tr><td>1</td><td>2</td></tr>
     # <tr><td>3</td><td>3</td></tr>
     # </html>

LaTeX Markup
............

If the published output is a LaTeX or PDF report, you can insert LaTeX markup, that is only visible in this kind of output.

     ##
     # <latex>
     # Some output only visible in LaTeX or PDF reports.
     # \begin{equation}
     # e^x = \lim\limits_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}
     # \end{equation}
     # </latex>

Jupyter Notebooks
-----------------

Jupyter notebooks are one popular technique for displaying code, text, and graphical output together in a comprehensive manner.  Octave can publish results to a Jupyter notebook with the function jupyter_notebook.

 -- NOTEBOOK =: jupyter_notebook (NOTEBOOK_FILENAME)
 -- NOTEBOOK =: jupyter_notebook (NOTEBOOK_FILENAME, OPTIONS)

     Run and fill the Jupyter Notebook in file NOTEBOOK_FILENAME from within GNU Octave.

     Both text and graphical Octave outputs are supported.

     This class has a public property notebook which is a structure representing the JSON-decoded Jupyter Notebook.  This property is intentionally public to enable advanced notebook manipulations.

     Note: Jupyter Notebook versions (nbformat) lower than 4.0 are not supported.

     The optional second argument OPTIONS is a struct with fields:

       * tmpdir to set the temporary working directory.

     %plot magic is supported with the following settings:

       * "%plot -f <format>" or "%plot --format <format>": specifies the image storage format.  Supported formats are:

            - PNG (default)

            - SVG (Note: If SVG images do not appear in the notebook, it is most likely related to Jupyter Notebook security mechanisms and explicitly "trusting" them will be necessary).

            - JPG

       * "%plot -r <number>" or "%plot --resolution <number>": specifies the image resolution.

       * "%plot -w <number>" or "%plot --width <number>": specifies the image width.

       * "%plot -h <number>" or "%plot --height <number>": specifies the image height.

     Examples:

          ## Run all cells and generate the filled notebook

          ## Instantiate an object from a notebook file
          notebook = jupyter_notebook ("myNotebook.ipynb");
          ## Run the code and embed the results in the notebook property
          notebook.run_all ();
          ## Generate a new notebook by overwriting the original notebook
          notebook.generate_notebook ("myNotebook.ipynb");

          ## Run just the second cell and generate the filled notebook

          ## Instantiate an object from a notebook file
          notebook = jupyter_notebook ("myNotebook.ipynb");
          ## Run the code and embed the results in the notebook property
          notebook.run (2)
          ## Generate a new notebook in a new file
          notebook.generate_notebook ("myNewNotebook.ipynb");

          ## Generate an Octave script from a notebook

          ## Instantiate an object from a notebook file
          notebook = jupyter_notebook ("myNotebook.ipynb");
          ## Generate the Octave script
          notebook.generate_octave_script ("jup_script.m");

     jsondecode, jsonencode

Function Handles and Anonymous Functions
========================================

It can be very convenient store a function in a variable so that it can be passed to a different function.  For example, a function that performs numerical minimization needs access to the function that should be minimized.

Function Handles
----------------

A function handle is a pointer to another function and is defined with the syntax

     @FUNCTION-NAME

For example,

     f = @sin;

creates a function handle called f that refers to the function sin.

Function handles are used to call other functions indirectly, or to pass a function as an argument to another function like quad or fsolve.  For example:

     f = @sin;
     quad (f, 0, pi)
         => 2

You may use feval to call a function using function handle, or simply write the name of the function handle followed by an argument list.  If there are no arguments, you must use an empty argument list ().  For example:

     f = @sin;
     feval (f, pi/4)
         => 0.70711
     f (pi/4)
         => 0.70711

 -- TF =: is_function_handle (X)
     Return true if X is a function handle. isa, typeinfo, class, functions

 -- S =: functions (FCN_HANDLE)
     Return a structure containing information about the function handle FCN_HANDLE.

     The structure S always contains these three fields:

     function
          The function name.  For an anonymous function (no name) this will be the actual function definition.

     type
          Type of the function.

          anonymous
               The function is anonymous.

          private
               The function is private.

          overloaded
               The function overloads an existing function.

          simple
               The function is a built-in or m-file function.

          subfunction
               The function is a subfunction within an m-file.

     nested
          The function is nested.

     file
          The m-file that will be called to perform the function.  This field is empty for anonymous and built-in functions.

     In addition, some function types may return more information in additional fields.

     Warning: functions is provided for debugging purposes only. Its behavior may change in the future and programs should not depend on any particular output format.

     func2str, str2func

 -- STR =: func2str (FCN_HANDLE)
     Return a string containing the name of the function referenced by the function handle FCN_HANDLE. str2func, functions

 -- HFCN =: str2func (STR)
     Return a function handle constructed from the string STR.

     The input may be the name of a function such as "sin" or a string defining a function such as "@(x) sin (x + pi)".

     Programming Note: In most cases it will be better to use anonymous function syntax and let the Octave parser create the function handle rather than use str2func.  For example:

          hfcn = @sin ;
          hfcn = @(x) sin (x + pi) ;

     func2str, functions

 -- VARS =: symvar (STR)
     Identify the symbolic variable names in the string STR.

     Common constant names such as i, j, pi, Inf and Octave functions such as sin or plot are ignored.

     Any names identified are returned in a cell array of strings.  The array is empty if no variables were found.

     Example:

          symvar ("x^2 + y^2 == 4")
          => {
               [1,1] = x
               [2,1] = y
             }

Anonymous Functions
-------------------

Anonymous functions are defined using the syntax

     @(ARGUMENT-LIST) EXPRESSION

Any variables that are not found in the argument list are inherited from the enclosing scope.  Anonymous functions are useful for creating simple unnamed functions from expressions or for wrapping calls to other functions to adapt them for use by functions like quad.  For example,

     f = @(x) x.^2;
     quad (f, 0, 10)
         => 333.33

creates a simple unnamed function from the expression x.^2 and passes it to quad,

     quad (@(x) sin (x), 0, pi)
         => 2

wraps another function, and

     a = 1;
     b = 2;
     quad (@(x) betainc (x, a, b), 0, 0.4)
         => 0.13867

adapts a function with several parameters to the form required by quad.  In this example, the values of A and B that are passed to betainc are inherited from the current environment.

Note that for performance reasons it is better to use handles to existing Octave functions, rather than to define anonymous functions which wrap an existing function.  The integration of sin (x) is 5X faster if the code is written as

     quad (@sin, 0, pi)

rather than using the anonymous function @(x) sin (x).  There are many operators which have functional equivalents that may be better choices than an anonymous function.  Instead of writing

     f = @(x, y) x + y

this should be coded as

     f = @plus

See Operator Overloading, for a list of operators which also have a functional form.

Command Syntax and Function Syntax
==================================

In addition to the function syntax described above (i.e., calling a function like fun (arg1, arg2, ...)), a function can be called using command syntax (for example, calling a function like fun arg1 arg2 ...).  In that case, all arguments are passed to the function as strings.  For example,

     my_command hello world

is equivalent to

     my_command ("hello", "world")

The general form of a command call is

     cmdname arg1 arg2 ...

which translates directly to

     cmdname ("arg1", "arg2", ...)

If an argument including spaces should be passed to a function in command syntax, (double-)quotes can be used.  For example,

     my_command "first argument" "second argument"

is equivalent to

     my_command ("first argument", "second argument")

Any function can be used as a command if it accepts string input arguments. For example:

     upper lower_case_arg
        => ans = LOWER_CASE_ARG

Since the arguments are passed as strings to the corresponding function, it is not possible to pass input arguments that are stored in variables.  In that case, a command must be called using the function syntax.  For example:

     strvar = "hello world";
     upper strvar
        => ans = STRVAR
     upper (strvar)
        => ans = HELLO WORLD

Additionally, the return values of functions cannot be assigned to variables using the command syntax.  Only the first return argument is assigned to the built-in variable ans.  If the output argument of a command should be assigned to a variable, or multiple output arguments of a function should be returned, the function syntax must be used.

It should be noted that mixing command syntax and binary operators can create apparent ambiguities with mathematical and logical expressions that use function syntax.  For example, all three of the statements

     arg1 - arg2
     arg1 -arg2
     arg1-arg2

could be intended by a user to be subtraction operations between arg1 and arg2.  The first two, however, could also have been meant as a command syntax call to function arg1, in the first case with options - and arg2, and in the second case with option -arg2.

Octave uses whitespace to interpret such expressions according to the following rules:

  * Statements consisting of plain symbols without any operators that are separated only by whitespace are always treated as command syntax:

          arg1 arg2 arg3 ... argn

  * Statements without any whitespace are always treated as function syntax:

          arg1+arg2
          arg1&&arg2||arg3
          arg1+=arg2*arg3

  * If the first symbol is a constant (or special-valued named constant pi, i, I, j, J, e, NaN, or Inf) followed by a binary operator, the statement is treated as function syntax regardless of any whitespace or what follows the second symbol:

          7 -arg2
          pi+ arg2
          j * arg2 -arg3

  * If the first symbol is a function or variable and there is no whitespace separating the operator and the second symbol, the statement is treated as command syntax:

          arg1 -arg2
          arg1 &&arg2 ||arg3
          arg1 +=arg2*arg3

  * Any other whitespace combination will result in the statement being treated as function syntax.

Note 1: If a special-valued named constant has been redefined as a variable, the interpreter will still process the statement with function syntax.

Note 2: Attempting to use a variable as arg1 in a command being processed as command syntax will result in an error.

Organization of Functions Distributed with Octave
=================================================

Many of Octave's standard functions are distributed as function files. They are loosely organized by topic, in subdirectories of OCTAVE-HOME/share/octave/VERSION/m, to make it easier to find them.

The following is a list of all the function file subdirectories, and the types of functions you will find there.

@ftp
     Class functions for the FTP object.

+containers
     Package for the containers classes.

audio
     Functions for playing and recording sounds.

deprecated
     Out-of-date functions which will eventually be removed from Octave.

elfun
     Elementary functions, principally trigonometric.

general
     Miscellaneous matrix manipulations, like flipud, rot90, and triu, as well as other basic functions, like ismatrix, narginchk, etc.

geometry
     Functions related to Delaunay triangulation.

gui
     Functions for GUI elements like dialog, message box, etc.

help
     Functions for Octave's built-in help system.

image
     Image processing tools.  These functions require the X Window System.

io
     Input-output functions.

java
     Functions related to the Java integration.

linear-algebra
     Functions for linear algebra.

miscellaneous
     Functions that don't really belong anywhere else.

ode
     Functions to solve ordinary differential equations (ODEs).

optimization
     Functions related to minimization, optimization, and root finding.

path
     Functions to manage the directory path Octave uses to find functions.

pkg
     Package manager for installing external packages of functions in Octave.

plot
     Functions for displaying and printing two- and three-dimensional graphs.

polynomial
     Functions for manipulating polynomials.

prefs
     Functions implementing user-defined preferences.

set
     Functions for creating and manipulating sets of unique values.

signal
     Functions for signal processing applications.

sparse
     Functions for handling sparse matrices.

specfun
     Special functions such as bessel or factor.

special-matrix
     Functions that create special matrix forms such as Hilbert or Vandermonde matrices.

startup
     Octave's system-wide startup file.

statistics
     Statistical functions.

strings
     Miscellaneous string-handling functions.

testfun
     Functions for performing unit tests on other functions.

time
     Functions related to time and date processing.