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 additional 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

Although Octave does not automatically report an error if you call a function with more arguments than expected, doing so probably indicates that something is wrong.  Octave also does not automatically report an error if a function is called with too few arguments, but any attempt to use a variable that has not been given a value will result in an error. To avoid such problems and to provide useful messages, we check for both possibilities and issue our own error message.

(nargin)

(inputname)

(silent_functions)

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.

(nthargout)

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 lu functions are examples of built-in functions that behave differently depending on the value of nargout.

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.

(nargout)

It is good practice at the head of a function to verify that it has been called correctly.  In Octave the following idiom is seen frequently

     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.

(validateattributes)

For compatibility with MATLAB, nargchk, narginchk and nargoutchk are available which provide similar error checking.

(nargchk)

(narginchk)

(nargoutchk)

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

(parseparams)

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.  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

(isargout)

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.

(deal)

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.

 -- Keyword: 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.

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!

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)

(mfilename)

(ignore_function_time_stamp)

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)

(genpath)

(rmpath)

(savepath)

(path)

(pathdef)

(pathsep)

(rehash)

(file_in_loadpath)

(restoredefaultpath)

(command_line_path)

(dir_in_loadpath)

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.

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 ()
         ## Call 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)

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)

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,

     mlock ("my_function");

prevents my_function from being removed from memory, 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 illustrates.

     mlock ("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 ()
       persistent calls = 0;
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction
     mlock ("count_calls");

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

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

It is, however, often inconvenient to lock a function from the prompt, so it is also possible to lock a function from within its body.  This is simply done by calling mlock from within the function.

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

mlock might equally be used to prevent changes to a function from having effect in Octave, though a similar effect can be had with the ignore_function_time_stamp function.

(mlock)

(munlock)

(mislocked)

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 constuctors 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. Legacy Dispatch An overloaded function as defined by dispatch.

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

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

 8. 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.

 9. Built-in function A function that is builtin to Octave itself 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)

Function Handles, Anonymous Functions, Inline 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

(is_function_handle)

(functions)

(func2str)

(str2func)

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.

Inline Functions
----------------

An inline function is created from a string containing the function body using the inline function.  The following code defines the function f(x) = x^2 + 2.

     f = inline ("x^2 + 2");

After this it is possible to evaluate f at any x by writing f(x).

(inline)

(argnames)

(formula)

(symvar)

Commands
========

Commands are a special class of functions that only accept string input arguments.  A command can be called as an ordinary function, but it can also be called without the parentheses.  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", ...)

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

     toupper lower_case_arg
        => ans = LOWER_CASE_ARG

One difficulty of commands occurs when one of the string input arguments is stored in a variable.  Because Octave can't tell the difference between a variable name and an ordinary string, it is not possible to pass a variable as input to a command.  In such a situation a command must be called as a function.  For example:

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

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/lib/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.

audio
     Functions for playing and recording sounds.

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

elfun
     Elementary functions, principally trigonometric.

@ftp
     Class functions for the FTP object.

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

geometry
     Functions related to Delaunay triangulation.

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

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

io
     Input-output functions.

linear-algebra
     Functions for linear algebra.

miscellaneous
     Functions that don't really belong anywhere else.

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.