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 the list of directories specified by the built-in variable
`LOADPATH' for files ending in `.m' that have the same base name as the
undefined identifier.(1) 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. *Note 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. After
that, it checks the time stamp on the file every time it needs the
function. If the time stamp indicates that the file has changed since
the last time it was read, Octave reads it again.
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. Checking the
time stamp every time a function is used is rather inefficient, but it
has to be done to ensure that the correct function definition is used.
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 setting the variable
`ignore_function_time_stamp' to `"all"', so that Octave will ignore the
time stamps for all function files. Setting it to `"system"' gives the
default behavior. If you set it to anything else, Octave will check
the time stamps on all function files.
- Built-in Variable: DEFAULT_LOADPATH
A colon separated list of directories in which to search for
function files by default. The value of this variable is also
automatically substituted for leading, trailing, or doubled colons
that appear in the built-in variable `LOADPATH'.
- Built-in Variable: LOADPATH
A colon separated list of directories in which to search for
function files. *Note Functions and Scripts::. The value of
`LOADPATH' overrides the environment variable `OCTAVE_PATH'.
*Note Installation::.
`LOADPATH' is now handled in the same way as TeX handles
`TEXINPUTS'. Leading, trailing, or doubled colons that appear in
`LOADPATH' are replaced by the value of `DEFAULT_LOADPATH'. The
default value of `LOADPATH' is `":"', which tells Octave to search
in the directories specified by `DEFAULT_LOADPATH'.
In addition, if any path element ends in `//', that directory and
all subdirectories it contains are searched recursively for
function files. This can result in a slight delay as Octave
caches the lists of files found in the `LOADPATH' the first time
Octave searches for a function. After that, searching is usually
much faster because Octave normally only needs to search its
internal cache for files.
To improve performance of recursive directory searching, it is
best for each directory that is to be searched recursively to
contain _either_ additional subdirectories _or_ function files, but
not a mixture of both.
*Note Organization of Functions::, for a description of the
function file directories that are distributed with Octave.
- Built-in Function: rehash ()
Reinitialize Octave's `LOADPATH' directory cache.
- Built-in Function: file_in_loadpath (NAME)
Look up NAME in Octave's `LOADPATH'.
- Built-in Variable: ignore_function_time_stamp
This variable can be used to prevent Octave from making the system
call `stat' each time it looks up functions defined in function
files. If `ignore_function_time_stamp' to `"system"', Octave will
not automatically recompile function files in subdirectories of
`OCTAVE-HOME/lib/VERSION' if they have changed since they were
last compiled, but will recompile other function files in the
`LOADPATH' if they change. If set to `"all"', Octave will not
recompile any function files unless their definitions are removed
with `clear'. For any other value of `ignore_function_time_stamp',
Octave will always check to see if functions defined in function
files need to recompiled. The default value of
`ignore_function_time_stamp' is `"system"'.
- Built-in Variable: warn_function_name_clash
If the value of `warn_function_name_clash' is nonzero, a warning is
issued when Octave finds that the name of a function defined in a
function file differs from the name of the file. (If the names
disagree, the name declared inside the file is ignored.) If the
value is 0, the warning is omitted. The default value is 1.
- Built-in Variable: warn_future_time_stamp
If the value of this variable is nonzero, Octave will print a
warning if it finds a function file with a time stamp that is in
the future.
---------- Footnotes ----------
(1) The `.m' suffix was chosen for compatibility with MATLAB.
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 `LOADPATH',
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 `LOADPATH'.
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.
- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
Dynamically Linked Functions
============================
On some systems, Octave can dynamically load and execute functions
written in C++. Octave can only directly call functions written in C++,
but you can also load functions written in other languages by calling
them from a simple wrapper function written in C++.
Here is an example of how to write a C++ function that Octave can
load, with commentary. The source for this function is included in the
source distributions of Octave, in the file `examples/oregonator.cc'.
It defines the same set of differential equations that are used in the
example problem of *Note Ordinary Differential Equations::. By running
that example and this one, we can compare the execution times to see
what sort of increase in speed you can expect by using dynamically
linked functions.
The function defined in `oregonator.cc' contains just 8 statements,
and is not much different than the code defined in the corresponding
M-file (also distributed with Octave in the file
`examples/oregonator.m').
Here is the complete text of `oregonator.cc':
just
#include
DEFUN_DLD (oregonator, args, ,
"The `oregonator'.")
{
ColumnVector dx (3);
ColumnVector x (args(0).vector_value ());
dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0)
- 8.375e-06*pow (x(0), 2));
dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27;
dx(2) = 0.161*(x(0) - x(2));
return octave_value (dx);
}
The first line of the file,
#include
includes declarations for all of Octave's internal functions that you
will need. If you need other functions from the standard C++ or C
libraries, you can include the necessary headers here.
The next two lines
DEFUN_DLD (oregonator, args, ,
"The `oregonator'.")
declares the function. The macro `DEFUN_DLD' and the macros that it
depends on are defined in the files `defun-dld.h', `defun.h', and
`defun-int.h' (these files are included in the header file
`octave/oct.h').
Note that the third parameter to `DEFUN_DLD' (`nargout') is not
used, so it is omitted from the list of arguments in order to avoid the
warning from gcc about an unused function parameter.
The next line,
ColumnVector dx (3);
simply declares an object to store the right hand sides of the
differential equation, and the statement
ColumnVector x (args(0).vector_value ());
extracts a vector from the first input argument. The `vector_value'
method is used so that the user of the function can pass either a row
or column vector. The `ColumnVector' constructor is needed because the
ODE class requires a column vector. The variable `args' is passed to
functions defined with `DEFUN_DLD' as an `octave_value_list' object,
which includes methods for getting the length of the list and
extracting individual elements.
In this example, we don't check for errors, but that is not
difficult. All of the Octave's built-in functions do some form of
checking on their arguments, so you can check the source code for those
functions for examples of various strategies for verifying that the
correct number and types of arguments have been supplied.
The next statements
ColumnVector dx (3);
dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0)
- 8.375e-06*pow (x(0), 2));
dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27;
dx(2) = 0.161*(x(0) - x(2));
define the right hand side of the differential equation. Finally, we
can return `dx':
return octave_value (dx);
The actual return type is `octave_value_list', but it is only necessary
to convert the return type to an `octave_value' because there is a
default constructor that can automatically create an object of that
type from an `octave_value' object, so we can just use that instead.
To use this file, your version of Octave must support dynamic
linking. To find out if it does, type the command `octave_config_info
("dld")' at the Octave prompt. Support for dynamic linking is included
if this command returns 1.
To compile the example file, type the command `mkoctfile
oregonator.cc' at the shell prompt. The script `mkoctfile' should have
been installed along with Octave. Running it will create a file called
`oregonator.oct' that can be loaded by Octave. To test the
`oregonator.oct' file, start Octave and type the command
oregonator ([1, 2, 3], 0)
at the Octave prompt. Octave should respond by printing
ans =
77.269353
-0.012942
-0.322000
You can now use the `oregonator.oct' file just as you would the
`oregonator.m' file to solve the set of differential equations.
On a 133 MHz Pentium running Linux, Octave can solve the problem
shown in *Note Ordinary Differential Equations::, in about 1.4 seconds
using the dynamically linked function, compared to about 19 seconds
using the M-file. Similar decreases in execution time can be expected
for other functions, particularly those that rely on functions like
`lsode' that require user-supplied functions.
Just as for M-files, Octave will automatically reload a dynamically
linked function when the file that defines it is more recent than the
last time that the function was loaded. If more than one function is
defined in a single `.oct' file, reloading the file may force other
functions to be cleared and reloaded. If all the functions loaded from
a given `.oct' file are cleared, Octave will automatically unload the
`.oct' file.
- Built-in Variable: warn_reload_forces_clear
If several functions have been loaded from the same file, Octave
must clear all the functions before any one of them can be
reloaded. If `warn_reload_forces_clear', Octave will warn you
when this happens, and print a list of the additional functions
that it is forced to clear.
- variables_can_hide_functions:
If the value of this variable is nonzero, assignments to variables
may hide previously defined functions of the same name. A
negative value will cause Octave to print a warning, but allow the
operation.
Additional examples for writing dynamically linked functions are
available in the files in the `src' directory of the Octave
distribution. Currently, this includes the files
balance.cc fft2.cc inv.cc qzval.cc
chol.cc filter.cc log.cc schur.cc
colloc.cc find.cc lsode.cc sort.cc
dassl.cc fsolve.cc lu.cc svd.cc
det.cc givens.cc minmax.cc syl.cc
eig.cc hess.cc pinv.cc
expm.cc ifft.cc qr.cc
fft.cc ifft2.cc quad.cc
These files use the macro `DEFUN_DLD_BUILTIN' instead of `DEFUN_DLD'.
The difference between these two macros is just that
`DEFUN_DLD_BUILTIN' can define a built-in function that is not
dynamically loaded if the operating system does not support dynamic
linking. To define your own dynamically linked functions you should use
`DEFUN_DLD'.
There is currently no detailed description of all the functions that
you can call in a built-in function. For the time being, you will have
to read the source code for Octave.
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.
`control'
Functions for design and simulation of automatic control systems.
`elfun'
Elementary functions.
`general'
Miscellaneous matrix manipulations, like `flipud', `rot90', and
`triu', as well as other basic functions, like `is_matrix',
`nargchk', etc.
`image'
Image processing tools. These functions require the X Window
System.
`io'
Input-ouput functions.
`linear-algebra'
Functions for linear algebra.
`miscellaneous'
Functions that don't really belong anywhere else.
`plot'
A set of functions that implement the MATLAB-like plotting
functions.
`polynomial'
Functions for manipulating polynomials.
`set'
Functions for creating and manipulating sets of unique values.
`signal'
Functions for signal processing applications.
`specfun'
Special functions.
`special-matrix'
Functions that create special matrix forms.
`startup'
Octave's system-wide startup file.
`statistics'
Statistical functions.
`strings'
Miscellaneous string-handling functions.
`time'
Functions related to time keeping.
Error Handling
**************
Octave includes several functions for printing error and warning
messages. When you write functions that need to take special action
when they encounter abnormal conditions, you should print the error
messages using the functions described in this chapter.
- Built-in Function: error (TEMPLATE, ...)
The `error' function formats the optional arguments under the
control of the template string TEMPLATE using the same rules as
the `printf' family of functions (*note Formatted Output::). The
resulting message is prefixed by the string `error: ' and printed
on the `stderr' stream.
Calling `error' also sets Octave's internal error state such that
control will return to the top level without evaluating any more
commands. This is useful for aborting from functions or scripts.
If the error message does not end with a new line character,
Octave will print a traceback of all the function calls leading to
the error. For example, given the following function definitions:
function f () g () end
function g () h () end
function h () nargin == 1 || error ("nargin != 1"); end
calling the function `f' will result in a list of messages that
can help you to quickly locate the exact location of the error:
f ()
error: nargin != 1
error: evaluating index expression near line 1, column 30
error: evaluating binary operator `||' near line 1, column 27
error: called from `h'
error: called from `g'
error: called from `f'
If the error message ends in a new line character, Octave will
print the message but will not display any traceback messages as
it returns control to the top level. For example, modifying the
error message in the previous example to end in a new line causes
Octave to only print a single message:
function h () nargin == 1 || error ("nargin != 1\n"); end
f ()
error: nargin != 1
- Built-in Variable: error_text
This variable contains the text of error messages that would have
been printed in the body of the most recent `unwind_protect' or
`try' statement or the TRY part of the most recent call to the
`eval' function. Outside of the `unwind_protect' and `try'
statements or the `eval' function, or if no error has occurred
within them, the value of `error_text' is guaranteed to be the
empty string.
Note that the message does not include the first `error: ' prefix,
so that it may easily be passed to the `error' function without
additional processing(1).
*Note The try Statement::, and *Note The unwind_protect
Statement::.
- Built-in Variable: beep_on_error
If the value of `beep_on_error' is nonzero, Octave will try to
ring your terminal's bell before printing an error message. The
default value is 0.
- Built-in Function: warning (MSG)
Print a warning message MSG prefixed by the string `warning: '.
After printing the warning message, Octave will continue to execute
commands. You should use this function when you want to notify
the user of an unusual condition, but only when it makes sense for
your program to go on.
- Built-in Function: usage (MSG)
Print the message MSG, prefixed by the string `usage: ', and set
Octave's internal error state such that control will return to the
top level without evaluating any more commands. This is useful for
aborting from functions.
After `usage' is evaluated, Octave will print a traceback of all
the function calls leading to the usage message.
You should use this function for reporting problems errors that
result from an improper call to a function, such as calling a
function with an incorrect number of arguments, or with arguments
of the wrong type. For example, most functions distributed with
Octave begin with code like this
if (nargin != 2)
usage ("foo (a, b)");
endif
to check for the proper number of arguments.
The following pair of functions are of limited usefulness, and may be
removed from future versions of Octave.
- Function File: perror (NAME, NUM)
Print the error message for function NAME corresponding to the
error number NUM. This function is intended to be used to print
useful error messages for those functions that return numeric error
codes.
- Function File: strerror (NAME, NUM)
Return the text of an error message for function NAME
corresponding to the error number NUM. This function is intended
to be used to print useful error messages for those functions that
return numeric error codes.
---------- Footnotes ----------
(1) Yes, it's a kluge, but it seems to be a reasonably useful one.
Input and Output
****************
There are two distinct classes of input and output functions. The
first set are modeled after the functions available in MATLAB. The
second set are modeled after the standard I/O library used by the C
programming language and offer more flexibility and control over the
output.
When running interactively, Octave normally sends any output intended
for your terminal that is more than one screen long to a paging program,
such as `less' or `more'. This avoids the problem of having a large
volume of output stream by before you can read it. With `less' (and
some versions of `more') you can also scan forward and backward, and
search for specific items.
Normally, no output is displayed by the pager until just before
Octave is ready to print the top level prompt, or read from the
standard input (for example, by using the `fscanf' or `scanf'
functions). This means that there may be some delay before any output
appears on your screen if you have asked Octave to perform a
significant amount of work with a single command statement. The
function `fflush' may be used to force output to be sent to the pager
(or any other stream) immediately.
You can select the program to run as the pager by setting the
variable `PAGER', and you can turn paging off by setting the value of
the variable `page_screen_output' to 0.
- Command: more
- Command: more on
- Command: more off
Turn output pagination on or off. Without an argument, `more'
toggles the current state.
- Built-in Variable: PAGER
The default value is normally `"less"', `"more"', or `"pg"',
depending on what programs are installed on your system. *Note
Installation::.
When running interactively, Octave sends any output intended for
your terminal that is more than one screen long to the program
named by the value of the variable `PAGER'.
- Built-in Variable: page_screen_output
If the value of `page_screen_output' is nonzero, all output
intended for the screen that is longer than one page is sent
through a pager. This allows you to view one screenful at a time.
Some pagers (such as `less'--see *Note Installation::) are also
capable of moving backward on the output. The default value is 1.
- Built-in Variable: page_output_immediately
If the value of `page_output_immediately' is nonzero, Octave sends
output to the pager as soon as it is available. Otherwise, Octave
buffers its output and waits until just before the prompt is
printed to flush it to the pager. The default value is 0.
- Built-in Function: fflush (FID)
Flush output to FID. This is useful for ensuring that all pending
output makes it to the screen before some other event occurs. For
example, it is always a good idea to flush the standard output
stream before calling `input'.