This is octave.info, produced by makeinfo version 6.1 from octave.texi.

START-INFO-DIR-ENTRY
* Octave: (octave).           Interactive language for numerical computations.

END-INFO-DIR-ENTRY

   Copyright © 1996-2016 John W. Eaton.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions.


File: octave.info,  Node: File Archiving Utilities,  Next: Networking Utilities,  Prev: Filesystem Utilities,  Up: System Utilities

36.3 File Archiving Utilities
=============================

 -- Function File: FILELIST = bunzip2 (BZFILE)
 -- Function File: FILELIST = bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where BZFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

     See also: *note bzip2: XREFbzip2, *note unpack: XREFunpack, *note
     gunzip: XREFgunzip, *note unzip: XREFunzip, *note untar: XREFuntar.

 -- Function File: FILELIST = gzip (FILES)
 -- Function File: FILELIST = gzip (FILES, DIR)
     Compress the list of files and directories specified in FILES.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Each file is compressed separately and a new file with a
     ‘".gz"’ extension is created.  The original files are not modified,
     but existing compressed files will be silently overwritten.  If a
     directory is specified then ‘gzip’ recursively compresses all files
     in the directory.

     If DIR is defined the compressed files are placed in this
     directory, rather than the original directory where the
     uncompressed file resides.  If DIR does not exist it is created.

     The optional output FILELIST is a list of the compressed files.

     See also: *note gunzip: XREFgunzip, *note unpack: XREFunpack, *note
     bzip2: XREFbzip2, *note zip: XREFzip, *note tar: XREFtar.

 -- Function File: FILELIST = gunzip (GZFILE)
 -- Function File: FILELIST = gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE.

     If GZFILE is a directory, all gzfiles in the directory will be
     recursively unpacked.

     If DIR is specified the files are unpacked in this directory rather
     than the one where GZFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

     See also: *note gzip: XREFgzip, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note unzip: XREFunzip, *note untar:
     XREFuntar.

 -- Function File: FILELIST = tar (TARFILE, FILES)
 -- Function File: FILELIST = tar (TARFILE, FILES, ROOTDIR)
     Pack the list of files and directories specified in FILES into the
     TAR archive TARFILE.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Directories are recursively traversed and all files are
     added to the archive.

     If ROOTDIR is defined then any files without absolute pathnames are
     located relative to ROOTDIR rather than the current directory.

     The optional output FILELIST is a list of the files that were
     included in the archive.

     See also: *note untar: XREFuntar, *note unpack: XREFunpack, *note
     bzip2: XREFbzip2, *note gzip: XREFgzip, *note zip: XREFzip.

 -- Function File: untar (TARFILE)
 -- Function File: untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where TARFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

     See also: *note tar: XREFtar, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note gunzip: XREFgunzip, *note unzip:
     XREFunzip.

 -- Function File: FILELIST = zip (ZIPFILE, FILES)
 -- Function File: FILELIST = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and directories specified in FILES into
     the ZIP archive ZIPFILE.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Directories are recursively traversed and all files are
     compressed and added to the archive.

     If ROOTDIR is defined then any files without absolute pathnames are
     located relative to ROOTDIR rather than the current directory.

     The optional output FILELIST is a list of the files that were
     included in the archive.

     See also: *note unzip: XREFunzip, *note unpack: XREFunpack, *note
     bzip2: XREFbzip2, *note gzip: XREFgzip, *note tar: XREFtar.

 -- Function File: FILELIST = unzip (ZIPFILE)
 -- Function File: FILELIST = unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where ZIPFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

     See also: *note zip: XREFzip, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note gunzip: XREFgunzip, *note untar:
     XREFuntar.

 -- Function File: FILES = unpack (FILE)
 -- Function File: FILES = unpack (FILE, DIR)
 -- Function File: FILES = unpack (FILE, DIR, FILETYPE)
     Unpack the archive FILE based on its extension to the directory
     DIR.

     If FILE is a list of strings, then each file is unpacked
     individually.  Shell wildcards in the filename such as ‘*’ or ‘?’
     are accepted and expanded.

     If DIR is not specified or is empty (‘[]’), it defaults to the
     current directory.  If a directory is in the file list, then
     FILETYPE must also be specified.

     The specific archive filetype is inferred from the extension of the
     file.  The FILETYPE may also be specified directly using a string
     which corresponds to a known extension.

     Valid filetype extensions:

     ‘bz’
     ‘bz2’
          bzip archive

     ‘gz’
          gzip archive

     ‘tar’
          tar archive

     ‘tarbz’
     ‘tarbz2’
     ‘tbz’
     ‘tbz2’
          tar + bzip archive

     ‘targz’
     ‘tgz’
          tar + gzip archive

     ‘z’
          compress archive

     ‘zip’
          zip archive

     The optional return value is a list of FILES unpacked.

     See also: *note bunzip2: XREFbunzip2, *note gunzip: XREFgunzip,
     *note unzip: XREFunzip, *note untar: XREFuntar, *note bzip2:
     XREFbzip2, *note gzip: XREFgzip, *note zip: XREFzip, *note tar:
     XREFtar.

 -- Function File: FILELIST = bzip2 (FILES)
 -- Function File: FILELIST = bzip2 (FILES, DIR)
     Compress the list of files specified in FILES.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Each file is compressed separately and a new file with a
     ‘".bz2"’ extension is created.  The original files are not
     modified, but existing compressed files will be silently
     overwritten.

     If DIR is defined the compressed files are placed in this
     directory, rather than the original directory where the
     uncompressed file resides.  If DIR does not exist it is created.

     The optional output FILELIST is a list of the compressed files.

     See also: *note bunzip2: XREFbunzip2, *note unpack: XREFunpack,
     *note gzip: XREFgzip, *note zip: XREFzip, *note tar: XREFtar.


File: octave.info,  Node: Networking Utilities,  Next: Controlling Subprocesses,  Prev: File Archiving Utilities,  Up: System Utilities

36.4 Networking Utilities
=========================

* Menu:

* FTP Objects::
* URL Manipulation::
* Base64 and Binary Data Transmission::

 -- Built-in Function: gethostname ()
     Return the hostname of the system where Octave is running.


File: octave.info,  Node: FTP Objects,  Next: URL Manipulation,  Up: Networking Utilities

36.4.1 FTP Objects
------------------

Octave supports the FTP protocol through an object-oriented interface.
Use the function ‘ftp’ to create an FTP object which represents the
connection.  All FTP functions take an FTP object as the first argument.

 -- Function File: F = ftp (HOST)
 -- Function File: F = ftp (HOST, USERNAME, PASSWORD)
     Connect to the FTP server HOST with USERNAME and PASSWORD.

     If USERNAME and PASSWORD are not specified, user "anonymous" with
     no password is used.  The returned FTP object F represents the
     established FTP connection.

     The list of actions for an FTP object are shown below.  All
     functions require an FTP object as the first argument.

     Method      Description
     -----------------------------------------------------------------------
     ascii       Set transfer type to ascii
     binary      Set transfer type to binary
     cd          Change remote working directory
     close       Close FTP connection
     delete      Delete remote file
     dir         List remote directory contents
     mget        Download remote files
     mkdir       Create remote directory
     mput        Upload local files
     rename      Rename remote file or directory
     rmdir       Remove remote directory

 -- Function File: close (F)
     Close the FTP connection represented by the FTP object F.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: mget (F, FILE)
 -- Function File: mget (F, DIR)
 -- Function File: mget (F, REMOTE_NAME, TARGET)
     Download a remote file FILE or directory DIR to the local directory
     on the FTP connection F.

     F is an FTP object returned by the ‘ftp’ function.

     The arguments FILE and DIR can include wildcards and any files or
     directories on the remote server that match will be downloaded.

     If a third argument TARGET is given, then a single file or
     directory will be downloaded to the local directory and the local
     name will be changed to TARGET.

 -- Function File: mput (F, FILE)
     Upload the local file FILE into the current remote directory on the
     FTP connection F.

     F is an FTP object returned by the ftp function.

     The argument FILE is passed through the ‘glob’ function and any
     files that match the wildcards in FILE will be uploaded.

 -- Function File: cd (F)
 -- Function File: cd (F, PATH)
     Get or set the remote directory on the FTP connection F.

     F is an FTP object returned by the ‘ftp’ function.

     If PATH is not specified, return the remote current working
     directory.  Otherwise, set the remote directory to PATH and return
     the new remote working directory.

     If the directory does not exist, an error message is printed and
     the working directory is not changed.

 -- Function File: LST = dir (F)
     List the current directory in verbose form for the FTP connection
     F.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: ascii (F)
     Set the FTP connection F to use ASCII mode for transfers.

     ASCII mode is only appropriate for text files as it will convert
     the remote host’s newline representation to the local host’s
     newline representation.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: binary (F)
     Set the FTP connection F to use binary mode for transfers.

     In binary mode there is no conversion of newlines from the remote
     representation to the local representation.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: delete (F, FILE)
     Delete the remote file FILE over the FTP connection F.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: rename (F, OLDNAME, NEWNAME)
     Rename or move the remote file or directory OLDNAME to NEWNAME,
     over the FTP connection F.

     F is an FTP object returned by the ftp function.

 -- Function File: mkdir (F, PATH)
     Create the remote directory PATH, over the FTP connection F.

     F is an FTP object returned by the ‘ftp’ function.

 -- Function File: rmdir (F, PATH)
     Remove the remote directory PATH, over the FTP connection F.

     F is an FTP object returned by the ‘ftp’ function.


File: octave.info,  Node: URL Manipulation,  Next: Base64 and Binary Data Transmission,  Prev: FTP Objects,  Up: Networking Utilities

36.4.2 URL Manipulation
-----------------------

 -- Loadable Function: S = urlread (URL)
 -- Loadable Function: [S, SUCCESS] = urlread (URL)
 -- Loadable Function: [S, SUCCESS, MESSAGE] = urlread (URL)
 -- Loadable Function: [...] = urlread (URL, METHOD, PARAM)
     Download a remote file specified by its URL and return its content
     in string S.

     For example:

          s = urlread ("ftp://ftp.octave.org/pub/README");

     The variable SUCCESS is 1 if the download was successful, otherwise
     it is 0 in which case MESSAGE contains an error message.

     If no output argument is specified and an error occurs, then the
     error is signaled through Octave’s error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL.  For example:

          s = urlread ("http://user:password@example.com/file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either ‘get’ or ‘post’ and PARAM is a cell
     array of parameter and value pairs.  For example:

          s = urlread ("http://www.google.com/search", "get",
                      {"query", "octave"});

     See also: *note urlwrite: XREFurlwrite.

 -- Loadable Function: urlwrite (URL, LOCALFILE)
 -- Loadable Function: F = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS] = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS, MESSAGE] = urlwrite (URL, LOCALFILE)
     Download a remote file specified by its URL and save it as
     LOCALFILE.

     For example:

          urlwrite ("ftp://ftp.octave.org/pub/README",
                    "README.txt");

     The full path of the downloaded file is returned in F.

     The variable SUCCESS is 1 if the download was successful, otherwise
     it is 0 in which case MESSAGE contains an error message.

     If no output argument is specified and an error occurs, then the
     error is signaled through Octave’s error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL, for example:

          urlwrite ("http://username:password@example.com/file.txt",
                    "file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either ‘get’ or ‘post’ and PARAM is a cell
     array of parameter and value pairs.  For example:

          urlwrite ("http://www.google.com/search", "search.html",
                    "get", {"query", "octave"});

     See also: *note urlread: XREFurlread.


File: octave.info,  Node: Base64 and Binary Data Transmission,  Prev: URL Manipulation,  Up: Networking Utilities

36.4.3 Base64 and Binary Data Transmission
------------------------------------------

Some transmission channels can not accept binary data.  It is customary
to encode binary data in Base64 for transmission and to decode the data
upon reception.

 -- Built-in Function: S = base64_encode (X)
     Encode a double matrix or array X into the base64 format string S.

     See also: *note base64_decode: XREFbase64_decode.

 -- Built-in Function: X = base64_decode (S)
 -- Built-in Function: X = base64_decode (S, DIMS)
     Decode the double matrix or array X from the base64 encoded string
     S.

     The optional input parameter DIMS should be a vector containing the
     dimensions of the decoded array.

     See also: *note base64_encode: XREFbase64_encode.


File: octave.info,  Node: Controlling Subprocesses,  Next: Process ID Information,  Prev: Networking Utilities,  Up: System Utilities

36.5 Controlling Subprocesses
=============================

Octave includes some high-level commands like ‘system’ and ‘popen’ for
starting subprocesses.  If you want to run another program to perform
some task and then look at its output, you will probably want to use
these functions.

   Octave also provides several very low-level Unix-like functions which
can also be used for starting subprocesses, but you should probably only
use them if you can’t find any way to do what you need with the
higher-level functions.

 -- Built-in Function: system ("STRING")
 -- Built-in Function: system ("STRING", RETURN_OUTPUT)
 -- Built-in Function: system ("STRING", RETURN_OUTPUT, TYPE)
 -- Built-in Function: [STATUS, OUTPUT] = system (...)
     Execute a shell command specified by STRING.

     If the optional argument TYPE is "async", the process is started in
     the background and the process ID of the child process is returned
     immediately.  Otherwise, the child process is started and Octave
     waits until it exits.  If the TYPE argument is omitted, it defaults
     to the value "sync".

     If SYSTEM is called with one or more output arguments, or if the
     optional argument RETURN_OUTPUT is true and the subprocess is
     started synchronously, then the output from the command is returned
     as a variable.  Otherwise, if the subprocess is executed
     synchronously, its output is sent to the standard output.  To send
     the output of a command executed with ‘system’ through the pager,
     use a command like

          [output, text] = system ("cmd");
          disp (text);

     or

          printf ("%s\n", nthargout (2, "system", "cmd"));

     The ‘system’ function can return two values.  The first is the exit
     status of the command and the second is any output from the command
     that was written to the standard output stream.  For example,

          [status, output] = system ("echo foo; exit 2");

     will set the variable ‘output’ to the string ‘foo’, and the
     variable ‘status’ to the integer ‘2’.

     For commands run asynchronously, STATUS is the process id of the
     command shell that is started to run the command.

     See also: *note unix: XREFunix, *note dos: XREFdos.

 -- Function File: unix ("COMMAND")
 -- Function File: STATUS = unix ("COMMAND")
 -- Function File: [STATUS, TEXT] = unix ("COMMAND")
 -- Function File: [...] = unix ("COMMAND", "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.

     Octave waits for the external command to finish before returning
     the exit status of the program in STATUS and any output in TEXT.

     When called with no output argument, or the "-echo" argument is
     given, then TEXT is also sent to standard output.

     See also: *note dos: XREFdos, *note system: XREFsystem, *note
     isunix: XREFisunix, *note ismac: XREFismac, *note ispc: XREFispc.

 -- Function File: dos ("COMMAND")
 -- Function File: STATUS = dos ("COMMAND")
 -- Function File: [STATUS, TEXT] = dos ("COMMAND")
 -- Function File: [...] = dos ("COMMAND", "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.

     Octave waits for the external command to finish before returning
     the exit status of the program in STATUS and any output in TEXT.

     When called with no output argument, or the "-echo" argument is
     given, then TEXT is also sent to standard output.

     See also: *note unix: XREFunix, *note system: XREFsystem, *note
     isunix: XREFisunix, *note ismac: XREFismac, *note ispc: XREFispc.

 -- Function File: OUTPUT = open FILE
 -- Function File: OUTPUT = open (FILE)
     Open the file FILE in Octave or in an external application based on
     the file type as determined by the file name extension.

     Recognized file types are

     ‘.m’
          Open file in the editor.

     ‘.mat’
          Load the file in the base workspace.

     ‘.exe’
          Execute the program (on Windows systems only).

     Other file types are opened in the appropriate external
     application.

 -- Function File: OUTPUT = perl (SCRIPTFILE)
 -- Function File: OUTPUT = perl (SCRIPTFILE, ARGUMENT1, ARGUMENT2, ...)
 -- Function File: [OUTPUT, STATUS] = perl (...)
     Invoke Perl script SCRIPTFILE, possibly with a list of command line
     arguments.

     Return output in OUTPUT and optional status in STATUS.  If
     SCRIPTFILE is not an absolute file name it is searched for in the
     current directory and then in the Octave loadpath.

     See also: *note system: XREFsystem, *note python: XREFpython.

 -- Function File: OUTPUT = python (SCRIPTFILE)
 -- Function File: OUTPUT = python (SCRIPTFILE, ARGUMENT1, ARGUMENT2,
          ...)
 -- Function File: [OUTPUT, STATUS] = python (...)
     Invoke Python script SCRIPTFILE, possibly with a list of command
     line arguments.

     Return output in OUTPUT and optional status in STATUS.  If
     SCRIPTFILE is not an absolute file name it is searched for in the
     current directory and then in the Octave loadpath.

     See also: *note system: XREFsystem, *note perl: XREFperl.

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.

     The name of the command to run is given by COMMAND.  The argument
     MODE may be

     ‘"r"’
          The pipe will be connected to the standard output of the
          process, and open for reading.

     ‘"w"’
          The pipe will be connected to the standard input of the
          process, and open for writing.

     The file identifier corresponding to the input or output stream of
     the process is returned in FID.

     For example:

          fid = popen ("ls -ltr / | tail -3", "r");
          while (ischar (s = fgets (fid)))
            fputs (stdout, s);
          endwhile

             ⊣ drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
             ⊣ drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
             ⊣ drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

     See also: *note popen2: XREFpopen2.

 -- Built-in Function: pclose (FID)
     Close a file identifier that was opened by ‘popen’.

     The function ‘fclose’ may also be used for the same purpose.

     See also: *note fclose: XREFfclose, *note popen: XREFpopen.

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.

     The name of the process is given by COMMAND, and ARGS is an array
     of strings containing options for the command.

     The file identifiers for the input and output streams of the
     subprocess are returned in IN and OUT.  If execution of the command
     is successful, PID contains the process ID of the subprocess.
     Otherwise, PID is −1.

     For example:

          [in, out, pid] = popen2 ("sort", "-r");
          fputs (in, "these\nare\nsome\nstrings\n");
          fclose (in);
          EAGAIN = errno ("EAGAIN");
          done = false;
          do
            s = fgets (out);
            if (ischar (s))
              fputs (stdout, s);
            elseif (errno () == EAGAIN)
              sleep (0.1);
              fclear (out);
            else
              done = true;
            endif
          until (done)
          fclose (out);
          waitpid (pid);

             ⊣ these
             ⊣ strings
             ⊣ some
             ⊣ are

     Note that ‘popen2’, unlike ‘popen’, will not "reap" the child
     process.  If you don’t use ‘waitpid’ to check the child’s exit
     status, it will linger until Octave exits.

     See also: *note popen: XREFpopen, *note waitpid: XREFwaitpid.

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
 -- Built-in Function: EXEC_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated
     list of directories to append to the shell PATH when executing
     external programs.

     The initial value of is taken from the environment variable
     ‘OCTAVE_EXEC_PATH’, but that value can be overridden by the command
     line argument ‘--exec-path PATH’.

     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.

     See also: *note IMAGE_PATH: XREFIMAGE_PATH, *note OCTAVE_HOME:
     XREFOCTAVE_HOME.

   In most cases, the following functions simply decode their arguments
and make the corresponding Unix system calls.  For a complete example of
how they can be used, look at the definition of the function ‘popen2’.

 -- Built-in Function: [PID, MSG] = fork ()
     Create a copy of the current process.

     Fork can return one of the following values:

     > 0
          You are in the parent process.  The value returned from ‘fork’
          is the process id of the child process.  You should probably
          arrange to wait for any child processes to exit.

     0
          You are in the child process.  You can call ‘exec’ to start
          another process.  If that fails, you should probably call
          ‘exit’.

     < 0
          The call to ‘fork’ failed for some reason.  You must take
          evasive action.  A system dependent error message will be
          waiting in MSG.

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.

     Calling ‘exec’ without first calling ‘fork’ will terminate your
     current Octave process and replace it with the program named by
     FILE.  For example,

          exec ("ls" "-l")

     will run ‘ls’ and return you to your shell prompt.

     If successful, ‘exec’ does not return.  If ‘exec’ does return, ERR
     will be nonzero, and MSG will contain a system-dependent error
     message.

 -- Built-in Function: [READ_FD, WRITE_FD, ERR, MSG] = pipe ()
     Create a pipe and return the reading and writing ends of the pipe
     into READ_FD and WRITE_FD respectively.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise, ERR
     is nonzero and MSG contains a system-dependent error message.

     See also: *note mkfifo: XREFmkfifo.

 -- Built-in Function: [FID, MSG] = dup2 (OLD, NEW)
     Duplicate a file descriptor.

     If successful, FID is greater than zero and contains the new file
     ID.  Otherwise, FID is negative and MSG contains a system-dependent
     error message.

     See also: *note fopen: XREFfopen, *note fclose: XREFfclose, *note
     fcntl: XREFfcntl.

 -- Built-in Function: [PID, STATUS, MSG] = waitpid (PID, OPTIONS)
     Wait for process PID to terminate.

     The PID argument can be:

     −1
          Wait for any child process.

     0
          Wait for any child process whose process group ID is equal to
          that of the Octave interpreter process.

     > 0
          Wait for termination of the child process with ID PID.

     The OPTIONS argument can be a bitwise OR of zero or more of the
     following constants:

     ‘0’
          Wait until signal is received or a child process exits (this
          is the default if the OPTIONS argument is missing).

     ‘WNOHANG’
          Do not hang if status is not immediately available.

     ‘WUNTRACED’
          Report the status of any child processes that are stopped, and
          whose status has not yet been reported since they stopped.

     ‘WCONTINUE’
          Return if a stopped child has been resumed by delivery of
          ‘SIGCONT’.  This value may not be meaningful on all systems.

     If the returned value of PID is greater than 0, it is the process
     ID of the child process that exited.  If an error occurs, PID will
     be less than zero and MSG will contain a system-dependent error
     message.  The value of STATUS contains additional system-dependent
     information about the subprocess that exited.

     See also: *note WCONTINUE: XREFWCONTINUE, *note WCOREDUMP:
     XREFWCOREDUMP, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFCONTINUED: XREFWIFCONTINUED, *note WIFSIGNALED: XREFWIFSIGNALED,
     *note WIFSTOPPED: XREFWIFSTOPPED, *note WNOHANG: XREFWNOHANG, *note
     WSTOPSIG: XREFWSTOPSIG, *note WTERMSIG: XREFWTERMSIG, *note
     WUNTRACED: XREFWUNTRACED.

 -- Built-in Function: WCONTINUE ()
     Return the numerical value of the option argument that may be
     passed to ‘waitpid’ to indicate that it should also return if a
     stopped child has been resumed by delivery of a ‘SIGCONT’ signal.

     See also: *note waitpid: XREFwaitpid, *note WNOHANG: XREFWNOHANG,
     *note WUNTRACED: XREFWUNTRACED.

 -- Built-in Function: WCOREDUMP (STATUS)
     Given STATUS from a call to ‘waitpid’, return true if the child
     produced a core dump.

     This function should only be employed if ‘WIFSIGNALED’ returned
     true.  The macro used to implement this function is not specified
     in POSIX.1-2001 and is not available on some Unix implementations
     (e.g., AIX, SunOS).

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WEXITSTATUS (STATUS)
     Given STATUS from a call to ‘waitpid’, return the exit status of
     the child.

     This function should only be employed if ‘WIFEXITED’ returned true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG:
     XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED:
     XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note WIFCONTINUED:
     XREFWIFCONTINUED.

 -- Built-in Function: WIFCONTINUED (STATUS)
     Given STATUS from a call to ‘waitpid’, return true if the child
     process was resumed by delivery of ‘SIGCONT’.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED: XREFWIFSTOPPED, *note
     WSTOPSIG: XREFWSTOPSIG.

 -- Built-in Function: WIFSIGNALED (STATUS)
     Given STATUS from a call to ‘waitpid’, return true if the child
     process was terminated by a signal.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note WTERMSIG:
     XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED:
     XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note WIFCONTINUED:
     XREFWIFCONTINUED.

 -- Built-in Function: WIFSTOPPED (STATUS)
     Given STATUS from a call to ‘waitpid’, return true if the child
     process was stopped by delivery of a signal.

     This is only possible if the call was done using ‘WUNTRACED’ or
     when the child is being traced (see ptrace(2)).

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WIFEXITED (STATUS)
     Given STATUS from a call to ‘waitpid’, return true if the child
     terminated normally.

     See also: *note waitpid: XREFwaitpid, *note WEXITSTATUS:
     XREFWEXITSTATUS, *note WIFSIGNALED: XREFWIFSIGNALED, *note
     WTERMSIG: XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WNOHANG ()
     Return the numerical value of the option argument that may be
     passed to ‘waitpid’ to indicate that it should return its status
     immediately instead of waiting for a process to exit.

     See also: *note waitpid: XREFwaitpid, *note WUNTRACED:
     XREFWUNTRACED, *note WCONTINUE: XREFWCONTINUE.

 -- Built-in Function: WSTOPSIG (STATUS)
     Given STATUS from a call to ‘waitpid’, return the number of the
     signal which caused the child to stop.

     This function should only be employed if ‘WIFSTOPPED’ returned
     true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED: XREFWIFSTOPPED, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WTERMSIG (STATUS)
     Given STATUS from a call to ‘waitpid’, return the number of the
     signal that caused the child process to terminate.

     This function should only be employed if ‘WIFSIGNALED’ returned
     true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WCOREDUMP: XREFWCOREDUMP, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WUNTRACED ()
     Return the numerical value of the option argument that may be
     passed to ‘waitpid’ to indicate that it should also return if the
     child process has stopped but is not traced via the ‘ptrace’ system
     call

     See also: *note waitpid: XREFwaitpid, *note WNOHANG: XREFWNOHANG,
     *note WCONTINUE: XREFWCONTINUE.

 -- Built-in Function: [ERR, MSG] = fcntl (FID, REQUEST, ARG)
     Change the properties of the open file FID.

     The following values may be passed as REQUEST:

     ‘F_DUPFD’
          Return a duplicate file descriptor.

     ‘F_GETFD’
          Return the file descriptor flags for FID.

     ‘F_SETFD’
          Set the file descriptor flags for FID.

     ‘F_GETFL’
          Return the file status flags for FID.  The following codes may
          be returned (some of the flags may be undefined on some
          systems).

          ‘O_RDONLY’
               Open for reading only.

          ‘O_WRONLY’
               Open for writing only.

          ‘O_RDWR’
               Open for reading and writing.

          ‘O_APPEND’
               Append on each write.

          ‘O_CREAT’
               Create the file if it does not exist.

          ‘O_NONBLOCK’
               Non-blocking mode.

          ‘O_SYNC’
               Wait for writes to complete.

          ‘O_ASYNC’
               Asynchronous I/O.

     ‘F_SETFL’
          Set the file status flags for FID to the value specified by
          ARG.  The only flags that can be changed are ‘O_APPEND’ and
          ‘O_NONBLOCK’.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise, ERR
     is nonzero and MSG contains a system-dependent error message.

     See also: *note fopen: XREFfopen, *note dup2: XREFdup2.

 -- Built-in Function: [ERR, MSG] = kill (PID, SIG)
     Send signal SIG to process PID.

     If PID is positive, then signal SIG is sent to PID.

     If PID is 0, then signal SIG is sent to every process in the
     process group of the current process.

     If PID is -1, then signal SIG is sent to every process except
     process 1.

     If PID is less than -1, then signal SIG is sent to every process in
     the process group -PID.

     If SIG is 0, then no signal is sent, but error checking is still
     performed.

     Return 0 if successful, otherwise return -1.

 -- Built-in Function: SIG ()
     Return a structure containing Unix signal names and their defined
     values.


File: octave.info,  Node: Process ID Information,  Next: Environment Variables,  Prev: Controlling Subprocesses,  Up: System Utilities

36.6 Process, Group, and User IDs
=================================

 -- Built-in Function: pgid = getpgrp ()
     Return the process group id of the current process.

 -- Built-in Function: pid = getpid ()
     Return the process id of the current process.

     See also: *note getppid: XREFgetppid.

 -- Built-in Function: pid = getppid ()
     Return the process id of the parent process.

     See also: *note getpid: XREFgetpid.

 -- Built-in Function: euid = geteuid ()
     Return the effective user id of the current process.

     See also: *note getuid: XREFgetuid.

 -- Built-in Function: uid = getuid ()
     Return the real user id of the current process.

     See also: *note geteuid: XREFgeteuid.

 -- Built-in Function: egid = getegid ()
     Return the effective group id of the current process.

     See also: *note getgid: XREFgetgid.

 -- Built-in Function: gid = getgid ()
     Return the real group id of the current process.

     See also: *note getegid: XREFgetegid.


File: octave.info,  Node: Environment Variables,  Next: Current Working Directory,  Prev: Process ID Information,  Up: System Utilities

36.7 Environment Variables
==========================

 -- Built-in Function: getenv (VAR)
     Return the value of the environment variable VAR.

     For example,

          getenv ("PATH")

     returns a string containing the value of your path.

     See also: *note setenv: XREFsetenv, *note unsetenv: XREFunsetenv.

 -- Built-in Function: setenv (VAR, VALUE)
 -- Built-in Function: setenv (VAR)
 -- Built-in Function: putenv (...)
     Set the value of the environment variable VAR to VALUE.

     If no VALUE is specified then the variable will be assigned the
     null string.

     See also: *note unsetenv: XREFunsetenv, *note getenv: XREFgetenv.

 -- Built-in Function: STATUS = unsetenv (VAR)
     Delete the environment variable VAR.

     Return 0 if the variable was deleted, or did not exist, and -1 if
     an error occurred.

     See also: *note setenv: XREFsetenv, *note getenv: XREFgetenv.

 -- Built-in Function: HOMEDIR = get_home_directory ()
     Return the current home directory.

     On most systems, this is equivalent to ‘getenv ("HOME")’.  On
     Windows systems, if the environment variable ‘HOME’ is not set then
     it is equivalent to ‘fullfile (getenv ("HOMEDRIVE"), getenv
     ("HOMEPATH"))’

     See also: *note getenv: XREFgetenv.


File: octave.info,  Node: Current Working Directory,  Next: Password Database Functions,  Prev: Environment Variables,  Up: System Utilities

36.8 Current Working Directory
==============================

 -- Command: cd DIR
 -- Command: cd
 -- Built-in Function: OLD_DIR = cd (DIR)
 -- Command: chdir ...
     Change the current working directory to DIR.

     If DIR is omitted, the current directory is changed to the user’s
     home directory ("~").

     For example,

          cd ~/octave

     changes the current working directory to ‘~/octave’.  If the
     directory does not exist, an error message is printed and the
     working directory is not changed.

     ‘chdir’ is an alias for ‘cd’ and can be used in all of the same
     calling formats.

     Compatibility Note: When called with no arguments, MATLAB prints
     the present working directory rather than changing to the user’s
     home directory.

     See also: *note pwd: XREFpwd, *note mkdir: XREFmkdir, *note rmdir:
     XREFrmdir, *note dir: XREFdir, *note ls: XREFls.

 -- Command: ls
 -- Command: ls FILENAMES
 -- Command: ls OPTIONS
 -- Command: ls OPTIONS FILENAMES
 -- Function File: LIST = ls (...)

     List directory contents.

     The ‘ls’ command is implemented by calling the native operating
     system’s directory listing command—available OPTIONS will vary from
     system to system.

     Filenames are subject to shell expansion if they contain any
     wildcard characters ‘*’, ‘?’, ‘[]’.  To find a literal example of a
     wildcard character the wildcard must be escaped using the backslash
     operator ‘\’.

     If the optional output LIST is requested then ‘ls’ returns a
     character array with one row for each file/directory name.

     Example usage on a UNIX-like system:

          ls -l
               ⊣ total 12
               ⊣ -rw-r--r--   1 jwe  users  4488 Aug 19 04:02 foo.m
               ⊣ -rw-r--r--   1 jwe  users  1315 Aug 17 23:14 bar.m

     See also: *note dir: XREFdir, *note readdir: XREFreaddir, *note
     glob: XREFglob, *note what: XREFwhat, *note stat: XREFstat, *note
     filesep: XREFfilesep, *note ls_command: XREFls_command.

 -- Function File: VAL = ls_command ()
 -- Function File: OLD_VAL = ls_command (NEW_VAL)
     Query or set the shell command used by Octave’s ‘ls’ command.

     See also: *note ls: XREFls.

 -- Function File: dir
 -- Function File: dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.

     If DIRECTORY is not specified then list the present working
     directory.

     If a return value is requested, return a structure array with the
     fields

     name
          File or directory name.

     date
          Timestamp of file modification (string value).

     bytes
          File size in bytes.

     isdir
          True if name is a directory.

     datenum
          Timestamp of file modification as serial date number (double).

     statinfo
          Information structure returned from ‘stat’.

     If DIRECTORY is a filename, rather than a directory, then return
     information about the named file.  DIRECTORY may also be a list
     rather than a single directory or file.

     DIRECTORY is subject to shell expansion if it contains any wildcard
     characters ‘*’, ‘?’, ‘[]’.  To find a literal example of a wildcard
     character the wildcard must be escaped using the backslash operator
     ‘\’.

     Note that for symbolic links, ‘dir’ returns information about the
     file that the symbolic link points to rather than the link itself.
     However, if the link points to a nonexistent file, ‘dir’ returns
     information about the link.

     See also: *note ls: XREFls, *note readdir: XREFreaddir, *note glob:
     XREFglob, *note what: XREFwhat, *note stat: XREFstat, *note lstat:
     XREFlstat.

 -- Built-in Function: pwd ()
 -- Built-in Function: DIR = pwd ()
     Return the current working directory.

     See also: *note cd: XREFcd, *note dir: XREFdir, *note ls: XREFls,
     *note mkdir: XREFmkdir, *note rmdir: XREFrmdir.


File: octave.info,  Node: Password Database Functions,  Next: Group Database Functions,  Prev: Current Working Directory,  Up: System Utilities

36.9 Password Database Functions
================================

Octave’s password database functions return information in a structure
with the following fields.

‘name’
     The user name.

‘passwd’
     The encrypted password, if available.

‘uid’
     The numeric user id.

‘gid’
     The numeric group id.

‘gecos’
     The GECOS field.

‘dir’
     The home directory.

‘shell’
     The initial shell.

   In the descriptions of the following functions, this data structure
is referred to as a PW_STRUCT.

 -- Built-in Function: PW_STRUCT = getpwent ()
     Return a structure containing an entry from the password database,
     opening it if necessary.

     Once the end of the data has been reached, ‘getpwent’ returns 0.

     See also: *note setpwent: XREFsetpwent, *note endpwent:
     XREFendpwent.

 -- Built-in Function: PW_STRUCT = getpwuid (UID).
     Return a structure containing the first entry from the password
     database with the user ID UID.

     If the user ID does not exist in the database, ‘getpwuid’ returns
     0.

     See also: *note getpwnam: XREFgetpwnam.

 -- Built-in Function: PW_STRUCT = getpwnam (NAME)
     Return a structure containing the first entry from the password
     database with the user name NAME.

     If the user name does not exist in the database, ‘getpwname’
     returns 0.

     See also: *note getpwuid: XREFgetpwuid.

 -- Built-in Function: setpwent ()
     Return the internal pointer to the beginning of the password
     database.

     See also: *note getpwent: XREFgetpwent, *note endpwent:
     XREFendpwent.

 -- Built-in Function: endpwent ()
     Close the password database.

     See also: *note getpwent: XREFgetpwent, *note setpwent:
     XREFsetpwent.


File: octave.info,  Node: Group Database Functions,  Next: System Information,  Prev: Password Database Functions,  Up: System Utilities

36.10 Group Database Functions
==============================

Octave’s group database functions return information in a structure with
the following fields.

‘name’
     The user name.

‘passwd’
     The encrypted password, if available.

‘gid’
     The numeric group id.

‘mem’
     The members of the group.

   In the descriptions of the following functions, this data structure
is referred to as a GRP_STRUCT.

 -- Built-in Function: GRP_STRUCT = getgrent ()
     Return an entry from the group database, opening it if necessary.

     Once the end of data has been reached, ‘getgrent’ returns 0.

     See also: *note setgrent: XREFsetgrent, *note endgrent:
     XREFendgrent.

 -- Built-in Function: GRP_STRUCT = getgrgid (GID).
     Return the first entry from the group database with the group ID
     GID.

     If the group ID does not exist in the database, ‘getgrgid’ returns
     0.

     See also: *note getgrnam: XREFgetgrnam.

 -- Built-in Function: GRP_STRUCT = getgrnam (NAME)
     Return the first entry from the group database with the group name
     NAME.

     If the group name does not exist in the database, ‘getgrnam’
     returns 0.

     See also: *note getgrgid: XREFgetgrgid.

 -- Built-in Function: setgrent ()
     Return the internal pointer to the beginning of the group database.

     See also: *note getgrent: XREFgetgrent, *note endgrent:
     XREFendgrent.

 -- Built-in Function: endgrent ()
     Close the group database.

     See also: *note getgrent: XREFgetgrent, *note setgrent:
     XREFsetgrent.


File: octave.info,  Node: System Information,  Next: Hashing Functions,  Prev: Group Database Functions,  Up: System Utilities

36.11 System Information
========================

 -- Function File: computer ()
 -- Function File: C = computer ()
 -- Function File: [C, MAXSIZE] = computer ()
 -- Function File: [C, MAXSIZE, ENDIAN] = computer ()
 -- Function File: ARCH = computer ("arch")
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the type of computer that Octave is running on.

     If invoked with an output argument, the value is returned instead
     of printed.  For example:

          computer ()
             ⊣ i586-pc-linux-gnu

          mycomp = computer ()
             ⇒ mycomp = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.  This will depend on whether
     Octave has been compiled with 32-bit or 64-bit index vectors.

     If three output arguments are requested, also return the byte order
     of the current system as a character ("B" for big-endian or "L" for
     little-endian).

     If the argument "arch" is specified, return a string indicating the
     architecture of the computer on which Octave is running.

     See also: *note isunix: XREFisunix, *note ismac: XREFismac, *note
     ispc: XREFispc.

 -- Built-in Function: [UTS, ERR, MSG] = uname ()
     Return system information in the structure.

     For example:

          uname ()
             ⇒ {
                   sysname = x86_64
                   nodename = segfault
                   release = 2.6.15-1-amd64-k8-smp
                   version = Linux
                   machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006
                }

     If successful, ERR is 0 and MSG is an empty string.  Otherwise, ERR
     is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: nproc ()
 -- Built-in Function: nproc (QUERY)
     Return the current number of available processors.

     If called with the optional argument QUERY, modify how processors
     are counted as follows:

     ‘all’
          total number of processors.

     ‘current’
          processors available to the current process.

     ‘overridable’
          same as ‘current’, but overridable through the
          ‘OMP_NUM_THREADS’ environment variable.

 -- Function File: ispc ()
     Return true if Octave is running on a Windows system and false
     otherwise.

     See also: *note isunix: XREFisunix, *note ismac: XREFismac.

 -- Function File: isunix ()
     Return true if Octave is running on a Unix-like system and false
     otherwise.

     See also: *note ismac: XREFismac, *note ispc: XREFispc.

 -- Function File: ismac ()
     Return true if Octave is running on a Mac OS X system and false
     otherwise.

     See also: *note isunix: XREFisunix, *note ispc: XREFispc.

 -- Built-in Function: isieee ()
     Return true if your computer _claims_ to conform to the IEEE
     standard for floating point calculations.

     No actual tests are performed.

 -- Function File: isdeployed ()
     Return true if the current program has been compiled and is running
     separately from the Octave interpreter and false if it is running
     in the Octave interpreter.

     Currently, this function always returns false in Octave.

 -- Built-in Function: isstudent ()
     Return true if running in the student edition of MATLAB.

     ‘isstudent’ always returns false in Octave.

     See also: *note false: XREFfalse.

 -- Built-in Function: OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory.

     See also: *note EXEC_PATH: XREFEXEC_PATH, *note IMAGE_PATH:
     XREFIMAGE_PATH.

 -- Function File: matlabroot ()
     Return the name of the top-level Octave installation directory.

     This is an alias for the function ‘OCTAVE_HOME’ provided for
     compatibility.

     See also: *note OCTAVE_HOME: XREFOCTAVE_HOME.

 -- Built-in Function: OCTAVE_VERSION ()
     Return the version number of Octave as a string.

     See also: *note ver: XREFver, *note version: XREFversion.

 -- Function File: version ()
     Return the version number of Octave as a string.

     This is an alias for the function ‘OCTAVE_VERSION’ provided for
     compatibility.

     See also: *note OCTAVE_VERSION: XREFOCTAVE_VERSION, *note ver:
     XREFver.

 -- Function File: ver
 -- Function File: ver Octave
 -- Function File: ver PACKAGE
 -- Function File: v = ver (...)

     Display a header containing the current Octave version number,
     license string, and operating system.  The header is followed by a
     list of installed packages, versions, and installation directories.

     Use the package name PACKAGE or Octave to limit the listing to a
     desired component.

     When called with an output argument, return a vector of structures
     describing Octave and each installed package.  The structure
     includes the following fields.

     ‘Name’
          Package name.

     ‘Version’
          Version of the package.

     ‘Revision’
          Revision of the package.

     ‘Date’
          Date of the version/revision.

     See also: *note version: XREFversion, *note octave_config_info:
     XREFoctave_config_info, *note usejava: XREFusejava, *note pkg:
     XREFpkg.

 -- Function File: compare_versions (V1, V2, OPERATOR)
     Compare two version strings using the given OPERATOR.

     This function assumes that versions V1 and V2 are arbitrarily long
     strings made of numeric and period characters possibly followed by
     an arbitrary string (e.g., "1.2.3", "0.3", "0.1.2+", or
     "1.2.3.4-test1").

     The version is first split into numeric and character portions and
     then the parts are padded to be the same length (i.e., "1.1" would
     be padded to be "1.1.0" when being compared with "1.1.1", and
     separately, the character parts of the strings are padded with
     nulls).

     The operator can be any logical operator from the set

        • "==" equal

        • "<" less than

        • "<=" less than or equal to

        • ">" greater than

        • ">=" greater than or equal to

        • "!=" not equal

        • "~=" not equal

     Note that version "1.1-test2" will compare as greater than
     "1.1-test10".  Also, since the numeric part is compared first, "a"
     compares less than "1a" because the second string starts with a
     numeric part even though ‘double ("a")’ is greater than ‘double
     ("1").’

 -- Command: license
 -- Command: license inuse
 -- Command: license inuse FEATURE
 -- Function File: license ("inuse")
 -- Function File: RETVAL = license ("inuse")
 -- Function File: RETVAL = license ("test", FEATURE)
 -- Function File: RETVAL = license ("checkout", FEATURE)
 -- Function File: [RETVAL, ERRMSG] = license ("checkout", FEATURE)
     Get license information for Octave and Octave packages.

     GNU Octave is free software distributed under the GNU General
     Public License (GPL), and a license manager makes no sense.  This
     function is provided only for MATLAB compatibility.

     When called with no extra input arguments, it returns the Octave
     license, otherwise the first input defines the operation mode and
     must be one of the following strings: ‘inuse’, ‘test’, and
     ‘checkout’.  The optional FEATURE argument can either be "octave"
     (core), or an Octave package.

     "inuse"
          Returns a list of loaded features, i.e., octave and the list
          of loaded packages.  If an output is requested, it returns a
          struct array with the fields "feature", and "user".

     "test"
          Return true if the specified FEATURE is installed, false
          otherwise.

          An optional third argument "enable" or "disable" is accepted
          but ignored.

     "checkout"
          Return true if the specified FEATURE is installed, false
          otherwise.  An optional second output will have an error
          message if a package is not installed.

     See also: *note pkg: XREFpkg, *note ver: XREFver, *note version:
     XREFversion.

 -- Built-in Function: octave_config_info ()
 -- Built-in Function: octave_config_info (OPTION)
     Return a structure containing configuration and installation
     information for Octave.

     If OPTION is a string, return the configuration information for the
     specified option.

     See also: *note computer: XREFcomputer.

 -- Built-in Function: getrusage ()
     Return a structure containing a number of statistics about the
     current Octave process.

     Not all fields are available on all systems.  If it is not possible
     to get CPU time statistics, the CPU time slots are set to zero.
     Other missing data are replaced by NaN.  The list of possible
     fields is:

     ‘idrss’
          Unshared data size.

     ‘inblock’
          Number of block input operations.

     ‘isrss’
          Unshared stack size.

     ‘ixrss’
          Shared memory size.

     ‘majflt’
          Number of major page faults.

     ‘maxrss’
          Maximum data size.

     ‘minflt’
          Number of minor page faults.

     ‘msgrcv’
          Number of messages received.

     ‘msgsnd’
          Number of messages sent.

     ‘nivcsw’
          Number of involuntary context switches.

     ‘nsignals’
          Number of signals received.

     ‘nswap’
          Number of swaps.

     ‘nvcsw’
          Number of voluntary context switches.

     ‘oublock’
          Number of block output operations.

     ‘stime’
          A structure containing the system CPU time used.  The
          structure has the elements ‘sec’ (seconds) ‘usec’
          (microseconds).

     ‘utime’
          A structure containing the user CPU time used.  The structure
          has the elements ‘sec’ (seconds) ‘usec’ (microseconds).


File: octave.info,  Node: Hashing Functions,  Prev: System Information,  Up: System Utilities

36.12 Hashing Functions
=======================

It is often necessary to find if two strings or files are identical.
This might be done by comparing them character by character and looking
for differences.  However, this can be slow, and so comparing a hash of
the string or file can be a rapid way of finding if the files differ.

   Another use of the hashing function is to check for file integrity.
The user can check the hash of the file against a known value and find
if the file they have is the same as the one that the original hash was
produced with.

   Octave supplies the ‘md5sum’ function to perform MD5 hashes on
strings and files.  An example of the use of ‘md5sum’ function might be

     if exist (file, "file")
       hash = md5sum (file);
     else
       # Treat the variable "file" as a string
       hash = md5sum (file, true);
     endif

 -- Built-in Function: md5sum (FILE)
 -- Built-in Function: md5sum (STR, OPT)
     Calculate the MD5 sum of the file FILE.

     If the second parameter OPT exists and is true, then calculate the
     MD5 sum of the string STR.


File: octave.info,  Node: Java Interface,  Next: Packages,  Prev: System Utilities,  Up: Top

37 Java Interface
*****************

The Java Interface is designed for calling Java functions from within
Octave.  If you want to do the reverse, and call Octave from within
Java, try a library like ‘javaOctave’
(<http://kenai.com/projects/javaOctave>) or ‘joPas’
(<http://jopas.sourceforge.net>).

* Menu:

* Java Interface Functions::
* Dialog Box Functions::
* FAQ - Frequently asked Questions::


File: octave.info,  Node: Java Interface Functions,  Next: Dialog Box Functions,  Up: Java Interface

37.1 Java Interface Functions
=============================

The following functions are the core of the Java Interface.  They
provide a way to create a Java object, get and set its data fields, and
call Java methods which return results to Octave.

 -- Built-in Function: JOBJ = javaObject (CLASSNAME)
 -- Built-in Function: JOBJ = javaObject (CLASSNAME, ARG1, ...)
     Create a Java object of class CLASSSNAME, by calling the class
     constructor with the arguments ARG1, ...

     The first example below creates an uninitialized object, while the
     second example supplies an initial argument to the constructor.

          x = javaObject ("java.lang.StringBuffer")
          x = javaObject ("java.lang.StringBuffer", "Initial string")

     See also: *note javaMethod: XREFjavaMethod, *note javaArray:
     XREFjavaArray.

 -- Function File: JARY = javaArray (CLASSNAME, SZ)
 -- Function File: JARY = javaArray (CLASSNAME, M, N, ...)

     Create a Java array of size SZ with elements of class CLASSNAME.

     CLASSNAME may be a Java object representing a class or a string
     containing the fully qualified class name.  The size of the object
     may also be specified with individual integer arguments M, N, etc.

     The generated array is uninitialized.  All elements are set to null
     if CLASSNAME is a reference type, or to a default value (usually 0)
     if CLASSNAME is a primitive type.

     Sample code:

          jary = javaArray ("java.lang.String", 2, 2);
          jary(1,1) = "Hello";

     See also: *note javaObject: XREFjavaObject.

   There are many different variable types in Octave but only ones
created through ‘javaObject’ can use Java functions.  Before using Java
with an unknown object the type can be checked with ‘isjava’.

 -- Built-in Function: isjava (X)
     Return true if X is a Java object.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo,
     *note isa: XREFisa, *note javaObject: XREFjavaObject.

   Once an object has been created it is natural to find out what fields
the object has and to read (get) and write (set) them.

   In Octave the ‘fieldnames’ function for structures has been
overloaded to return the fields of a Java object.  For example:

     dobj = javaObject ("java.lang.Double", pi);
     fieldnames (dobj)
     ⇒
     {
       [1,1] = public static final double java.lang.Double.POSITIVE_INFINITY
       [1,2] = public static final double java.lang.Double.NEGATIVE_INFINITY
       [1,3] = public static final double java.lang.Double.NaN
       [1,4] = public static final double java.lang.Double.MAX_VALUE
       [1,5] = public static final double java.lang.Double.MIN_NORMAL
       [1,6] = public static final double java.lang.Double.MIN_VALUE
       [1,7] = public static final int java.lang.Double.MAX_EXPONENT
       [1,8] = public static final int java.lang.Double.MIN_EXPONENT
       [1,9] = public static final int java.lang.Double.SIZE
       [1,10] = public static final java.lang.Class java.lang.Double.TYPE
     }

   The analogy of objects with structures is carried over into reading
and writing object fields.  To read a field the object is indexed with
the ‘.’ operator from structures.  This is the preferred method for
reading fields, but Octave also provides a function interface to read
fields with ‘java_get’.  An example of both styles is shown below.

     dobj = javaObject ("java.lang.Double", pi);
     dobj.MAX_VALUE
     ⇒  1.7977e+308
     java_get ("java.lang.Float", "MAX_VALUE")
     ⇒  3.4028e+38

 -- Function File: VAL = java_get (OBJ, NAME)
     Get the value of the field NAME of the Java object OBJ.

     For static fields, OBJ can be a string representing the fully
     qualified name of the corresponding class.

     When OBJ is a regular Java object, structure-like indexing can be
     used as a shortcut syntax.  For instance, the following two
     statements are equivalent

            java_get (x, "field1")
            x.field1

     See also: *note java_set: XREFjava_set, *note javaMethod:
     XREFjavaMethod, *note javaObject: XREFjavaObject.

 -- Function File: OBJ = java_set (OBJ, NAME, VAL)
     Set the value of the field NAME of the Java object OBJ to VAL.

     For static fields, OBJ can be a string representing the fully
     qualified named of the corresponding Java class.

     When OBJ is a regular Java object, structure-like indexing can be
     used as a shortcut syntax.  For instance, the following two
     statements are equivalent

            java_set (x, "field1", val)
            x.field1 = val

     See also: *note java_get: XREFjava_get, *note javaMethod:
     XREFjavaMethod, *note javaObject: XREFjavaObject.

   To see what functions can be called with an object use ‘methods’.
For example, using the previously created DOBJ:

     methods (dobj)
     ⇒
     Methods for class java.lang.Double:
     boolean equals(java.lang.Object)
     java.lang.String toString(double)
     java.lang.String toString()
     ...

   To call a method of an object the same structure indexing operator
‘.’ is used.  Octave also provides a functional interface to calling the
methods of an object through ‘javaMethod’.  An example showing both
styles is shown below.

     dobj = javaObject ("java.lang.Double", pi);
     dobj.equals (3)
     ⇒  0
     javaMethod ("equals", dobj, pi)
     ⇒  1

 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ)
 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ, ARG1, ...)
     Invoke the method METHODNAME on the Java object OBJ with the
     arguments ARG1, ....

     For static methods, OBJ can be a string representing the fully
     qualified name of the corresponding class.

     When OBJ is a regular Java object, structure-like indexing can be
     used as a shortcut syntax.  For instance, the two following
     statements are equivalent

            ret = javaMethod ("method1", x, 1.0, "a string")
            ret = x.method1 (1.0, "a string")

     ‘javaMethod’ returns the result of the method invocation.

     See also: *note methods: XREFmethods, *note javaObject:
     XREFjavaObject.

   The following three functions are used to display and modify the
class path used by the Java Virtual Machine.  This is entirely separate
from Octave’s PATH variable and is used by the JVM to find the correct
code to execute.

 -- Function File: javaclasspath ()
 -- Function File: DPATH = javaclasspath ()
 -- Function File: [DPATH, SPATH] = javaclasspath ()
 -- Function File: CLSPATH = javaclasspath (WHAT)
     Return the class path of the Java virtual machine in the form of a
     cell array of strings.

     If called with no inputs:

        • If no output is requested, the dynamic and static classpaths
          are printed to the standard output.

        • If one output value DPATH is requested, the result is the
          dynamic classpath.

        • If two output valuesDPATH and SPATH are requested, the first
          variable will contain the dynamic classpath and the second
          will contain the static classpath.

     If called with a single input parameter WHAT:

     "-dynamic"
          Return the dynamic classpath.

     "-static"
          Return the static classpath.

     "-all"
          Return both the static and dynamic classpath in a single
          cellstr.

     See also: *note javaaddpath: XREFjavaaddpath, *note javarmpath:
     XREFjavarmpath.

 -- Function File: javaaddpath (CLSPATH)
 -- Function File: javaaddpath (CLSPATH1, ...)
     Add CLSPATH to the dynamic class path of the Java virtual machine.

     CLSPATH may either be a directory where ‘.class’ files are found,
     or a ‘.jar’ file containing Java classes.  Multiple paths may be
     added at once by specifying additional arguments.

     See also: *note javarmpath: XREFjavarmpath, *note javaclasspath:
     XREFjavaclasspath.

 -- Function File: javarmpath (CLSPATH)
 -- Function File: javarmpath (CLSPATH1, ...)
     Remove CLSPATH from the dynamic class path of the Java virtual
     machine.

     CLSPATH may either be a directory where ‘.class’ files are found,
     or a ‘.jar’ file containing Java classes.  Multiple paths may be
     removed at once by specifying additional arguments.

     See also: *note javaaddpath: XREFjavaaddpath, *note javaclasspath:
     XREFjavaclasspath.

   The following functions provide information and control over the
interface between Octave and the Java Virtual Machine.

 -- Function File: javachk (FEATURE)
 -- Function File: javachk (FEATURE, COMPONENT)
 -- Function File: MSG = javachk (...)
     Check for the presence of the Java FEATURE in the current session
     and print or return an error message if it is not.

     Possible features are:

     "awt"
          Abstract Window Toolkit for GUIs.

     "desktop"
          Interactive desktop is running.

     "jvm"
          Java Virtual Machine.

     "swing"
          Swing components for lightweight GUIs.

     If FEATURE is supported and

        • no output argument is requested:

          Return an empty string

        • an output argument is requested:

          Return a struct with fields "feature" and "identifier" both
          empty

     If FEATURE is not supported and

        • no output argument is requested:

          Emit an error message

        • an output argument is requested:

          Return a struct with field "feature" set to FEATURE and field
          "identifier" set to COMPONENT

     The optional input COMPONENT will be used in place of FEATURE in
     any error messages for greater specificity.

     ‘javachk’ determines if specific Java features are available in an
     Octave session.  This function is provided for scripts which may
     alter their behavior based on the availability of Java.  The
     feature "desktop" is never available as Octave has no Java-based
     desktop.  Other features may be available if Octave was compiled
     with the Java Interface and Java is installed.

     See also: *note usejava: XREFusejava, *note error: XREFerror.

 -- Function File: usejava (FEATURE)
     Return true if the Java element FEATURE is available.

     Possible features are:

     "awt"
          Abstract Window Toolkit for GUIs.

     "desktop"
          Interactive desktop is running.

     "jvm"
          Java Virtual Machine.

     "swing"
          Swing components for lightweight GUIs.

     ‘usejava’ determines if specific Java features are available in an
     Octave session.  This function is provided for scripts which may
     alter their behavior based on the availability of Java.  The
     feature "desktop" always returns ‘false’ as Octave has no
     Java-based desktop.  Other features may be available if Octave was
     compiled with the Java Interface and Java is installed.

     See also: *note javachk: XREFjavachk.

 -- Function File: javamem ()
 -- Function File: JMEM = javamem ()
     Show the current memory usage of the Java virtual machine (JVM) and
     run the garbage collector.

     When no return argument is given the info is printed to the screen.
     Otherwise, the output cell array JMEM contains Maximum, Total, and
     Free memory (in bytes).

     All Java-based routines are run in the JVM’s shared memory pool, a
     dedicated and separate part of memory claimed by the JVM from your
     computer’s total memory (which comprises physical RAM and virtual
     memory / swap space on hard disk).

     The maximum allowable memory usage can be configured using the file
     ‘java.opts’.  The directory where this file resides is determined
     by the environment variable ‘OCTAVE_JAVA_DIR’.  If unset, the
     directory where ‘javaaddpath.m’ resides is used instead (typically
     ‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’).

     ‘java.opts’ is a plain text file with one option per line.  The
     default initial memory size and default maximum memory size (which
     are both system dependent) can be overridden like so:

     -Xms64m

     -Xmx512m

     (in megabytes in this example).  You can adapt these values to your
     own requirements if your system has limited available physical
     memory or if you get Java memory errors.

     "Total memory" is what the operating system has currently assigned
     to the JVM and depends on actual and active memory usage.  "Free
     memory" is self-explanatory.  During operation of Java-based Octave
     functions the amount of Total and Free memory will vary, due to
     Java’s own cleaning up and your operating system’s memory
     management.

 -- Built-in Function: VAL = java_matrix_autoconversion ()
 -- Built-in Function: OLD_VAL = java_matrix_autoconversion (NEW_VAL)
 -- Built-in Function: java_matrix_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls whether Java
     arrays are automatically converted to Octave matrices.

     The default value is false.

     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.

     See also: *note java_unsigned_autoconversion:
     XREFjava_unsigned_autoconversion, *note debug_java: XREFdebug_java.

 -- Built-in Function: VAL = java_unsigned_autoconversion ()
 -- Built-in Function: OLD_VAL = java_unsigned_autoconversion (NEW_VAL)
 -- Built-in Function: java_unsigned_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls how integer
     classes are converted when ‘java_matrix_autoconversion’ is enabled.

     When enabled, Java arrays of class Byte or Integer are converted to
     matrices of class uint8 or uint32 respectively.  The default value
     is true.

     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.

     See also: *note java_matrix_autoconversion:
     XREFjava_matrix_autoconversion, *note debug_java: XREFdebug_java.

 -- Built-in Function: VAL = debug_java ()
 -- Built-in Function: OLD_VAL = debug_java (NEW_VAL)
 -- Built-in Function: debug_java (NEW_VAL, "local")
     Query or set the internal variable that determines whether extra
     debugging information regarding the initialization of the JVM and
     any Java exceptions is printed.

     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.

     See also: *note java_matrix_autoconversion:
     XREFjava_matrix_autoconversion, *note java_unsigned_autoconversion:
     XREFjava_unsigned_autoconversion.


File: octave.info,  Node: Dialog Box Functions,  Next: FAQ - Frequently asked Questions,  Prev: Java Interface Functions,  Up: Java Interface

37.2 Dialog Box Functions
=========================

The following functions all use the Java Interface to provide some form
of dialog box.

 -- Function File: H = msgbox (MSG)
 -- Function File: H = msgbox (MSG, TITLE)
 -- Function File: H = msgbox (MSG, TITLE, ICON)
 -- Function File: H = msgbox (..., CREATEMODE)
     Display MSG using a message dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional input TITLE (character string) can be used to decorate
     the dialog caption.

     The optional argument ICON selects a dialog icon.  It can be one of
     "none" (default), "error", "help", or "warn".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: H = errordlg (MSG)
 -- Function File: H = errordlg (MSG, TITLE)
 -- Function File: H = errordlg (MSG, TITLE, CREATEMODE)
     Display MSG using an error dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional input TITLE (character string) can be used to set the
     dialog caption.  The default title is "Error Dialog".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.

     See also: *note helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: H = helpdlg (MSG)
 -- Function File: H = helpdlg (MSG, TITLE)
     Display MSG in a help dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional input TITLE (character string) can be used to set the
     dialog caption.  The default title is "Help Dialog".

     The return value is always 1.

     See also: *note errordlg: XREFerrordlg, *note inputdlg:
     XREFinputdlg, *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: CSTR = inputdlg (PROMPT)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS)
     Return user input from a multi-textfield dialog box in a cell array
     of strings, or an empty cell array if the dialog is closed by the
     Cancel button.

     Inputs:

     PROMPT
          A cell array with strings labeling each text field.  This
          input is required.

     TITLE
          String to use for the caption of the dialog.  The default is
          "Input Dialog".

     ROWSCOLS
          Specifies the size of the text fields and can take three
          forms:

            1. a scalar value which defines the number of rows used for
               each text field.

            2. a vector which defines the individual number of rows used
               for each text field.

            3. a matrix which defines the individual number of rows and
               columns used for each text field.  In the matrix each row
               describes a single text field.  The first column
               specifies the number of input rows to use and the second
               column specifies the text field width.

     DEFAULTS
          A list of default values to place in each text fields.  It
          must be a cell array of strings with the same size as PROMPT.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: [SEL, OK] = listdlg (KEY, VALUE, ...)
     Return user inputs from a list dialog box in a vector of selection
     indices SEL and a flag OK indicating how the user closed the dialog
     box.

     The value of OK is 1 if the user closed the box with the OK button,
     otherwise it is 0 and SEL is empty.

     The indices in SEL are 1-based.

     The arguments are specified in form of KEY, VALUE pairs.  The
     "ListString" argument pair must be specified.

     Valid KEY and VALUE pairs are:

     "ListString"
          a cell array of strings comprising the content of the list.

     "SelectionMode"
          can be either "Single" or "Multiple" (default).

     "ListSize"
          a vector with two elements WIDTH and HEIGHT defining the size
          of the list field in pixels.  Default is [160 300].

     "InitialValue"
          a vector containing 1-based indices of preselected elements.
          Default is 1 (first item).

     "Name"
          a string to be used as the dialog caption.  Default is "".

     "PromptString"
          a cell array of strings to be displayed above the list field.
          Default is {}.

     "OKString"
          a string used to label the OK button.  Default is "OK".

     "CancelString"
          a string used to label the Cancel button.  Default is
          "Cancel".

     Example:

          [sel, ok] = listdlg ("ListString", {"An item", "another", "yet another"},
                               "SelectionMode", "Multiple");
          if (ok == 1)
            for i = 1:numel (sel)
              disp (sel(i));
            endfor
          endif

     See also: *note menu: XREFmenu, *note errordlg: XREFerrordlg, *note
     helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg, *note msgbox:
     XREFmsgbox, *note questdlg: XREFquestdlg, *note warndlg:
     XREFwarndlg.

 -- Function File: BTN = questdlg (MSG)
 -- Function File: BTN = questdlg (MSG, TITLE)
 -- Function File: BTN = questdlg (MSG, TITLE, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, BTN3,
          DEFAULT)
     Display MSG using a question dialog box and return the caption of
     the activated button.

     The dialog may contain two or three buttons which will all close
     the dialog.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional TITLE (character string) can be used to decorate the
     dialog caption.

     The string DEFAULT identifies the default button, which is
     activated by pressing the <ENTER> key.  It must match one of the
     strings given in BTN1, BTN2, or BTN3.

     If only MSG and TITLE are specified, three buttons with the default
     captions "Yes", "No", and "Cancel" are used.

     If only two button captions, BTN1 and BTN2, are specified the
     dialog will have only these two buttons.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     warndlg: XREFwarndlg.

 -- Function File: H = warndlg (MSG)
 -- Function File: H = warndlg (MSG, TITLE)
 -- Function File: H = warndlg (MSG, TITLE, CREATEMODE)
     Display MSG using a warning dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.

     The optional input TITLE (character string) can be used to set the
     dialog caption.  The default title is "Warning Dialog".

     The return value is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.

     See also: *note helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg,
     *note listdlg: XREFlistdlg, *note questdlg: XREFquestdlg.


File: octave.info,  Node: FAQ - Frequently asked Questions,  Prev: Dialog Box Functions,  Up: Java Interface

37.3 FAQ - Frequently asked Questions
=====================================

* Menu:

* How to distinguish between Octave and Matlab?::
* How to make Java classes available?::
* How to create an instance of a Java class?::
* How can I handle memory limitations?::
* Which TeX symbols are implemented in dialog functions?::


File: octave.info,  Node: How to distinguish between Octave and Matlab?,  Next: How to make Java classes available?,  Up: FAQ - Frequently asked Questions

37.3.1 How to distinguish between Octave and Matlab?
----------------------------------------------------

Octave and MATLAB are very similar, but handle Java slightly different.
Therefore it may be necessary to detect the environment and use the
appropriate functions.  The following function can be used to detect the
environment.  Due to the persistent variable it can be called repeatedly
without a heavy performance hit.

   Example:

     %%
     %% Return: true if the environment is Octave.
     %%
     function retval = isOctave
       persistent cacheval;  % speeds up repeated calls

       if isempty (cacheval)
         cacheval = (exist ("OCTAVE_VERSION", "builtin") > 0);
       end

       retval = cacheval;
     end


File: octave.info,  Node: How to make Java classes available?,  Next: How to create an instance of a Java class?,  Prev: How to distinguish between Octave and Matlab?,  Up: FAQ - Frequently asked Questions

37.3.2 How to make Java classes available to Octave?
----------------------------------------------------

Java finds classes by searching a CLASSPATH.  This is a list of Java
archive files and/or directories containing class files.  In Octave the
CLASSPATH is composed of two parts:

   • the STATIC CLASSPATH is initialized once at startup of the JVM, and

   • the DYNAMIC CLASSPATH which can be modified at runtime.

   Octave searches the STATIC CLASSPATH first, then the DYNAMIC
CLASSPATH.  Classes appearing in the STATIC as well as in the DYNAMIC
CLASSPATH will therefore be found in the STATIC CLASSPATH and loaded
from this location.  Classes which will be used frequently or must be
available to all users should be added to the STATIC CLASSPATH.  The
STATIC CLASSPATH is populated once from the contents of a plain text
file named ‘javaclasspath.txt’ (or ‘classpath.txt’ historically) when
the Java Virtual Machine starts.  This file contains one line for each
individual classpath to be added to the STATIC CLASSPATH.  These lines
can identify single class files, directories containing class files, or
Java archives with complete class file hierarchies.  Comment lines
starting with a ‘#’ or a ‘%’ character are ignored.

   The search rules for the file ‘javaclasspath.txt’ (or
‘classpath.txt’) are:

   • First, Octave tries to locate it in the current directory (where
     Octave was started from).  If such a file is found, it is read and
     defines the initial STATIC CLASSPATH.  Thus, it is possible to
     define a static classpath on a ’per Octave invocation’ basis.

   • Next, Octave searches in the user’s home directory.  If a file
     ‘javaclasspath.txt’ exists here, its contents are appended to the
     static classpath (if any).  Thus, it is possible to build an
     initial static classpath on a ’per user’ basis.

   • Finally, Octave looks for a next occurrence of file
     ‘javaclasspath.txt’ in the m-files directory where Octave Java
     functions live.  This is where ‘javaclasspath.m’ resides, usually
     something like ‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’.
     You can find this directory by executing the command

          which javaclasspath

     If this file exists here, its contents are also appended to the
     static classpath.  Note that the archives and class directories
     defined in this last step will affect all users.

   Classes which are used only by a specific script should be placed in
the DYNAMIC CLASSPATH.  This portion of the classpath can be modified at
runtime using the ‘javaaddpath’ and ‘javarmpath’ functions.

   Example:

     octave> base_path = "C:/Octave/java_files";

     octave> % add two JARchives to the dynamic classpath
     octave> javaaddpath ([base_path, "/someclasses.jar"]);
     octave> javaaddpath ([base_path, "/moreclasses.jar"]);

     octave> % check the dynamic classpath
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/someclasses.jar
     octave> disp (p{2});
     C:/Octave/java_files/moreclasses.jar

     octave> % remove the first element from the classpath
     octave> javarmpath ([base_path, "/someclasses.jar"]);
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/moreclasses.jar

     octave> % provoke an error
     octave> disp (p{2});
     error: A(I): Index exceeds matrix dimension.

   Another way to add files to the DYNAMIC CLASSPATH exclusively for
your user account is to use the file ‘.octaverc’ which is stored in your
home directory.  All Octave commands in this file are executed each time
you start a new instance of Octave.  The following example adds the
directory ‘octave’ to Octave’s search path and the archive
‘myclasses.jar’ in this directory to the Java search path.

     % contents of .octaverc:
     addpath ("~/octave");
     javaaddpath ("~/octave/myclasses.jar");


File: octave.info,  Node: How to create an instance of a Java class?,  Next: How can I handle memory limitations?,  Prev: How to make Java classes available?,  Up: FAQ - Frequently asked Questions

37.3.3 How to create an instance of a Java class?
-------------------------------------------------

The function ‘javaObject’ can be used to create Java objects..

   Example:

     Passenger = javaObject ("package.FirstClass", row, seat);


File: octave.info,  Node: How can I handle memory limitations?,  Next: Which TeX symbols are implemented in dialog functions?,  Prev: How to create an instance of a Java class?,  Up: FAQ - Frequently asked Questions

37.3.4 How can I handle memory limitations?
-------------------------------------------

In order to execute Java code Octave creates a Java Virtual Machine
(JVM). Such a JVM allocates a fixed amount of initial memory and may
expand this pool up to a fixed maximum memory limit.  The default values
depend on the Java version (*note javamem: XREFjavamem.).  The memory
pool is shared by all Java objects running in the JVM.  This strict
memory limit is intended mainly to avoid that runaway applications
inside web browsers or in enterprise servers can consume all memory and
crash the system.  When the maximum memory limit is hit, Java code will
throw exceptions so that applications will fail or behave unexpectedly.

   You can specify options for the creation of the JVM inside a file
named ‘java.opts’.  This is a text file where you can enter lines
containing ‘-X’ and ‘-D’ options handed to the JVM during
initialization.

   The directory where the Java options file is located is specified by
the environment variable ‘OCTAVE_JAVA_DIR’.  If unset the directory
where ‘javaclasspath.m’ resides is used instead (typically
‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’).  You can find this
directory by executing

     which javaclasspath

   The ‘-X’ options allow you to increase the maximum amount of memory
available to the JVM.  The following example allows up to 256 Megabytes
to be used by adding the following line to the ‘java.opts’ file:

     -Xmx256m

   The maximum possible amount of memory depends on your system.  On a
Windows system with 2 Gigabytes main memory you should be able to set
this maximum to about 1 Gigabyte.

   If your application requires a large amount of memory from the
beginning, you can also specify the initial amount of memory allocated
to the JVM.  Adding the following line to the ‘java.opts’ file starts
the JVM with 64 Megabytes of initial memory:

     -Xms64m

   For more details on the available ‘-X’ options of your Java Virtual
Machine issue the command ‘java -X’ at the operating system command
prompt and consult the Java documentation.

   The ‘-D’ options can be used to define system properties which can
then be used by Java classes inside Octave.  System properties can be
retrieved by using the ‘getProperty()’ methods of the ‘java.lang.System’
class.  The following example line defines the property MYPROPERTY and
assigns it the string ‘12.34’.

     -DMyProperty=12.34

   The value of this property can then be retrieved as a string by a
Java object or in Octave:

     octave> javaMethod ("getProperty", "java.lang.System", "MyProperty");
     ans = 12.34

See also: javamem.


File: octave.info,  Node: Which TeX symbols are implemented in dialog functions?,  Prev: How can I handle memory limitations?,  Up: FAQ - Frequently asked Questions

37.3.5 Which TeX symbols are implemented in dialog functions?
-------------------------------------------------------------

The dialog functions contain a translation table for TeX like symbol
codes.  Thus messages and labels can be tailored to show some common
mathematical symbols or Greek characters.  No further TeX formatting
codes are supported.  The characters are translated to their Unicode
equivalent.  However, not all characters may be displayable on your
system.  This depends on the font used by the Java system on your
computer.

   Each TeX symbol code must be terminated by a space character to make
it distinguishable from the surrounding text.  Therefore the string
‘\alpha =12.0’ will produce the desired result, whereas ‘\alpha=12.0’
would produce the literal text ’\ALPHA=12.0’.

See also: errordlg, helpdlg, inputdlg, listdlg, msgbox, questdlg,
warndlg.


File: octave.info,  Node: Packages,  Next: External Code Interface,  Prev: Java Interface,  Up: Top

38 Packages
***********

Since Octave is Free Software users are encouraged to share their
programs amongst each other.  To aid this sharing Octave supports the
installation of extra packages.  The ‘Octave-Forge’ project is a
community-maintained set of packages that can be downloaded and
installed in Octave.  At the time of writing the ‘Octave-Forge’ project
can be found online at <http://octave.sourceforge.net>, but since the
Internet is an ever-changing place this may not be true at the time of
reading.  Therefore it is recommended to see the Octave website for an
updated reference.

* Menu:

* Installing and Removing Packages::
* Using Packages::
* Administrating Packages::
* Creating Packages::


File: octave.info,  Node: Installing and Removing Packages,  Next: Using Packages,  Up: Packages

38.1 Installing and Removing Packages
=====================================

Assuming a package is available in the file ‘image-1.0.0.tar.gz’ it can
be installed from the Octave prompt with the command

     pkg install image-1.0.0.tar.gz

If the package is installed successfully nothing will be printed on the
prompt, but if an error occurred during installation it will be
reported.  It is possible to install several packages at once by writing
several package files after the ‘pkg install’ command.  If a different
version of the package is already installed it will be removed prior to
installing the new package.  This makes it easy to upgrade and downgrade
the version of a package, but makes it impossible to have several
versions of the same package installed at once.

   To see which packages are installed type

     pkg list
     ⊣ Package Name  | Version | Installation directory
     ⊣ --------------+---------+-----------------------
     ⊣        image *|   1.0.0 | /home/jwe/octave/image-1.0.0

In this case only version 1.0.0 of the ‘image’ package is installed.
The ’*’ character next to the package name shows that the image package
is loaded and ready for use.

   It is possible to remove a package from the system using the ‘pkg
uninstall’ command like this

     pkg uninstall image

If the package is removed successfully nothing will be printed in the
prompt, but if an error occurred it will be reported.  It should be
noted that the package file used for installation is not needed for
removal, and that only the package name as reported by ‘pkg list’ should
be used when removing a package.  It is possible to remove several
packages at once by writing several package names after the ‘pkg
uninstall’ command.

   To minimize the amount of code duplication between packages it is
possible that one package depends on another one.  If a package depends
on another, it will check if that package is installed during
installation.  If it is not, an error will be reported and the package
will not be installed.  This behavior can be disabled by passing the
‘-nodeps’ flag to the ‘pkg install’ command

     pkg install -nodeps my_package_with_dependencies.tar.gz

Since the installed package expects its dependencies to be installed it
may not function correctly.  Because of this it is not recommended to
disable dependency checking.

 -- Command: pkg COMMAND PKG_NAME
 -- Command: pkg COMMAND OPTION PKG_NAME
     Manage packages (groups of add-on functions) for Octave.

     Different actions are available depending on the value of COMMAND.

     Available commands:

     ‘install’
          Install named packages.  For example,

               pkg install image-1.0.0.tar.gz

          installs the package found in the file ‘image-1.0.0.tar.gz’.

          The OPTION variable can contain options that affect the manner
          in which a package is installed.  These options can be one or
          more of

          ‘-nodeps’
               The package manager will disable dependency checking.
               With this option it is possible to install a package even
               when it depends on another package which is not installed
               on the system.  *Use this option with care.*

          ‘-noauto’
               The package manager will not automatically load the
               installed package when starting Octave.  This overrides
               any setting within the package.

          ‘-auto’
               The package manager will automatically load the installed
               package when starting Octave.  This overrides any setting
               within the package.

          ‘-local’
               A local installation (package available only to current
               user) is forced, even if the user has system privileges.

          ‘-global’
               A global installation (package available to all users) is
               forced, even if the user doesn’t normally have system
               privileges.

          ‘-forge’
               Install a package directly from the Octave-Forge
               repository.  This requires an internet connection and the
               cURL library.

          ‘-verbose’
               The package manager will print the output of all commands
               as they are performed.

     ‘update’
          Check installed Octave-Forge packages against repository and
          update any outdated items.  This requires an internet
          connection and the cURL library.  Usage:

               pkg update

     ‘uninstall’
          Uninstall named packages.  For example,

               pkg uninstall image

          removes the ‘image’ package from the system.  If another
          installed package depends on the ‘image’ package an error will
          be issued.  The package can be uninstalled anyway by using the
          ‘-nodeps’ option.

     ‘load’
          Add named packages to the path.  After loading a package it is
          possible to use the functions provided by the package.  For
          example,

               pkg load image

          adds the ‘image’ package to the path.  It is possible to load
          all installed packages at once with the keyword ‘all’.  Usage:

               pkg load all

     ‘unload’
          Remove named packages from the path.  After unloading a
          package it is no longer possible to use the functions provided
          by the package.  It is possible to unload all installed
          packages at once with the keyword ‘all’.  Usage:

               pkg unload all

     ‘list’
          Show the list of currently installed packages.  For example,

               pkg list

          will produce a short report with the package name, version,
          and installation directory for each installed package.  Supply
          a package name to limit reporting to a particular package.
          For example:

               pkg list image

          If a single return argument is requested then ‘pkg’ returns a
          cell array where each element is a structure with information
          on a single package.

               installed_packages = pkg ("list")

          If two output arguments are requested ‘pkg’ splits the list of
          installed packages into those which were installed by the
          current user, and those which were installed by the system
          administrator.

               [user_packages, system_packages] = pkg ("list")

          The "-forge" option lists packages available at the
          Octave-Forge repository.  This requires an internet connection
          and the cURL library.  For example:

               oct_forge_pkgs = pkg ("list", "-forge")

     ‘describe’
          Show a short description of the named installed packages, with
          the option "-verbose" also list functions provided by the
          package.  For example,

               pkg describe -verbose all

          will describe all installed packages and the functions they
          provide.  If one output is requested a cell of structure
          containing the description and list of functions of each
          package is returned as output rather than printed on screen:

               desc = pkg ("describe", "secs1d", "image")

          If any of the requested packages is not installed, ‘pkg’
          returns an error, unless a second output is requested:

               [desc, flag] = pkg ("describe", "secs1d", "image")

          FLAG will take one of the values "Not installed", "Loaded", or
          "Not loaded" for each of the named packages.

     ‘prefix’
          Set the installation prefix directory.  For example,

               pkg prefix ~/my_octave_packages

          sets the installation prefix to ‘~/my_octave_packages’.
          Packages will be installed in this directory.

          It is possible to get the current installation prefix by
          requesting an output argument.  For example:

               pfx = pkg ("prefix")

          The location in which to install the architecture dependent
          files can be independently specified with an addition
          argument.  For example:

               pkg prefix ~/my_octave_packages ~/my_arch_dep_pkgs

     ‘local_list’
          Set the file in which to look for information on locally
          installed packages.  Locally installed packages are those that
          are available only to the current user.  For example:

               pkg local_list ~/.octave_packages

          It is possible to get the current value of local_list with the
          following

               pkg local_list

     ‘global_list’
          Set the file in which to look for information on globally
          installed packages.  Globally installed packages are those
          that are available to all users.  For example:

               pkg global_list /usr/share/octave/octave_packages

          It is possible to get the current value of global_list with
          the following

               pkg global_list

     ‘build’
          Build a binary form of a package or packages.  The binary file
          produced will itself be an Octave package that can be
          installed normally with ‘pkg’.  The form of the command to
          build a binary package is

               pkg build builddir image-1.0.0.tar.gz ...

          where ‘builddir’ is the name of a directory where the
          temporary installation will be produced and the binary
          packages will be found.  The options ‘-verbose’ and ‘-nodeps’
          are respected, while all other options are ignored.

     ‘rebuild’
          Rebuild the package database from the installed directories.
          This can be used in cases where the package database has been
          corrupted.  It can also take the ‘-auto’ and ‘-noauto’ options
          to allow the autoloading state of a package to be changed.
          For example,

               pkg rebuild -noauto image

          will remove the autoloading status of the image package.

     See also: *note ver: XREFver, *note news: XREFnews.


File: octave.info,  Node: Using Packages,  Next: Administrating Packages,  Prev: Installing and Removing Packages,  Up: Packages

38.2 Using Packages
===================

By default installed packages are not available from the Octave prompt,
but it is possible to control this using the ‘pkg load’ and ‘pkg unload’
commands.  The functions from a package can be added to the Octave path
by typing

     pkg load package_name

where ‘package_name’ is the name of the package to be added to the path.

   In much the same way a package can be removed from the Octave path by
typing

     pkg unload package_name


File: octave.info,  Node: Administrating Packages,  Next: Creating Packages,  Prev: Using Packages,  Up: Packages

38.3 Administrating Packages
============================

On UNIX-like systems it is possible to make both per-user and
system-wide installations of a package.  If the user performing the
installation is ‘root’ the packages will be installed in a system-wide
directory that defaults to ‘OCTAVE_HOME/share/octave/packages/’.  If the
user is not ‘root’ the default installation directory is ‘~/octave/’.
Packages will be installed in a subdirectory of the installation
directory that will be named after the package.  It is possible to
change the installation directory by using the ‘pkg prefix’ command

     pkg prefix new_installation_directory

The current installation directory can be retrieved by typing

     current_installation_directory = pkg prefix

   To function properly the package manager needs to keep some
information about the installed packages.  For per-user packages this
information is by default stored in the file ‘~/.octave_packages’ and
for system-wide installations it is stored in
‘OCTAVE_HOME/share/octave/octave_packages’.  The path to the per-user
file can be changed with the ‘pkg local_list’ command

     pkg local_list /path/to/new_file

For system-wide installations this can be changed in the same way using
the ‘pkg global_list’ command.  If these commands are called without a
new path, the current path will be returned.


File: octave.info,  Node: Creating Packages,  Prev: Administrating Packages,  Up: Packages

38.4 Creating Packages
======================

Internally a package is simply a gzipped tar file that contains a top
level directory of any given name.  This directory will in the following
be referred to as ‘package’ and may contain the following files:

‘package/CITATION’
     This is am optional file describing instructions on how to cite the
     package for publication.  It will be displayed verbatim by the
     function ‘citation’.

‘package/COPYING’
     This is a required file containing the license of the package.  No
     restrictions is made on the license in general.  If however the
     package contains dynamically linked functions the license must be
     compatible with the GNU General Public License.

‘package/DESCRIPTION’
     This is a required file containing information about the package.
     *Note The DESCRIPTION File::, for details on this file.

‘package/ChangeLog’
     This is an optional file describing all the changes made to the
     package source files.

‘package/INDEX’
     This is an optional file describing the functions provided by the
     package.  If this file is not given then one with be created
     automatically from the functions in the package and the
     ‘Categories’ keyword in the ‘DESCRIPTION’ file.  *Note The INDEX
     File::, for details on this file.

‘package/NEWS’
     This is an optional file describing all user-visible changes worth
     mentioning.  As this file increases on size, old entries can be
     moved into ‘package/ONEWS’.

‘package/ONEWS’
     This is an optional file describing old entries from the ‘NEWS’
     file.

‘package/PKG_ADD’
     An optional file that includes commands that are run when the
     package is added to the users path.  Note that ‘PKG_ADD’ directives
     in the source code of the package will also be added to this file
     by the Octave package manager.  Note that symbolic links are to be
     avoided in packages, as symbolic links do not exist on some file
     systems, and so a typical use for this file is the replacement of
     the symbolic link

          ln -s foo.oct bar.oct

     with an autoload directive like

          autoload ('bar', which ('foo'));

     *Note PKG_ADD and PKG_DEL Directives::, for details on ‘PKG_ADD’
     directives.

‘package/PKG_DEL’
     An optional file that includes commands that are run when the
     package is removed from the users path.  Note that ‘PKG_DEL’
     directives in the source code of the package will also be added to
     this file by the Octave package manager.  *Note PKG_ADD and PKG_DEL
     Directives::, for details on ‘PKG_DEL’ directives.

‘package/pre_install.m’
     This is an optional function that is run prior to the installation
     of a package.  This function is called with a single argument, a
     struct with fields names after the data in the ‘DESCRIPTION’, and
     the paths where the package functions will be installed.

‘package/post_install.m’
     This is an optional function that is run after the installation of
     a package.  This function is called with a single argument, a
     struct with fields names after the data in the ‘DESCRIPTION’, and
     the paths where the package functions were installed.

‘package/on_uninstall.m’
     This is an optional function that is run prior to the removal of a
     package.  This function is called with a single argument, a struct
     with fields names after the data in the ‘DESCRIPTION’, the paths
     where the package functions are installed, and whether the package
     is currently loaded.

   Besides the above mentioned files, a package can also contain one or
more of the following directories:

‘package/inst’
     An optional directory containing any files that are directly
     installed by the package.  Typically this will include any
     ‘m’-files.

‘package/src’
     An optional directory containing code that must be built prior to
     the packages installation.  The Octave package manager will execute
     ‘./configure’ in this directory if this script exists, and will
     then call ‘make’ if a file ‘Makefile’ exists in this directory.
     ‘make install’ will however not be called.  The environment
     variables ‘MKOCTFILE’, ‘OCTAVE_CONFIG’, and ‘OCTAVE’ will be set to
     the full paths of the programs ‘mkoctfile’, ‘octave-config’, and
     ‘octave’, respectively, of the correct version when ‘configure’ and
     ‘make’ are called.  If a file called ‘FILES’ exists all files
     listed there will be copied to the ‘inst’ directory, so they also
     will be installed.  If the ‘FILES’ file doesn’t exist, ‘src/*.m’
     and ‘src/*.oct’ will be copied to the ‘inst’ directory.

‘package/doc’
     An optional directory containing documentation for the package.
     The files in this directory will be directly installed in a
     sub-directory of the installed package for future reference.

‘package/bin’
     An optional directory containing files that will be added to the
     Octave ‘EXEC_PATH’ when the package is loaded.  This might contain
     external scripts, etc., called by functions within the package.

* Menu:

* The DESCRIPTION File::
* The INDEX File::
* PKG_ADD and PKG_DEL Directives::
* Missing Components::


File: octave.info,  Node: The DESCRIPTION File,  Next: The INDEX File,  Up: Creating Packages

38.4.1 The DESCRIPTION File
---------------------------

The ‘DESCRIPTION’ file contains various information about the package,
such as its name, author, and version.  This file has a very simple
format

   • Lines starting with ‘#’ are comments.

   • Lines starting with a blank character are continuations from the
     previous line.

   • Everything else is of the form ‘NameOfOption: ValueOfOption’.

The following is a simple example of a ‘DESCRIPTION’ file

     Name: The name of my package
     Version: 1.0.0
     Date: 2007-18-04
     Author: The name (and possibly email) of the package author.
     Maintainer: The name (and possibly email) of the current
      package maintainer.
     Title: The title of the package
     Description: A short description of the package.  If this
      description gets too long for one line it can continue
      on the next by adding a space to the beginning of the
      following lines.
     License: GPLv3+

   The package manager currently recognizes the following keywords

‘Name’
     Name of the package.

‘Version’
     Version of the package.  A package version must be 3 numbers
     separated by dots.

‘Date’
     Date of last update.

‘Author’
     Original author of the package.

‘Maintainer’
     Maintainer of the package.

‘Title’
     A one line description of the package.

‘Description’
     A one paragraph description of the package.

‘Categories’
     Optional keyword describing the package (if no ‘INDEX’ file is
     given this is mandatory).

‘Problems’
     Optional list of known problems.

‘Url’
     Optional list of homepages related to the package.

‘Autoload’
     Optional field that sets the default loading behavior for the
     package.  If set to ‘yes’, ‘true’ or ‘on’, then Octave will
     automatically load the package when starting.  Otherwise the
     package must be manually loaded with the pkg load command.  This
     default behavior can be overridden when the package is installed.

‘Depends’
     A list of other Octave packages that this package depends on.  This
     can include dependencies on particular versions, with a format

          Depends: package (>= 1.0.0)

     Possible operators are ‘<’, ‘<=’, ‘==’, ‘>=’ or ‘>’.  If the part
     of the dependency in ‘()’ is missing, any version of the package is
     acceptable.  Multiple dependencies can be defined either as a comma
     separated list or on separate ‘Depends’ lines.

‘License’
     An optional short description of the used license (e.g., GPL
     version 3 or newer).  This is optional since the file ‘COPYING’ is
     mandatory.

‘SystemRequirements’
     These are the external install dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     ‘Depends’ keyword.

‘BuildRequires’
     These are the external build dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     ‘Depends’ keyword.  Note that in general, packaging systems such as
     ‘rpm’ or ‘deb’ and autoprobe the install dependencies from the
     build dependencies, and therefore the often a ‘BuildRequires’
     dependency removes the need for a ‘SystemRequirements’ dependency.

The developer is free to add additional arguments to the ‘DESCRIPTION’
file for their own purposes.  One further detail to aid the packager is
that the ‘SystemRequirements’ and ‘BuildRequires’ keywords can have a
distribution dependent section, and the automatic build process will use
these.  An example of the format of this is

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

where the first package name will be used as a default and if the RPMs
are built on a Mandriva distribution, then the second package name will
be used instead.


File: octave.info,  Node: The INDEX File,  Next: PKG_ADD and PKG_DEL Directives,  Prev: The DESCRIPTION File,  Up: Creating Packages

38.4.2 The INDEX File
---------------------

The optional ‘INDEX’ file provides a categorical view of the functions
in the package.  This file has a very simple format

   • Lines beginning with ‘#’ are comments.

   • The first non-comment line should look like this

          toolbox >> Toolbox name

   • Lines beginning with an alphabetical character indicates a new
     category of functions.

   • Lines starting with a white space character indicate that the
     function names on the line belong to the last mentioned category.

The format can be summarized with the following example:

     # A comment
     toolbox >> Toolbox name
     Category Name 1
      function1 function2 function3
      function4
     Category Name 2
      function2 function5

   If you wish to refer to a function that users might expect to find in
your package but is not there, providing a work around or pointing out
that the function is available elsewhere, you can use:

     fn = workaround description

This workaround description will not appear when listing functions in
the package with ‘pkg describe’ but they will be published in the HTML
documentation online.  Workaround descriptions can use any HTML markup,
but keep in mind that it will be enclosed in a bold-italic environment.
For the special case of:

     fn = use <code>alternate expression</code>

the bold-italic is automatically suppressed.  You will need to use
‘<code>’ even in references:

     fn = use <a href="someothersite.html"><code>fn</code></a>

Sometimes functions are only partially compatible, in which case you can
list the non-compatible cases separately.  To refer to another function
in the package, use ‘<f>fn</f>’.  For example:

     eig (a, b) = use <f>qz</f>

Since sites may have many missing functions, you can define a macro
rather than typing the same link over and again.

     $id = expansion

defines the macro id.  You can use ‘$id’ anywhere in the description and
it will be expanded.  For example:

     $TSA = see <a href="link_to_spctools">SPC Tools</a>
     arcov = $TSA <code>armcv</code>

id is any string of letters, numbers and ‘_’.


File: octave.info,  Node: PKG_ADD and PKG_DEL Directives,  Next: Missing Components,  Prev: The INDEX File,  Up: Creating Packages

38.4.3 PKG_ADD and PKG_DEL Directives
-------------------------------------

If the package contains files called ‘PKG_ADD’ or ‘PKG_DEL’ the commands
in these files will be executed when the package is added or removed
from the users path.  In some situations such files are a bit cumbersome
to maintain, so the package manager supports automatic creation of such
files.  If a source file in the package contains a ‘PKG_ADD’ or
‘PKG_DEL’ directive they will be added to either the ‘PKG_ADD’ or
‘PKG_DEL’ files.

   In ‘m’-files a ‘PKG_ADD’ directive looks like this

     ## PKG_ADD: some_octave_command

Such lines should be added before the ‘function’ keyword.  In C++ files
a ‘PKG_ADD’ directive looks like this

     // PKG_ADD: some_octave_command

In both cases ‘some_octave_command’ should be replaced by the command
that should be placed in the ‘PKG_ADD’ file. ‘PKG_DEL’ directives work
in the same way, except the ‘PKG_ADD’ keyword is replaced with ‘PKG_DEL’
and the commands get added to the ‘PKG_DEL’ file.


File: octave.info,  Node: Missing Components,  Prev: PKG_ADD and PKG_DEL Directives,  Up: Creating Packages

38.4.4 Missing Components
-------------------------

If a package relies on a component, such as another Octave package, that
may not be present it may be useful to install a function which informs
users what to do when a particular component is missing.  The function
must be written by the package maintainer and registered with Octave
using ‘missing_component_hook’.

 -- Built-in Function: VAL = missing_component_hook ()
 -- Built-in Function: OLD_VAL = missing_component_hook (NEW_VAL)
 -- Built-in Function: missing_component_hook (NEW_VAL, "local")
     Query or set the internal variable that specifies the function to
     call when a component of Octave is missing.

     This can be useful for packagers that may split the Octave
     installation into multiple sub-packages, for example, to provide a
     hint to users for how to install the missing components.

     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.

     The hook function is expected to be of the form

          FCN (COMPONENT)

     Octave will call FCN with the name of the function that requires
     the component and a string describing the missing component.  The
     hook function should return an error message to be displayed.

     See also: *note missing_function_hook: XREFmissing_function_hook.


File: octave.info,  Node: External Code Interface,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A External Code Interface
**********************************

"The sum of human wisdom is not contained in any one language" —Ezra
Pound

   Octave is a fantastic language for solving many problems in science
and engineering.  However, it is not the only computer language and
there are times when you may want to use code written in other
languages.  Good reasons for doing so include: 1) not re-inventing the
wheel; existing function libraries which have been thoroughly tested and
debugged or large scale simulation codebases are a good example, 2)
accessing unique capabilities of a different language; for example the
well-known regular expression functions of Perl (but don’t do that
because ‘regexp’ already exists in Octave).

   Performance should generally *not* be a reason for using compiled
extensions.  Although compiled extensions can run faster, particularly
if they replace a loop in Octave code, this is almost never the best
path to take.  First, there are many techniques to speed up Octave
performance while remaining within the language.  Second, Octave is a
high-level language that makes it easy to perform common mathematical
tasks.  Giving that up means shifting the focus from solving the real
problem to solving a computer programming problem.  It means returning
to low-level constructs such as pointers, memory management,
mathematical overflow/underflow, etc.  Because of the low level nature,
and the fact that the compiled code is executed outside of Octave, there
is the very real possibility of crashing the interpreter and losing
work.

   Before going further, you should first determine if you really need
to bother writing code outside of Octave.

   • Can I get the same functionality using the Octave scripting
     language alone?

     Even when a function already exists outside the language, it may be
     better to simply reproduce the behavior in an m-file rather than
     attempt to interface to the outside code.

   • Is the code thoroughly optimized for Octave?

     If performance is an issue you should always start with the
     in-language techniques for getting better performance.  Chief among
     these is vectorization (*note Vectorization and Faster Code
     Execution::) which not only makes the code concise and more
     understandable but improves performance (10X-100X). If loops must
     be used, make sure that the allocation of space for variables takes
     place outside the loops using an assignment to a matrix of the
     right size, or zeros.

   • Does the code make as much use as possible of existing built-in
     library routines?

     These routines are highly optimized and many do not carry the
     overhead of being interpreted.

   • Does writing a dynamically linked function represent a useful
     investment of your time, relative to staying in Octave?

     It will take time to learn Octave’s interface for external code and
     there will inevitably be issues with tools such as compilers.

   With that said, Octave offers a versatile interface for including
chunks of compiled code as dynamically linked extensions.  These
dynamically linked functions can be called from the interpreter in the
same manner as any ordinary function.  The interface is bi-directional
and external code can call Octave functions (like ‘plot’) which
otherwise might be very difficult to develop.

   The interface is centered around supporting the languages C++, C, and
Fortran.  Octave itself is written in C++ and can call external C++/C
code through its native oct-file interface.  The C language is also
supported through the mex-file interface for compatibility with MATLAB.
Fortran code is easiest to reach through the oct-file interface.

   Because many other languages provide C or C++ APIs it is relatively
simple to build bridges between Octave and other languages.  This is
also a way to bridge to hardware resources which often have device
drivers written in C.

* Menu:

* Oct-Files::
* Mex-Files::
* Standalone Programs::


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: External Code Interface

A.1 Oct-Files
=============

* Menu:

* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Test of Oct-Files::


File: octave.info,  Node: Getting Started with Oct-Files,  Next: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.1 Getting Started with Oct-Files
------------------------------------

Oct-files are pieces of C++ code that have been compiled with the Octave
API into a dynamically loadable object.  They take their name from the
file which contains the object which has the extension ‘.oct’.

   Finding a C++ compiler, using the correct switches, adding the right
include paths for header files, etc.  is a difficult task.  Octave
automates this by providing the ‘mkoctfile’ command with which to build
oct-files.  The command is available from within Octave or at the shell
command line.

 -- Command: mkoctfile [-options] file ...
 -- Function File: [OUTPUT, STATUS] = mkoctfile (...)

     The ‘mkoctfile’ function compiles source code written in C, C++, or
     Fortran.  Depending on the options used with ‘mkoctfile’, the
     compiled code can be called within Octave or can be used as a
     stand-alone application.

     ‘mkoctfile’ can be called from the shell prompt or from the Octave
     prompt.  Calling it from the Octave prompt simply delegates the
     call to the shell prompt.  The output is stored in the OUTPUT
     variable and the exit status in the STATUS variable.

     ‘mkoctfile’ accepts the following options, all of which are
     optional except for the file name of the code you wish to compile:

     ‘-I DIR’
          Add the include directory DIR to compile commands.

     ‘-D DEF’
          Add the definition DEF to the compiler call.

     ‘-l LIB’
          Add the library LIB to the link command.

     ‘-L DIR’
          Add the library directory DIR to the link command.

     ‘-M’
     ‘--depend’
          Generate dependency files (.d) for C and C++ source files.

     ‘-R DIR’
          Add the run-time path to the link command.

     ‘-Wl,...’
          Pass flags though the linker like "-Wl,-rpath=...".  The
          quotes are needed since commas are interpreted as command
          separators.

     ‘-W...’
          Pass flags though the compiler like "-Wa,OPTION".

     ‘-c’
          Compile but do not link.

     ‘-g’
          Enable debugging options for compilers.

     ‘-o FILE’
     ‘--output FILE’
          Output file name.  Default extension is .oct (or .mex if
          ‘--mex’ is specified) unless linking a stand-alone executable.

     ‘-p VAR’
     ‘--print VAR’
          Print the configuration variable VAR.  Recognized variables
          are:

                  ALL_CFLAGS                  INCFLAGS
                  ALL_CXXFLAGS                INCLUDEDIR
                  ALL_FFLAGS                  LAPACK_LIBS
                  ALL_LDFLAGS                 LD_CXX
                  AR                          LDFLAGS
                  BLAS_LIBS                   LD_STATIC_FLAG
                  CC                          LFLAGS
                  CFLAGS                      LIBDIR
                  CPICFLAG                    LIBOCTAVE
                  CPPFLAGS                    LIBOCTINTERP
                  CXX                         LIBS
                  CXXFLAGS                    OCTAVE_HOME
                  CXXPICFLAG                  OCTAVE_LIBS
                  DEPEND_EXTRA_SED_PATTERN    OCTAVE_LINK_DEPS
                  DEPEND_FLAGS                OCTAVE_LINK_OPTS
                  DL_LD                       OCTAVE_PREFIX
                  DL_LDFLAGS                  OCTINCLUDEDIR
                  F77                         OCTLIBDIR
                  F77_INTEGER8_FLAG           OCT_LINK_DEPS
                  FFLAGS                      OCT_LINK_OPTS
                  FFTW3F_LDFLAGS              RANLIB
                  FFTW3F_LIBS                 RDYNAMIC_FLAG
                  FFTW3_LDFLAGS               READLINE_LIBS
                  FFTW3_LIBS                  SED
                  FFTW_LIBS                   SPECIAL_MATH_LIB
                  FLIBS                       XTRA_CFLAGS
                  FPICFLAG                    XTRA_CXXFLAGS

     ‘--link-stand-alone’
          Link a stand-alone executable file.

     ‘--mex’
          Assume we are creating a MEX file.  Set the default output
          extension to ".mex".

     ‘-s’
     ‘--strip’
          Strip the output file.

     ‘-v’
     ‘--verbose’
          Echo commands as they are executed.

     ‘file’
          The file to compile or link.  Recognized file types are

                  .c    C source
                  .cc   C++ source
                  .C    C++ source
                  .cpp  C++ source
                  .f    Fortran source (fixed form)
                  .F    Fortran source (fixed form)
                  .f90  Fortran source (free form)
                  .F90  Fortran source (free form)
                  .o    object file
                  .a    library file

   Consider the following short example which introduces the basics of
writing a C++ function that can be linked to Octave.

     #include <octave/oct.h>

     DEFUN_DLD (helloworld, args, nargout,
                "Hello World Help String")
     {
       int nargin = args.length ();

       octave_stdout << "Hello World has "
                     << nargin << " input arguments and "
                     << nargout << " output arguments.\n";

       return octave_value_list ();
     }


   The first critical line is ‘#include <octave/oct.h>’ which makes
available most of the definitions necessary for a C++ oct-file.  Note
that ‘octave/oct.h’ is a C++ header and cannot be directly ‘#include’’ed
in a C source file, nor any other language.

   Included by ‘oct.h’ is a definition for the macro ‘DEFUN_DLD’ which
creates a dynamically loaded function.  This macro takes four arguments:

  1. The function name as it will be seen in Octave,

  2. The list of arguments to the function of type ‘octave_value_list’,

  3. The number of output arguments, which can and often is omitted if
     not used, and

  4. The string to use for the help text of the function.

   The return type of functions defined with ‘DEFUN_DLD’ is always
‘octave_value_list’.

   There are a couple of important considerations in the choice of
function name.  First, it must be a valid Octave function name and so
must be a sequence of letters, digits, and underscores not starting with
a digit.  Second, as Octave uses the function name to define the
filename it attempts to find the function in, the function name in the
‘DEFUN_DLD’ macro must match the filename of the oct-file.  Therefore,
the above function should be in a file ‘helloworld.cc’, and would be
compiled to an oct-file using the command

     mkoctfile helloworld.cc

   This will create a file called ‘helloworld.oct’ that is the compiled
version of the function.  It should be noted that it is perfectly
acceptable to have more than one ‘DEFUN_DLD’ function in a source file.
However, there must either be a symbolic link to the oct-file for each
of the functions defined in the source code with the ‘DEFUN_DLD’ macro
or the ‘autoload’ (*note Function Files::) function should be used.

   The rest of the function shows how to find the number of input
arguments, how to print through the Octave pager, and return from the
function.  After compiling this function as above, an example of its use
is

     helloworld (1, 2, 3)
     ⊣ Hello World has 3 input arguments and 0 output arguments.

   Subsequent sections show how to use specific classes from Octave’s
core internals.  Base classes like dMatrix (a matrix of double values)
are found in the directory ‘liboctave/array’.  The definitive reference
for how to use a particular class is the header file itself.  However,
it is often enough just to study the examples in the manual in order to
be able to use the class.


File: octave.info,  Node: Matrices and Arrays in Oct-Files,  Next: Character Strings in Oct-Files,  Prev: Getting Started with Oct-Files,  Up: Oct-Files

A.1.2 Matrices and Arrays in Oct-Files
--------------------------------------

Octave supports a number of different array and matrix classes, the
majority of which are based on the Array class.  The exception is the
sparse matrix types discussed separately below.  There are three basic
matrix types

‘Matrix’
     A double precision matrix class defined in ‘dMatrix.h’,

‘ComplexMatrix’
     A complex matrix class defined in ‘CMatrix.h’, and

‘BoolMatrix’
     A boolean matrix class defined in ‘boolMatrix.h’.

   These are the basic two-dimensional matrix types of Octave.  In
addition there are a number of multi-dimensional array types including

‘NDArray’
     A double precision array class defined in ‘dNDArray.h’

‘ComplexNDarray’
     A complex array class defined in ‘CNDArray.h’

‘boolNDArray’
     A boolean array class defined in ‘boolNDArray.h’

‘int8NDArray’
‘int16NDArray’
‘int32NDArray’
‘int64NDArray’
     8, 16, 32, and 64-bit signed array classes defined in
     ‘int8NDArray.h’, ‘int16NDArray.h’, etc.

‘uint8NDArray’
‘uint16NDArray’
‘uint32NDArray’
‘uint64NDArray’
     8, 16, 32, and 64-bit unsigned array classes defined in
     ‘uint8NDArray.h’, ‘uint16NDArray.h’, etc.

   There are several basic ways of constructing matrices or
multi-dimensional arrays.  Using the class ‘Matrix’ as an example one
can

   • Create an empty matrix or array with the empty constructor.  For
     example:

          Matrix a;

     This can be used for all matrix and array types.

   • Define the dimensions of the matrix or array with a dim_vector
     which has the same characteristics as the vector returned from
     ‘size’.  For example:

          dim_vector dv (2, 3);  // 2 rows, 3 columns
          Matrix a (dv);

     This can be used on all matrix and array types.

   • Define the number of rows and columns in the matrix.  For example:

          Matrix a (2, 2)

     However, this constructor can only be used with matrix types.

   These types all share a number of basic methods and operators.  Many
bear a resemblance to functions that exist in the interpreter.  A
selection of useful methods include

 -- Method: T& operator () (octave_idx_type)
 -- Method: T& elem (octave_idx_type)
     The ‘()’ operator or ‘elem’ method allow the values of the matrix
     or array to be read or set.  These can take a single argument,
     which is of type ‘octave_idx_type’, that is the index into the
     matrix or array.  Additionally, the matrix type allows two argument
     versions of the ‘()’ operator and elem method, giving the row and
     column index of the value to obtain or set.

   Note that these functions do significant error checking and so in
some circumstances the user might prefer to access the data of the array
or matrix directly through the fortran_vec method discussed below.

 -- Method: octave_idx_type numel (void) const
     The total number of elements in the matrix or array.

 -- Method: size_t byte_size (void) const
     The number of bytes used to store the matrix or array.

 -- Method: dim_vector dims (void) const
     The dimensions of the matrix or array in value of type dim_vector.

 -- Method: int ndims (void) const
     The number of dimensions of the matrix or array.  Matrices are 2-D,
     but arrays can be N-dimensional.

 -- Method: void resize (const dim_vector&)
     A method taking either an argument of type ‘dim_vector’, or in the
     case of a matrix two arguments of type ‘octave_idx_type’ defining
     the number of rows and columns in the matrix.

 -- Method: T* fortran_vec (void)
     This method returns a pointer to the underlying data of the matrix
     or array so that it can be manipulated directly, either within
     Octave or by an external library.

   Operators such an ‘+’, ‘-’, or ‘*’ can be used on the majority of the
matrix and array types.  In addition there are a number of methods that
are of interest only for matrices such as ‘transpose’, ‘hermitian’,
‘solve’, etc.

   The typical way to extract a matrix or array from the input arguments
of ‘DEFUN_DLD’ function is as follows

     #include <octave/oct.h>

     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       int nargin = args.length ();

       if (nargin != 2)
         print_usage ();
       else
         {
           NDArray A = args(0).array_value ();
           NDArray B = args(1).array_value ();
           if (! error_state)
             return octave_value (A + B);
         }

       return octave_value_list ();
     }


   To avoid segmentation faults causing Octave to abort this function
explicitly checks that there are sufficient arguments available before
accessing these arguments.  It then obtains two multi-dimensional arrays
of type ‘NDArray’ and adds these together.  Note that the array_value
method is called without using the ‘is_matrix_type’ type, and instead
the error_state is checked before returning ‘A + B’.  The reason to
prefer this is that the arguments might be a type that is not an
‘NDArray’, but it would make sense to convert it to one.  The
‘array_value’ method allows this conversion to be performed
transparently if possible, and sets ‘error_state’ if it is not.

   ‘A + B’, operating on two ‘NDArray’’s returns an ‘NDArray’, which is
cast to an ‘octave_value’ on the return from the function.  An example
of the use of this demonstration function is

     addtwomatrices (ones (2, 2), eye (2, 2))
           ⇒  2  1
               1  2

   A list of the basic ‘Matrix’ and ‘Array’ types, the methods to
extract these from an ‘octave_value’, and the associated header file is
listed below.

Type                   Function                      Source Code
----------------------------------------------------------------------------
‘RowVector’            ‘row_vector_value’            ‘dRowVector.h’
‘ComplexRowVector’     ‘complex_row_vector_value’    ‘CRowVector.h’
‘ColumnVector’         ‘column_vector_value’         ‘dColVector.h’
‘ComplexColumnVector’  ‘complex_column_vector_value’ ‘CColVector.h’
‘Matrix’               ‘matrix_value’                ‘dMatrix.h’
‘ComplexMatrix’        ‘complex_matrix_value’        ‘CMatrix.h’
‘boolMatrix’           ‘bool_matrix_value’           ‘boolMatrix.h’
‘charMatrix’           ‘char_matrix_value’           ‘chMatrix.h’
‘NDArray’              ‘array_value’                 ‘dNDArray.h’
‘ComplexNDArray’       ‘complex_array_value’         ‘CNDArray.h’
‘boolNDArray’          ‘bool_array_value’            ‘boolNDArray.h’
‘charNDArray’          ‘char_array_value’            ‘charNDArray.h’
‘int8NDArray’          ‘int8_array_value’            ‘int8NDArray.h’
‘int16NDArray’         ‘int16_array_value’           ‘int16NDArray.h’
‘int32NDArray’         ‘int32_array_value’           ‘int32NDArray.h’
‘int64NDArray’         ‘int64_array_value’           ‘int64NDArray.h’
‘uint8NDArray’         ‘uint8_array_value’           ‘uint8NDArray.h’
‘uint16NDArray’        ‘uint16_array_value’          ‘uint16NDArray.h’
‘uint32NDArray’        ‘uint32_array_value’          ‘uint32NDArray.h’
‘uint64NDArray’        ‘uint64_array_value’          ‘uint64NDArray.h’


File: octave.info,  Node: Character Strings in Oct-Files,  Next: Cell Arrays in Oct-Files,  Prev: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.3 Character Strings in Oct-Files
------------------------------------

A character string in Octave is just a special ‘Array’ class.  Consider
the example:

     #include <octave/oct.h>

     DEFUN_DLD (stringdemo, args, , "String Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           charMatrix ch = args(0).char_matrix_value ();

           if (! error_state)
             {
               retval(1) = octave_value (ch, '\'');  // Single Quote String

               octave_idx_type nr = ch.rows ();
               for (octave_idx_type i = 0; i < nr / 2; i++)
                 {
                   std::string tmp = ch.row_as_string (i);
                   ch.insert (ch.row_as_string (nr-i-1).c_str (), i, 0);
                   ch.insert (tmp.c_str (), nr-i-1, 0);
                 }
               retval(0) = octave_value (ch, '"');  // Double Quote String
             }
         }
       return retval;
     }


   An example of the use of this function is

     s0 = ["First String"; "Second String"];
     [s1,s2] = stringdemo (s0)
     ⇒ s1 = Second String
             First String

     ⇒ s2 = First String
             Second String

     typeinfo (s2)
     ⇒ sq_string
     typeinfo (s1)
     ⇒ string

   One additional complication of strings in Octave is the difference
between single quoted and double quoted strings.  To find out if an
‘octave_value’ contains a single or double quoted string use one of the
predicate tests shown below.

     if (args(0).is_sq_string ())
       octave_stdout << "First argument is a single quoted string\n";
     else if (args(0).is_dq_string ())
       octave_stdout << "First argument is a double quoted string\n";

   Note, however, that both types of strings are represented by the
‘charNDArray’ type, and so when assigning to an ‘octave_value’, the type
of string should be specified.  For example:

     octave_value_list retval;
     charNDArray ch;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch);        // default constructor is sq_string
                OR
     retval(1) = octave_value (ch, '\'');  // explicitly create sq_string

     // Create a double quoted string
     retval(0) = octave_value (ch, '"');


File: octave.info,  Node: Cell Arrays in Oct-Files,  Next: Structures in Oct-Files,  Prev: Character Strings in Oct-Files,  Up: Oct-Files

A.1.4 Cell Arrays in Oct-Files
------------------------------

Octave’s cell type is also available from within oct-files.  A cell
array is just an array of ‘octave_value’s, and thus each element of the
cell array can be treated just like any other ‘octave_value’.  A simple
example is

     #include <octave/oct.h>
     #include <octave/Cell.h>

     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           Cell c = args(0).cell_value ();
           if (! error_state)
             for (octave_idx_type i = 0; i < c.numel (); i++)
               {
                 retval(i) = c(i);          // using operator syntax
                 //retval(i) = c.elem (i);  // using method syntax
               }
         }

       return retval;
     }


   Note that cell arrays are used less often in standard oct-files and
so the ‘Cell.h’ header file must be explicitly included.  The rest of
the example extracts the ‘octave_value’s one by one from the cell array
and returns them as individual return arguments.  For example:

     [b1, b2, b3] = celldemo ({1, [1, 2], "test"})
     ⇒
     b1 =  1
     b2 =

        1   2

     b3 = test


File: octave.info,  Node: Structures in Oct-Files,  Next: Sparse Matrices in Oct-Files,  Prev: Cell Arrays in Oct-Files,  Up: Oct-Files

A.1.5 Structures in Oct-Files
-----------------------------

A structure in Octave is a map between a number of fields represented
and their values.  The Standard Template Library ‘map’ class is used,
with the pair consisting of a ‘std::string’ and an Octave ‘Cell’
variable.

   A simple example demonstrating the use of structures within oct-files
is

     #include <octave/oct.h>
     #include <octave/ov-struct.h>

     DEFUN_DLD (structdemo, args, , "Struct Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (args.length () == 2)
         {
           octave_scalar_map arg0 = args(0).scalar_map_value ();
           //octave_map arg0 = args(0).map_value ();

           if (! error_state)
             {
               std::string arg1 = args(1).string_value ();

               if (! error_state)
                 {
                   octave_value tmp = arg0.contents (arg1);
                   //octave_value tmp = arg0.contents (arg1)(0);

                   if (tmp.is_defined ())
                     {
                       octave_scalar_map st;

                       st.assign ("selected", tmp);

                       retval = octave_value (st);
                     }
                   else
                     error ("structdemo: struct does not have a field named '%s'\n",
                            arg1.c_str ());
                 }
               else
                 error ("structdemo: ARG2 must be a character string");
             }
           else
             error ("structdemo: ARG1 must be a struct");
         }
       else
         print_usage ();

       return retval;
     }


   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     ⇒ selected = test

   The example above specifically uses the ‘octave_scalar_map’ class
which is for representing a single struct.  For structure arrays the
‘octave_map’ class is used instead.  The commented code shows how the
demo could be modified to handle a structure array.  In that case the
‘contents’ method returns a ‘Cell’ which may have more than one element.
Therefore, to obtain the underlying ‘octave_value’ in this single-struct
example we write

     octave_value tmp = arg0.contents (arg1)(0);

where the trailing (0) is the () operator on the ‘Cell’ object.  If this
were a true structure array with multiple elements we could iterate over
the elements using the () operator.

   Structures are a relatively complex data container and there are more
functions available in ‘oct-map.h’ which make coding with them easier
than relying on just ‘contents’.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

‘SparseMatrix’
     A double precision sparse matrix class

‘SparseComplexMatrix’
     A complex sparse matrix class

‘SparseBoolMatrix’
     A boolean sparse matrix class

   All of these classes inherit from the ‘Sparse<T>’ template class, and
so all have similar capabilities and usage.  The ‘Sparse<T>’ class was
based on Octave’s ‘Array<T>’ class, and so users familiar with Octave’s
‘Array’ classes will be comfortable with the use of the sparse classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing ‘Array’ classes.  However,
there are a few differences due the different nature of sparse objects,
and these will be described.  First, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse classes
do not allow them at this time; All instances of the sparse classes must
be 2-dimensional.  This means that ‘SparseMatrix’ is actually more
similar to Octave’s ‘Matrix’ class than its ‘NDArray’ class.

* Menu:

* Array and Sparse Class Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Class Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 Array and Sparse Class Differences
..........................................

The number of elements in a sparse matrix is considered to be the number
of nonzero elements rather than the product of the dimensions.
Therefore

     SparseMatrix sm;
     ...
     int nel = sm.nelem ();

returns the number of nonzero elements.  If the user really requires the
number of elements in the matrix, including the nonzero elements, they
should use ‘numel’ rather than ‘nelem’.  Note that for very large
matrices, where the product of the two dimensions is larger than the
representation of an unsigned int, then ‘numel’ can overflow.  An
example is ‘speye (1e6)’ which will create a matrix with a million rows
and columns, but only a million nonzero elements.  Therefore the number
of rows by the number of columns in this case is more than two hundred
times the maximum value that can be represented by an unsigned int.  The
use of ‘numel’ should therefore be avoided useless it is known it won’t
overflow.

   Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function.  The reason is that if a
sparse object is non-const, then Octave will assume that a request for a
zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore a piece of code like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j) << std::endl;

is a great way of turning the sparse matrix into a dense one, and a very
slow way at that since it reallocates the sparse object at each zero
element in the matrix.

   An easy way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix.  So this is not a costly operation.  For example, the
above would become

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j) << std::endl;

   Finally, as the sparse types aren’t represented by a contiguous block
of memory, the ‘fortran_vec’ method of the ‘Array<T>’ is not available.
It is, however, replaced by three separate methods ‘ridx’, ‘cidx’ and
‘data’, that access the raw compressed column format that Octave sparse
matrices are stored in.  These methods can be used in a manner similar
to ‘elem’ to allow the matrix to be accessed or filled.  However, in
that case it is up to the user to respect the sparse matrix compressed
column format.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Class Differences,  Up: Sparse Matrices in Oct-Files

A.1.6.2 Creating Sparse Matrices in Oct-Files
.............................................

There are several useful alternatives for creating a sparse matrix.  The
first is to create three vectors representing the row index, column
index, and data values, and from these create the matrix.  The second
alternative is to create a sparse matrix with the appropriate amount of
space and then fill in the values.  Both techniques have their
advantages and disadvantages.

   Below is an example of creating a small sparse matrix using the first
technique

     int nz, nr, nc;
     nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 1; cidx(0) = 1; data(0) = 1;
     ridx(1) = 2; cidx(1) = 2; data(1) = 2;
     ridx(2) = 2; cidx(2) = 4; data(2) = 3;
     ridx(3) = 3; cidx(3) = 4; data(3) = 4;
     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *note Storage of Sparse
Matrices::.  Note that the compressed matrix format is not used at the
time of the creation of the matrix itself, but is used internally.

   As discussed in the chapter on Sparse Matrices, the values of the
sparse matrix are stored in increasing column-major ordering.  Although
the data passed by the user need not respect this requirement,
pre-sorting the data will significantly speed up creation of the sparse
matrix.

   The disadvantage of this technique for creating a sparse matrix is
that there is a brief time when two copies of the data exist.  For
extremely memory constrained problems this may not be the best technique
for creating a sparse matrix.

   The alternative is to first create a sparse matrix with the desired
number of nonzero elements and then later fill those elements in.
Sample code:

     int nz, nr, nc;
     nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, nz);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

   This creates the same matrix as previously.  Again, although not
strictly necessary, it is significantly faster if the sparse matrix is
created and the elements are added in column-major ordering.  The reason
for this is that when elements are inserted at the end of the current
list of known elements then no element in the matrix needs to be moved
to allow the new element to be inserted; Only the column indexes need to
be updated.

   There are a few further points to note about this method of creating
a sparse matrix.  First, it is possible to create a sparse matrix with
fewer elements than are actually inserted in the matrix.  Therefore,

     int nr, nc;
     nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, 0);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

is perfectly valid.  However, it is a very bad idea because as each new
element is added to the sparse matrix the matrix needs to request more
space and reallocate memory.  This is an expensive operation, that will
significantly slow this means of creating a sparse matrix.  Furthermore,
it is possible to create a sparse matrix with too much storage, so
having NZ greater than 4 is also valid.  The disadvantage is that the
matrix occupies more memory than strictly needed.

   It is not always possible to know the number of nonzero elements
prior to filling a matrix.  For this reason the additional unused
storage of a sparse matrix can be removed after its creation with the
‘maybe_compress’ function.  In addition, ‘maybe_compress’ can deallocate
the unused storage, but it can also remove zero elements from the
matrix.  The removal of zero elements from the matrix is controlled by
setting the argument of the ‘maybe_compress’ function to be ‘true’.
However, the cost of removing the zeros is high because it implies
re-sorting the elements.  If possible, it is better if the user does not
add the unnecessary zeros in the first place.  An example of the use of
‘maybe_compress’ is

     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;

     SparseMatrix sm1 (nr, nc, nz);
     sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
     sm1.maybe_compress ();  // No zero elements were added

     SparseMatrix sm2 (nr, nc, nz);
     sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
     sm1(1,3) = 3; sm1(2,3) = 4;
     sm2.maybe_compress (true);  // Zero elements were added

   The use of the ‘maybe_compress’ function should be avoided if
possible as it will slow the creation of the matrix.

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this technique might
be

     octave_value arg;
     ...
     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a priori the final # of nz.

which is probably the most efficient means of creating a sparse matrix.

   Finally, it might sometimes arise that the amount of storage
initially created is insufficient to completely store the sparse matrix.
Therefore, the method ‘change_capacity’ exists to reallocate the sparse
memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_mutate ();  // If don't know a priori the final # of nz.

   Note that both increasing and decreasing the number of nonzero
elements in a sparse matrix is expensive as it involves memory
reallocation.  Also as parts of the matrix, though not its entirety,
exist as old and new copies at the same time, additional memory is
needed.  Therefore, if possible this should be avoided.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.3 Using Sparse Matrices in Oct-Files
..........................................

Most of the same operators and functions on sparse matrices that are
available from the Octave command line are also available within
oct-files.  The basic means of extracting a sparse matrix from an
‘octave_value’ and returning it as an ‘octave_value’, can be seen in the
following example.

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm =
         args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an ‘octave_value’ is handled by the sparse
‘octave_value’ constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can be accessed within oct-files by using the support
functions ‘get_global_value’ and ‘set_global_value’.  ‘get_global_value’
takes two arguments, the first is a string representing the variable
name to obtain.  The second argument is a boolean argument specifying
what to do if no global variable of the desired name is found.  An
example of the use of these two functions is

     #include <octave/oct.h>

     DEFUN_DLD (globaldemo, args, , "Global Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           std::string s = args(0).string_value ();
           if (! error_state)
             {
               octave_value tmp = get_global_value (s, true);
               if (tmp.is_defined ())
                 retval = tmp;
               else
                 retval = "Global variable not found";

               set_global_value ("a", 42.0);
             }
         }
       return retval;
     }


   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     ⇒ 10
     globaldemo ("c")
     ⇒ "Global variable not found"
     num2str (a)
     ⇒ 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another Octave function from
within an oct-file, and there are many examples of such within Octave
itself.  For example, the ‘quad’ function is an oct-file that calculates
the definite integral by quadrature over a user supplied function.

   There are also many ways in which a function might be passed.  It
might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. Inline Function

  4. String

   The example below demonstrates an example that accepts all four means
of passing a function to an oct-file.

     #include <octave/oct.h>
     #include <octave/parse.h>

     DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin < 2)
         print_usage ();
       else
         {
           octave_value_list newargs;
           for (octave_idx_type i = nargin - 1; i > 0; i--)
             newargs(i-1) = args(i);
           if (args(0).is_function_handle () || args(0).is_inline_function ())
             {
               octave_function *fcn = args(0).function_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else if (args(0).is_string ())
             {
               std::string fcn = args(0).string_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else
             error ("funcdemo: INPUT must be string, inline, or function handle");
         }
       return retval;
     }


   The first argument to this demonstration is the user-supplied
function and the remaining arguments are all passed to the user
function.

     funcdemo (@sin,1)
     ⇒ 0.84147
     funcdemo (@(x) sin (x), 1)
     ⇒ 0.84147
     funcdemo (inline ("sin (x)"), 1)
     ⇒ 0.84147
     funcdemo ("sin",1)
     ⇒ 0.84147
     funcdemo (@atan2, 1, 1)
     ⇒ 0.78540

   When the user function is passed as a string the treatment of the
function is different.  In some cases it is necessary to have the user
supplied function as an ‘octave_function’ object.  In that case the
string argument can be used to create a temporary function as
demonstrated below.

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fcode = "function y = ";
     fcode.append (fcn_name);
     fcode.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fcode, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  First, the
number of input arguments to the user function is fixed, and in the
above example is a single argument.  Second, to avoid leaving the
temporary function in the Octave symbol table it should be cleared after
use.  Also, by convention internal function names begin and end with the
character sequence ‘__’.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
that the declarations of the external C functions may need to be
explicitly defined as C functions to the compiler.  If the declarations
of the external C functions are in the header ‘foo.h’, then the tactic
to ensure that the C++ compiler treats these declarations as C code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code, however, can pose more difficulties.  This is
due to differences in the manner in which compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies a number of macros
that allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the ‘XSTOPX’ function to
replace the Fortran ‘STOP’ function.  ‘XSTOPX’ uses the Octave exception
handler to treat failing cases in the Fortran code explicitly.  Note
that Octave supplies its own replacement BLAS ‘XERBLA’ function, which
uses ‘XSTOPX’.

   If the code calls ‘XSTOPX’, then the ‘F77_XFCN’ macro should be used
to call the underlying Fortran function.  The Fortran exception state
can then be checked with the global variable
‘f77_exception_encountered’.  If ‘XSTOPX’ will not be called, then the
‘F77_FCN’ macro should be used instead to call the Fortran code.

   There is no great harm in using ‘F77_XFCN’ in all cases, except that
for Fortran code that is short running and executes a large number of
times, there is potentially an overhead in doing so.  However, if
‘F77_FCN’ is used with code that calls ‘XSTOP’, Octave can generate a
segmentation fault.

   An example of the inclusion of a Fortran function in an oct-file is
given in the following example, where the C++ wrapper is

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortransub, FORTSUB)
         (const int&, double*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           if (! error_state)
             {
               double *av = a.fortran_vec ();
               octave_idx_type na = a.numel ();
               OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

               F77_XFCN (fortransub, FORTSUB,
                         (na, av, ctmp F77_CHAR_ARG_LEN (128)));

               retval(1) = std::string (ctmp);
               retval(0) = a;
             }
         }
       return retval;
     }


and the Fortran function is

           subroutine fortransub (n, a, s)
           implicit none
           character*(*) s
           real*8 a(*)
           integer*4 i, n, ioerr
           do i = 1, n
             if (a(i) .eq. 0d0) then
               call xstopx ('fortransub: divide by zero')
             else
               a(i) = 1d0 / a(i)
             endif
           enddo
           write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
          $       'There are ', n,
          $       ' values in the input vector', char(0)
           if (ioerr .ne. 0) then
             call xstopx ('fortransub: error writing string')
           endif
           return
           end



   This example demonstrates most of the features needed to link to an
external Fortran function, including passing arrays and strings, as well
as exception handling.  Both the Fortran and C++ files need to be
compiled in order for the example to work.

     mkoctfile fortrandemo.cc fortransub.f
     [b, s] = fortrandemo (1:3)
     ⇒
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortrandemo (0:3)
     error: fortrandemo: fortransub: divide by zero


File: octave.info,  Node: Allocating Local Memory in Oct-Files,  Next: Input Parameter Checking in Oct-Files,  Prev: Calling External Code from Oct-Files,  Up: Oct-Files

A.1.10 Allocating Local Memory in Oct-Files
-------------------------------------------

Allocating memory within an oct-file might seem easy as the C++
new/delete operators can be used.  However, in that case great care must
be taken to avoid memory leaks.  The preferred manner in which to
allocate memory for use locally is to use the ‘OCTAVE_LOCAL_BUFFER’
macro.  An example of its use is

     OCTAVE_LOCAL_BUFFER (double, tmp, len)

that returns a pointer ‘tmp’ of type ‘double *’ of length ‘len’.

   In this case Octave itself will worry about reference counting and
variable scope and will properly free memory without programmer
intervention.


File: octave.info,  Node: Input Parameter Checking in Oct-Files,  Next: Exception and Error Handling in Oct-Files,  Prev: Allocating Local Memory in Oct-Files,  Up: Oct-Files

A.1.11 Input Parameter Checking in Oct-Files
--------------------------------------------

As oct-files are compiled functions they open up the possibility of
crashing Octave through careless function calls or memory faults.  It is
quite important that each and every function have a sufficient level of
parameter checking to ensure that Octave behaves well.

   The minimum requirement, as previously discussed, is to check the
number of input arguments before using them to avoid referencing a
nonexistent argument.  However, in some cases this might not be
sufficient as the underlying code imposes further constraints.  For
example, an external function call might be undefined if the input
arguments are not integers, or if one of the arguments is zero, or if
the input is complex and a real value was expected.  Therefore,
oct-files often need additional input parameter checking.

   There are several functions within Octave that can be useful for the
purposes of parameter checking.  These include the methods of the
octave_value class like ‘is_real_matrix’, ‘is_numeric_type’, etc.
Often, with a knowledge of the Octave m-file language, you can guess at
what the corresponding C++ routine will.  In addition there are some
more specialized input validation functions of which a few are
demonstrated below.

     #include <octave/oct.h>

     DEFUN_DLD (paramdemo, args, nargout, "Parameter Check Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else if (nargout != 0)
         error ("paramdemo: OUTPUT argument required");
       else
         {
           NDArray m = args(0).array_value ();
           double min_val = -10.0;
           double max_val = 10.0;
           octave_stdout << "Properties of input array:\n";
           if (m.any_element_is_negative ())
             octave_stdout << "  includes negative values\n";
           if (m.any_element_is_inf_or_nan ())
             octave_stdout << "  includes Inf or NaN values\n";
           if (m.any_element_not_one_or_zero ())
             octave_stdout << "  includes other values than 1 and 0\n";
           if (m.all_elements_are_int_or_inf_or_nan ())
             octave_stdout << "  includes only int, Inf or NaN values\n";
           if (m.all_integers (min_val, max_val))
             octave_stdout << "  includes only integers in [-10,10]\n";
         }
       return retval;
     }


An example of its use is:

     paramdemo ([1, 2, NaN, Inf])
     ⇒ Properties of input array:
          includes Inf or NaN values
          includes other values than 1 and 0
          includes only int, Inf or NaN values


File: octave.info,  Node: Exception and Error Handling in Oct-Files,  Next: Documentation and Test of Oct-Files,  Prev: Input Parameter Checking in Oct-Files,  Up: Oct-Files

A.1.12 Exception and Error Handling in Oct-Files
------------------------------------------------

Another important feature of Octave is its ability to react to the user
typing <Control-C> even during calculations.  This ability is based on
the C++ exception handler, where memory allocated by the C++ new/delete
methods are automatically released when the exception is treated.  When
writing an oct-file, to allow Octave to treat the user typing
<Control-C>, the ‘OCTAVE_QUIT’ macro is supplied.  For example:

     for (octave_idx_type i = 0; i < a.nelem (); i++)
       {
         OCTAVE_QUIT;
         b.elem (i) = 2. * a.elem (i);
       }

   The presence of the ‘OCTAVE_QUIT’ macro in the inner loop allows
Octave to treat the user request with the <Control-C>.  Without this
macro, the user must either wait for the function to return before the
interrupt is processed, or press <Control-C> three times to force Octave
to exit.

   The ‘OCTAVE_QUIT’ macro does impose a very small speed penalty, and
so for loops that are known to be small it might not make sense to
include ‘OCTAVE_QUIT’.

   When creating an oct-file that uses an external libraries, the
function might spend a significant portion of its time in the external
library.  It is not generally possible to use the ‘OCTAVE_QUIT’ macro in
this case.  The alternative in this case is

     BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
     ...  some code that calls a "foreign" function ...
     END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;

   The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated.  Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
fortran_vec method or the ‘OCTAVE_LOCAL_BUFFER’ macro.

   The Octave unwind_protect mechanism (*note The unwind_protect
Statement::) can also be used in oct-files.  In conjunction with the
exception handling of Octave, it is important to enforce that certain
code is run to allow variables, etc. to be restored even if an exception
occurs.  An example of the use of this mechanism is

     #include <octave/oct.h>
     #include <octave/unwind-prot.h>

     void
     my_err_handler (const char *fmt, ...)
     {
       // Do nothing!!
     }

     void
     my_err_with_id_handler (const char *id, const char *fmt, ...)
     {
       // Do nothing!!
     }

     DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (nargin < 2)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           NDArray b = args(1).array_value ();

           if (! error_state)
             {
               // Declare unwind_protect frame which lasts as long as
               // the variable frame has scope.
               unwind_protect frame;
               frame.add_fcn (set_liboctave_warning_handler,
                              current_liboctave_warning_handler);

               frame.add_fcn (set_liboctave_warning_with_id_handler,
                              current_liboctave_warning_with_id_handler);

               set_liboctave_warning_handler (my_err_handler);
               set_liboctave_warning_with_id_handler (my_err_with_id_handler);

               retval = octave_value (quotient (a, b));
             }
         }

       return retval;
     }


   As can be seen in the example:

     unwinddemo (1, 0)
     ⇒ Inf
     1 / 0
     ⇒ warning: division by zero
        Inf

   The warning for division by zero (and in fact all warnings) are
disabled in the ‘unwinddemo’ function.


File: octave.info,  Node: Documentation and Test of Oct-Files,  Prev: Exception and Error Handling in Oct-Files,  Up: Oct-Files

A.1.13 Documentation and Test of Oct-Files
------------------------------------------

The documentation of an oct-file is the fourth string parameter of the
‘DEFUN_DLD’ macro.  This string can be formatted in the same manner as
the help strings for user functions (*note Documentation Tips::),
however there are some issue that are particular to the formatting of
help strings within oct-files.

   The major issue is that the help string will typically be longer than
a single line of text, and so the formatting of long help strings needs
to be taken into account.  There are several possible solutions, but the
most common is illustrated in the following example,

     DEFUN_DLD (do_what_i_want, args, nargout,
       "-*- texinfo -*-\n\
     @deftypefn {Function File} {} do_what_i_say (@var{n})\n\
     A function that does what the user actually wants rather\n\
     than what they requested.\n\
     @end deftypefn")
     {
     ...
     }

where, as can be seen, each line of text is terminated by ‘\n\’ which is
an embedded new-line in the string together with a C++ string
continuation character.  Note that the final ‘\’ must be the last
character on the line.

   Octave also includes the ability to embed test and demonstration code
for a function within the code itself (*note Test and Demo Functions::).
This can be used from within oct-files (or in fact any file) with
certain provisos.  First, the test and demo functions of Octave look for
‘%!’ as the first two characters of a line to identify test and
demonstration code.  This is a requirement for oct-files as well.  In
addition, the test and demonstration code must be wrapped in a comment
block to avoid it being interpreted by the compiler.  Finally, the
Octave test and demonstration code must have access to the original
source code of the oct-file and not just the compiled code as the tests
are stripped from the compiled code.  An example in an oct-file might be

     /*
     %!assert (sin ([1,2]), [sin(1),sin(2)])
     %!error (sin ())
     %!error (sin (1,1))
     */


File: octave.info,  Node: Mex-Files,  Next: Standalone Programs,  Prev: Oct-Files,  Up: External Code Interface

A.2 Mex-Files
=============

Octave includes an interface to allow legacy mex-files to be compiled
and used with Octave.  This interface can also be used to share code
between Octave and MATLAB users.  However, as mex-files expose MATLAB’s
internal API, and the internal structure of Octave is different, a
mex-file can never have the same performance in Octave as the equivalent
oct-file.  In particular, to support the manner in which variables are
passed to mex functions there are a significant number of additional
copies of memory blocks when calling or returning from a mex-file
function.  For this reason, it is recommended that any new code be
written with the oct-file interface previously discussed.

* Menu:

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::


File: octave.info,  Node: Getting Started with Mex-Files,  Next: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.1 Getting Started with Mex-Files
------------------------------------

The basic command to build a mex-file is either ‘mkoctfile --mex’ or
‘mex’.  The first command can be used either from within Octave or from
the command line.  However, to avoid issues with MATLAB’s own ‘mex’
command, the use of the command ‘mex’ is limited to within Octave.
Compiled mex-files have the extension ‘.mex’.

 -- Command: mex [options] file ...
     Compile source code written in C, C++, or Fortran, to a MEX file.

     This is equivalent to ‘mkoctfile --mex [options] file’.

     See also: *note mkoctfile: XREFmkoctfile, *note mexext: XREFmexext.

 -- Function File: mexext ()
     Return the filename extension used for MEX files.

     See also: *note mex: XREFmex.

   Consider the following short example:

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mexPrintf ("Hello, World!\n");

       mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
     }


   The first line ‘#include "mex.h"’ makes available all of the
definitions necessary for a mex-file.  One important difference between
Octave and MATLAB is that the header file "matrix.h" is implicitly
included through the inclusion of "mex.h".  This is necessary to avoid a
conflict with the Octave file "Matrix.h" for operating systems and
compilers that don’t distinguish between filenames in upper and lower
case.

   The entry point into the mex-file is defined by ‘mexFunction’.  The
function takes four arguments:

  1. The number of return arguments (# of left-hand side args).

  2. An array of pointers to return arguments.

  3. The number of input arguments (# of right-hand side args).

  4. An array of pointers to input arguments.

   Note that the function name definition is not explicitly included in
‘mexFunction’ and so there can only be a single ‘mexFunction’ entry
point per file.  Instead, the name of the function as seen in Octave is
determined by the name of the mex-file itself minus the extension.
Therefore, if the above function is in the file ‘myhello.c’, it can be
compiled with

     mkoctfile --mex myhello.c

which creates a file ‘myhello.mex’.  The function can then be run from
Octave as

     myhello (1,2,3)
     ⇒ Hello, World!
     ⇒ I have 3 inputs and 0 outputs

   It should be noted that the mex-file contains no help string for the
functions it contains.  To document mex-files, there should exist an
m-file in the same directory as the mex-file itself.  Taking the above
as an example, we would therefore have a file ‘myhello.m’ that might
contain the text

     %MYHELLO Simple test of the functionality of a mex-file.

   In this case, the function that will be executed within Octave will
be given by the mex-file, while the help string will come from the
m-file.  This can also be useful to allow a sample implementation of the
mex-file within the Octave language itself for testing purposes.

   Although there cannot be multiple entry points in a single mex-file,
one can use the ‘mexFunctionName’ function to determine what name the
mex-file was called with.  This can be used to alter the behavior of the
mex-file based on the function name.  For example, if

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       const char *nm;

       nm = mexFunctionName ();
       mexPrintf ("You called function: %s\n", nm);
       if (strcmp (nm, "myfunc") == 0)
         mexPrintf ("This is the principal function\n", nm);

       return;
     }


is in file ‘myfunc.c’, and it is compiled with

     mkoctfile --mex myfunc.c
     ln -s myfunc.mex myfunc2.mex

then as can be seen by

     myfunc ()
     ⇒ You called function: myfunc
         This is the principal function
     myfunc2 ()
     ⇒ You called function: myfunc2

the behavior of the mex-file can be altered depending on the functions
name.

   Although the user should only include ‘mex.h’ in their code, Octave
declares additional functions, typedefs, etc., available to the user to
write mex-files in the headers ‘mexproto.h’ and ‘mxarray.h’.


File: octave.info,  Node: Working with Matrices and Arrays in Mex-Files,  Next: Character Strings in Mex-Files,  Prev: Getting Started with Mex-Files,  Up: Mex-Files

A.2.2 Working with Matrices and Arrays in Mex-Files
---------------------------------------------------

The basic mex type of all variables is ‘mxArray’.  Any object, such as a
matrix, cell array, or structure is stored in this basic type.  As such,
‘mxArray’ serves basically the same purpose as the octave_value class in
oct-files in that it acts as a container for the more specialized types.

   The ‘mxArray’ structure contains at a minimum, the name of the
variable it represents, its dimensions, its type, and whether the
variable is real or complex.  It can also contain a number of additional
fields depending on the type of the ‘mxArray’.  There are a number of
functions to create ‘mxArray’ structures, including
‘mxCreateDoubleMatrix’, ‘mxCreateCellArray’, ‘mxCreateSparse’, and the
generic ‘mxCreateNumericArray’.

   The basic function to access the data contained in an array is
‘mxGetPr’.  As the mex interface assumes that real and imaginary parts
of a complex array are stored separately, there is an equivalent
function ‘mxGetPi’ that gets the imaginary part.  Both of these
functions are only for use with double precision matrices.  The generic
functions ‘mxGetData’ and ‘mxGetImagData’ perform the same operation on
all matrix types.  For example:

     mxArray *m;
     mwSize *dims;
     UINT32_T *pr;

     dims = (mwSize *) mxMalloc (2 * sizeof (mwSize));
     dims[0] = 2; dims[1] = 2;
     m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
     pr = (UINT32_T *) mxGetData (m);

   There are also the functions ‘mxSetPr’, etc., that perform the
inverse, and set the data of an array to use the block of memory pointed
to by the argument of ‘mxSetPr’.

   Note the type ‘mwSize’ used above, and also ‘mwIndex’, are defined as
the native precision of the indexing in Octave on the platform on which
the mex-file is built.  This allows both 32- and 64-bit platforms to
support mex-files.  ‘mwSize’ is used to define array dimensions and the
maximum number or elements, while ‘mwIndex’ is used to define indexing
into arrays.

   An example that demonstrates how to work with arbitrary real or
complex double precision arrays is given by the file ‘mypow2.c’ shown
below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[],
                  int nrhs, const mxArray* prhs[])
     {
       mwSize n;
       mwIndex i;
       double *vri, *vro;

       if (nrhs != 1 || ! mxIsDouble (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a double matrix");

       n = mxGetNumberOfElements (prhs[0]);
       plhs[0] = mxCreateNumericArray (mxGetNumberOfDimensions (prhs[0]),
                                       mxGetDimensions (prhs[0]),
                                       mxGetClassID (prhs[0]),
                                       mxIsComplex (prhs[0]));
       vri = mxGetPr (prhs[0]);
       vro = mxGetPr (plhs[0]);

       if (mxIsComplex (prhs[0]))
         {
           double *vii, *vio;
           vii = mxGetPi (prhs[0]);
           vio = mxGetPi (plhs[0]);

           for (i = 0; i < n; i++)
             {
               vro[i] = vri[i] * vri[i] - vii[i] * vii[i];
               vio[i] = 2 * vri[i] * vii[i];
             }
         }
       else
         {
           for (i = 0; i < n; i++)
             vro[i] = vri[i] * vri[i];
         }
     }


with an example of its use

     b = randn (4,1) + 1i * randn (4,1);
     all (b.^2 == mypow2 (b))
     ⇒ 1

   The example above uses the functions ‘mxGetDimensions’,
‘mxGetNumberOfElements’, and ‘mxGetNumberOfDimensions’ to work with the
dimensions of multi-dimensional arrays.  The functions ‘mxGetM’, and
‘mxGetN’ are also available to find the number of rows and columns in a
2-D matrix.


File: octave.info,  Node: Character Strings in Mex-Files,  Next: Cell Arrays with Mex-Files,  Prev: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.3 Character Strings in Mex-Files
------------------------------------

As mex-files do not make the distinction between single and double
quoted strings within Octave, there is perhaps less complexity in the
use of strings and character matrices in mex-files.  An example of their
use that parallels the demo in ‘stringdemo.cc’ is given in the file
‘mystring.c’, as shown below.

     #include <string.h>
     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize m, n;
       mwIndex i, j;
       mxChar *pi, *po;

       if (nrhs != 1 || ! mxIsChar (prhs[0])
           || mxGetNumberOfDimensions (prhs[0]) > 2)
         mexErrMsgTxt ("ARG1 must be a char matrix");

       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       pi = mxGetChars (prhs[0]);
       plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS, mxREAL);
       po = mxGetChars (plhs[0]);

       for (j = 0; j < n; j++)
         for (i = 0; i < m; i++)
           po[j*m + m - 1 - i] = pi[j*m + i];
     }


An example of its expected output is

     mystring (["First String"; "Second String"])
     ⇒ Second String
        First String

   Other functions in the mex interface for handling character strings
are ‘mxCreateString’, ‘mxArrayToString’, and
‘mxCreateCharMatrixFromStrings’.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an
arbitrary distinction as the data in the mxArray for the matrix is
consecutive in any case.


File: octave.info,  Node: Cell Arrays with Mex-Files,  Next: Structures with Mex-Files,  Prev: Character Strings in Mex-Files,  Up: Mex-Files

A.2.4 Cell Arrays with Mex-Files
--------------------------------

One can perform exactly the same operations on Cell arrays in mex-files
as in oct-files.  An example that reduplicates the function of the
‘celldemo.cc’ oct-file in a mex-file is given by ‘mycell.c’ as shown
below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[],
                  int nrhs, const mxArray* prhs[])
     {
       mwSize n;
       mwIndex i;

       if (nrhs != 1 || ! mxIsCell (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a cell");

       n = mxGetNumberOfElements (prhs[0]);
       n = (n > nlhs ? nlhs : n);

       for (i = 0; i < n; i++)
         plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
     }


The output is identical to the oct-file version as well.

     [b1, b2, b3] = mycell ({1, [1, 2], "test"})
     ⇒
     b1 =  1
     b2 =

        1   2

     b3 = test

   Note in the example the use of the ‘mxDuplicateArray’ function.  This
is needed as the ‘mxArray’ pointer returned by ‘mxGetCell’ might be
deallocated.  The inverse function to ‘mxGetCell’, used for setting Cell
values, is ‘mxSetCell’ and is defined as

     void mxSetCell (mxArray *ptr, int idx, mxArray *val);

   Finally, to create a cell array or matrix, the appropriate functions
are

     mxArray *mxCreateCellArray (int ndims, const int *dims);
     mxArray *mxCreateCellMatrix (int m, int n);


File: octave.info,  Node: Structures with Mex-Files,  Next: Sparse Matrices with Mex-Files,  Prev: Cell Arrays with Mex-Files,  Up: Mex-Files

A.2.5 Structures with Mex-Files
-------------------------------

The basic function to create a structure in a mex-file is
‘mxCreateStructMatrix’ which creates a structure array with a two
dimensional matrix, or ‘mxCreateStructArray’.

     mxArray *mxCreateStructArray (int ndims, int *dims,
                                   int num_keys,
                                   const char **keys);
     mxArray *mxCreateStructMatrix (int rows, int cols,
                                    int num_keys,
                                    const char **keys);

   Accessing the fields of the structure can then be performed with
‘mxGetField’ and ‘mxSetField’ or alternatively with the
‘mxGetFieldByNumber’ and ‘mxSetFieldByNumber’ functions.

     mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                          const char *key);
     mxArray *mxGetFieldByNumber (const mxArray *ptr,
                                  mwIndex index, int key_num);
     void mxSetField (mxArray *ptr, mwIndex index,
                      const char *key, mxArray *val);
     void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                              int key_num, mxArray *val);

   A difference between the oct-file interface to structures and the
mex-file version is that the functions to operate on structures in
mex-files directly include an ‘index’ over the elements of the arrays of
elements per ‘field’; Whereas, the oct-file structure includes a Cell
Array per field of the structure.

   An example that demonstrates the use of structures in a mex-file can
be found in the file ‘mystruct.c’ shown below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[],
                  int nrhs, const mxArray* prhs[])
     {
       int i;
       mwIndex j;
       mxArray *v;
       const char *keys[] = { "this", "that" };

       if (nrhs != 1 || ! mxIsStruct (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a struct");

       for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
         for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
           {
             mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j);
             v = mxGetFieldByNumber (prhs[0], j, i);
             mexCallMATLAB (0, NULL, 1, &v, "disp");
           }

       v = mxCreateStructMatrix (2, 2, 2, keys);

       mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
       mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
       mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
       mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
       mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
       mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
       mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
       mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));

       if (nlhs)
         plhs[0] = v;
     }


   An example of the behavior of this function within Octave is then

     a(1).f1 = "f11"; a(1).f2 = "f12";
     a(2).f1 = "f21"; a(2).f2 = "f22";
     b = mystruct (a);
     ⇒  field f1(0) = f11
         field f1(1) = f21
         field f2(0) = f12
         field f2(1) = f22
     b
     ⇒ 2x2 struct array containing the fields:

          this
          that

     b(3)
     ⇒ scalar structure containing the fields:

          this = this3
          that = that3


File: octave.info,  Node: Sparse Matrices with Mex-Files,  Next: Calling Other Functions in Mex-Files,  Prev: Structures with Mex-Files,  Up: Mex-Files

A.2.6 Sparse Matrices with Mex-Files
------------------------------------

The Octave format for sparse matrices is identical to the mex format in
that it is a compressed column sparse format.  Also in both, sparse
matrices are required to be two-dimensional.  The only difference is
that the real and imaginary parts of the matrix are stored separately.

   The mex-file interface, in addition to using ‘mxGetM’, ‘mxGetN’,
‘mxSetM’, ‘mxSetN’, ‘mxGetPr’, ‘mxGetPi’, ‘mxSetPr’, and ‘mxSetPi’, also
supplies the following functions.

     mwIndex *mxGetIr (const mxArray *ptr);
     mwIndex *mxGetJc (const mxArray *ptr);
     mwSize mxGetNzmax (const mxArray *ptr);

     void mxSetIr (mxArray *ptr, mwIndex *ir);
     void mxSetJc (mxArray *ptr, mwIndex *jc);
     void mxSetNzmax (mxArray *ptr, mwSize nzmax);

‘mxGetNzmax’ gets the maximum number of elements that can be stored in
the sparse matrix.  This is not necessarily the number of nonzero
elements in the sparse matrix.  ‘mxGetJc’ returns an array with one
additional value than the number of columns in the sparse matrix.  The
difference between consecutive values of the array returned by ‘mxGetJc’
define the number of nonzero elements in each column of the sparse
matrix.  Therefore,

     mwSize nz, n;
     mwIndex *Jc;
     mxArray *m;
     ...
     n = mxGetN (m);
     Jc = mxGetJc (m);
     nz = Jc[n];

returns the actual number of nonzero elements stored in the matrix in
‘nz’.  As the arrays returned by ‘mxGetPr’ and ‘mxGetPi’ only contain
the nonzero values of the matrix, we also need a pointer to the rows of
the nonzero elements, and this is given by ‘mxGetIr’.  A complete
example of the use of sparse matrices in mex-files is given by the file
‘mysparse.c’ shown below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize m, n, nz;
       mxArray *v;
       mwIndex i;
       double *pr, *pi;
       double *pr2, *pi2;
       mwIndex *ir, *jc;
       mwIndex *ir2, *jc2;

       if (nrhs != 1 || ! mxIsSparse (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a sparse matrix");

       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       nz = mxGetNzmax (prhs[0]);

       if (mxIsComplex (prhs[0]))
         {
           mexPrintf ("Matrix is %d-by-%d complex sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           pi = mxGetPi (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;

           mexPrintf ("last nonzero element (%d, %d) = (%g, %g)\n",
                      ir[nz-1]+ 1, i, pr[nz-1], pi[nz-1]);

           v = mxCreateSparse (m, n, nz, mxCOMPLEX);
           pr2 = mxGetPr (v);
           pi2 = mxGetPi (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               pi2[i] = 2 * pi[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else if (mxIsLogical (prhs[0]))
         {
           mxLogical *pbr, *pbr2;
           mexPrintf ("Matrix is %d-by-%d logical sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pbr = mxGetLogicals (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last nonzero element (%d, %d) = %d\n",
                      ir[nz-1]+ 1, i, pbr[nz-1]);

           v = mxCreateSparseLogicalMatrix (m, n, nz);
           pbr2 = mxGetLogicals (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pbr2[i] = pbr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else
         {
           mexPrintf ("Matrix is %d-by-%d real sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last nonzero element (%d, %d) = %g\n",
                      ir[nz-1]+ 1, i, pr[nz-1]);

           v = mxCreateSparse (m, n, nz, mxREAL);
           pr2 = mxGetPr (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
     }


   A sample usage of ‘mysparse’ is

     sm = sparse ([1, 0; 0, pi]);
     mysparse (sm)
     ⇒
     Matrix is 2-by-2 real sparse matrix with 2 elements
     last nonzero element (2, 2) = 3.14159


File: octave.info,  Node: Calling Other Functions in Mex-Files,  Prev: Sparse Matrices with Mex-Files,  Up: Mex-Files

A.2.7 Calling Other Functions in Mex-Files
------------------------------------------

It is possible to call other Octave functions from within a mex-file
using ‘mexCallMATLAB’.  An example of the use of ‘mexCallMATLAB’ can be
see in the example below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[],
                  int nrhs, const mxArray* prhs[])
     {
       char *str;

       mexPrintf ("Starting file myfeval.mex\n");

       mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);

       if (nrhs < 1 || ! mxIsChar (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a function name");

       str = mxArrayToString (prhs[0]);

       mexPrintf ("I'm going to call the function %s\n", str);

       if (nlhs == 0)
         nlhs = 1;  // Octave's automatic 'ans' variable

       /* Cast prhs just to get rid of 'const' qualifier and stop compile warning */
       mexCallMATLAB (nlhs, plhs, nrhs-1, (mxArray**)prhs+1, str);

       mxFree (str);
     }


   If this code is in the file ‘myfeval.c’, and is compiled to
‘myfeval.mex’, then an example of its use is

     a = myfeval ("sin", 1)
     ⇒ Starting file myfeval.mex
        I have 2 inputs and 1 outputs
        I'm going to call the interpreter function sin
        a =  0.84147

   Note that it is not possible to use function handles or inline
functions within a mex-file.


File: octave.info,  Node: Standalone Programs,  Prev: Mex-Files,  Up: External Code Interface

A.3 Standalone Programs
=======================

The libraries Octave itself uses can be utilized in standalone
applications.  These applications then have access, for example, to the
array and matrix classes, as well as to all of the Octave algorithms.
The following C++ program, uses class Matrix from ‘liboctave.a’ or
‘liboctave.so’.

     #include <iostream>
     #include <octave/oct.h>

     int
     main (void)
     {
       std::cout << "Hello Octave world!\n";

       int n = 2;
       Matrix a_matrix = Matrix (n, n);

       for (octave_idx_type i = 0; i < n; i++)
         for (octave_idx_type j = 0; j < n; j++)
           a_matrix(i,j) = (i + 1) * 10 + (j + 1);

       std::cout << a_matrix;

       return 0;
     }


mkoctfile can be used to build a standalone application with a command
like

     $ mkoctfile --link-stand-alone standalone.cc -o standalone
     $ ./standalone
     Hello Octave world!
       11 12
       21 22
     $

   Note that the application ‘standalone’ will be dynamically linked
against the Octave libraries and any Octave support libraries.  The
above allows the Octave math libraries to be used by an application.  It
does not, however, allow the script files, oct-files, or built-in
functions of Octave to be used by the application.  To do that the
Octave interpreter needs to be initialized first.  An example of how to
do this can then be seen in the code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/octave.h>
     #include <octave/parse.h>
     #include <octave/toplev.h>

     int
     main (void)
     {
       string_vector argv (2);
       argv(0) = "embedded";
       argv(1) = "-q";

       octave_main (2, argv.c_str_vec (), 1);

       octave_idx_type n = 2;
       octave_value_list in;

       for (octave_idx_type i = 0; i < n; i++)
         in(i) = octave_value (5 * (i + 2));

       octave_value_list out = feval ("gcd", in, 1);

       if (! error_state && out.length () > 0)
         std::cout << "GCD of ["
                   << in(0).int_value ()
                   << ", "
                   << in(1).int_value ()
                   << "] is " << out(0).int_value ()
                   << std::endl;
       else
         std::cout << "invalid\n";

       clean_up_and_exit (0);
     }


which, as before, is compiled and run as a standalone application with

     $ mkoctfile --link-stand-alone embedded.cc -o embedded
     $ ./embedded
     GCD of [10, 15] is 5
     $

   It is worth noting that, if only built-in functions are to be called
from a C++ standalone program, then it does not need to initialize the
interpreter to do so.  The general rule is that, for a built-in function
named ‘function_name’ in the interpreter, there will be a C++ function
named ‘Ffunction_name’ (note the prepended capital ‘F’) accessible in
the C++ API.  The declarations for all built-in functions are collected
in the header file ‘builtin-defun-decls.h’.  This feature should be used
with care as the list of built-in functions can change.  No guarantees
can be made that a function that is currently built in won’t be
implemented as a .m file or as a dynamically linked function in the
future.  An example of how to call built-in functions from C++ can be
seen in the code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/builtin-defun-decls.h>

     int
     main (void)
     {
       int n = 2;
       Matrix a_matrix = Matrix (n, n);

       for (octave_idx_type i = 0; i < n; i++)
         for (octave_idx_type j = 0; j < n; j++)
           a_matrix(i,j) = (i + 1) * 10 + (j + 1);

       std::cout << "This is a matrix:" << std::endl
                 << a_matrix            << std::endl;

       octave_value_list in;
       in(0) = a_matrix;

       octave_value_list out = Fnorm (in, 1);
       double norm_of_the_matrix = out(0).double_value ();

       std::cout << "This is the norm of the matrix:" << std::endl
                 << norm_of_the_matrix                << std::endl;

       return 0;
     }


which, again, is compiled and run as a standalone application with

     $ mkoctfile --link-stand-alone standalonebuiltin.cc -o standalonebuiltin
     $ ./standalonebuiltin
     This is a matrix:
      11 12
      21 22

     This is the norm of the matrix:
     34.4952
     $


File: octave.info,  Node: Test and Demo Functions,  Next: Tips and Standards,  Prev: External Code Interface,  Up: Top

Appendix B Test and Demo Functions
**********************************

Octave includes a number of functions to allow the integration of
testing and demonstration code in the source code of the functions
themselves.

* Menu:

* Test Functions::
* Demonstration Functions::


File: octave.info,  Node: Test Functions,  Next: Demonstration Functions,  Up: Test and Demo Functions

B.1 Test Functions
==================

 -- Command: test NAME
 -- Command: test NAME quiet|normal|verbose
 -- Function File: test ("NAME", "quiet|normal|verbose", FID)
 -- Function File: test ("NAME", "quiet|normal|verbose", FNAME)
 -- Function File: SUCCESS = test (...)
 -- Function File: [N, NMAX, NXFAIL, NSKIP] = test (...)
 -- Function File: [CODE, IDX] = test ("NAME", "grabdemo")
 -- Function File: test ([], "explain", FID)
 -- Function File: test ([], "explain", FNAME)

     Perform built-in self-tests from the first file in the loadpath
     matching NAME.

     ‘test’ can be called in either command or functional form.  The
     exact operation of test is determined by a combination of mode
     (interactive or batch), reporting level ("quiet", "normal",
     "verbose"), and whether a logfile or summary output variable is
     used.

     The default mode when ‘test’ is called from the command line is
     interactive.  In this mode, tests will be run until the first error
     is encountered, or all tests complete successfully.  In batch mode,
     all tests are run regardless of any failures, and the results are
     collected for reporting.  Tests which require user interaction,
     i.e., demo blocks, are never run in batch mode.

     Batch mode is enabled by either 1) specifying a logfile using the
     third argument FNAME or FID, or 2) requesting an output argument
     such as SUCCESS, N, etc.

     The optional second argument determines the amount of output to
     generate and which types of tests to run.  The default value is
     "normal".  Requesting an output argument will suppress printing the
     final summary message and any intermediate warnings, unless verbose
     reporting is enabled.

     "quiet"
          Print a summary message when all tests pass, or print an error
          with the results of the first bad test when a failure occurs.
          Don’t run tests which require user interaction.

     "normal"
          Display warning messages about skipped tests or failing xtests
          during test execution.  Print a summary message when all tests
          pass, or print an error with the results of the first bad test
          when a failure occurs.  Don’t run tests which require user
          interaction.

     "verbose"
          Display tests before execution.  Print all warning messages.
          In interactive mode, run all tests including those which
          require user interaction.

     The optional third input argument specifies a logfile where results
     of the tests should be written.  The logfile may be a character
     string (FNAME) or an open file descriptor ID (FID).  To enable
     batch processing, but still print the results to the screen, use
     ‘stdout’ for FID.

     When called with just a single output argument SUCCESS, ‘test’
     returns true if all of the tests were successful.  If called with
     more than one output argument then the number of successful tests
     (N), the total number of tests in the file (NMAX), the number of
     xtest failures (NXFAIL), and the number of skipped tests (NSKIP are
     returned.

     Example

          test sind
          ⇒
          PASSES 5 out of 5 tests

          [n, nmax] = test ("sind")
          ⇒
          n =  5
          nmax =  5

     Additional Calling Syntaxes

     If the second argument is the string "grabdemo", the contents of
     any built-in demo blocks are extracted but not executed.  The text
     for all code blocks is concatenated and returned as CODE with IDX
     being a vector of positions of the ends of each demo block.  For an
     easier way to extract demo blocks from files, *Note example:
     XREFexample.

     If the second argument is "explain" then NAME is ignored and an
     explanation of the line markers used in ‘test’ output reports is
     written to the file specified by FNAME or FID.

     See also: *note assert: XREFassert, *note fail: XREFfail, *note
     demo: XREFdemo, *note example: XREFexample, *note error: XREFerror.

   ‘test’ scans the named script file looking for lines which start with
the identifier ‘%!’.  The prefix is stripped off and the rest of the
line is processed through the Octave interpreter.  If the code generates
an error, then the test is said to fail.

   Since ‘eval()’ will stop at the first error it encounters, you must
divide your tests up into blocks, with anything in a separate block
evaluated separately.  Blocks are introduced by valid keywords like
‘test’, ‘function’, or ‘assert’ immediately following ‘%!’.  A block is
defined by indentation as in Python.  Lines beginning with
‘%!<whitespace>’ are part of the preceeding block.

   For example:

     %!test error ("this test fails!");
     %!test "test doesn't fail. it doesn't generate an error";

   When a test fails, you will see something like:

       ***** test error ("this test fails!")
     !!!!! test failed
     this test fails!

   Generally, to test if something works, you want to assert that it
produces a correct value.  A real test might look something like

     %!test
     %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
     %! expect = [ A ; 2*A ];
     %! get = kron (B, A);
     %! if (any (size (expect) != size (get)))
     %!   error ("wrong size: expected %d,%d but got %d,%d",
     %!          size (expect), size (get));
     %! elseif (any (any (expect != get)))
     %!   error ("didn't get what was expected.");
     %! endif

   To make the process easier, use the ‘assert’ function.  For example,
with ‘assert’ the previous test is reduced to:

     %!test
     %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
     %! assert (kron (B, A), [ A; 2*A ]);

   ‘assert’ can accept a tolerance so that you can compare results
absolutely or relatively.  For example, the following all succeed:

     %!test assert (1+eps, 1, 2*eps)          # absolute error
     %!test assert (100+100*eps, 100, -2*eps) # relative error

   You can also do the comparison yourself, but still have assert
generate the error:

     %!test assert (isempty ([]))
     %!test assert ([1, 2; 3, 4] > 0)

   Because ‘assert’ is so frequently used alone in a test block, there
is a shorthand form:

     %!assert (...)

which is equivalent to:

     %!test assert (...)

   Occasionally a block of tests will depend on having optional
functionality in Octave.  Before testing such blocks the availability of
the required functionality must be checked.  A ‘%!testif HAVE_XXX’ block
will only be run if Octave was compiled with functionality ‘HAVE_XXX’.
For example, the sparse single value decomposition, ‘svds()’, depends on
having the ARPACK library.  All of the tests for ‘svds’ begin with

     %!testif HAVE_ARPACK

Review ‘config.h’ or ‘octave_config_info ("features")’ to see some of
the possible values to check.

   Sometimes during development there is a test that should work but is
known to fail.  You still want to leave the test in because when the
final code is ready the test should pass, but you may not be able to fix
it immediately.  To avoid unnecessary bug reports for these known
failures, mark the block with ‘xtest’ rather than ‘test’:

     %!xtest assert (1==0)
     %!xtest fail ("success=1", "error")

In this case, the test will run and any failure will be reported.
However, testing is not aborted and subsequent test blocks will be
processed normally.  Another use of ‘xtest’ is for statistical tests
which should pass most of the time but are known to fail occasionally.

   Each block is evaluated in its own function environment, which means
that variables defined in one block are not automatically shared with
other blocks.  If you do want to share variables, then you must declare
them as ‘shared’ before you use them.  For example, the following
declares the variable A, gives it an initial value (default is empty),
and then uses it in several subsequent tests.

     %!shared A
     %! A = [1, 2, 3; 4, 5, 6];
     %!assert (kron ([1; 2], A), [ A; 2*A ]);
     %!assert (kron ([1, 2], A), [ A, 2*A ]);
     %!assert (kron ([1,2; 3,4], A), [ A,2*A; 3*A,4*A ]);

   You can share several variables at the same time:

     %!shared A, B

   You can also share test functions:

     %!function A = fn (B)
     %!  A = 2*B;
     %!endfunction
     %!assert (fn(2), 4);

   Note that all previous variables and values are lost when a new
shared block is declared.

   Remember that ‘%!function’ begins a new block and that
‘%!endfunction’ ends this block.  Be aware that until a new block is
started, lines starting with ‘%!<space>’ will be discarded as comments.
The following is nearly identical to the example above, but does
nothing.

     %!function A = fn (B)
     %!  A = 2*B;
     %!endfunction
     %! assert (fn(2), 4);

Because there is a space after ‘%!’ the ‘assert’ statement does not
begin a new block and this line is treated as a comment.

   Error and warning blocks are like test blocks, but they only succeed
if the code generates an error.  You can check the text of the error is
correct using an optional regular expression ‘<pattern>’.  For example:

     %!error <passes!> error ("this test passes!");

   If the code doesn’t generate an error, the test fails.  For example:

     %!error "this is an error because it succeeds.";

produces

       ***** error "this is an error because it succeeds.";
     !!!!! test failed: no error

   It is important to automate the tests as much as possible, however
some tests require user interaction.  These can be isolated into demo
blocks, which if you are in batch mode, are only run when called with
‘demo’ or the ‘verbose’ option to ‘test’.  The code is displayed before
it is executed.  For example,

     %!demo
     %! T = [0:0.01:2*pi]; X = sin (T);
     %! plot (T, X);
     %! # you should now see a sine wave in your figure window

produces

     funcname example 1:
      T = [0:0.01:2*pi]; X = sin (T);
      plot (T, X);
      # you should now see a sine wave in your figure window

     Press <enter> to continue:

   Note that demo blocks cannot use any shared variables.  This is so
that they can be executed by themselves, ignoring all other tests.

   If you want to temporarily disable a test block, put ‘#’ in place of
the block type.  This creates a comment block which is echoed in the log
file but not executed.  For example:

     %!#demo
     %! T = [0:0.01:2*pi]; X = sin (T);
     %! plot (T, X);
     %! # you should now see a sine wave in your figure window

The following trivial code snippet provides examples for the use of
fail, assert, error and xtest:

     function output = must_be_zero (INPUT)
       if (INPUT != 0)
         error ("Nonzero input!")
       endif
       output = input;
     endfunction

     %!fail ("must_be_zero (1)");
     %!assert (must_be_zero (0), 0);
     %!error <Nonzero> must_be_zero (1);
     %!xtest error ("This code generates an error");

When putting this a file ‘must_be_zero.m’, and running the test, we see

     test must_be_zero verbose

     ⇒
     >>>>> /path/to/must_be_zero.m
       ***** fail ("must_be_zero (1)");
       ***** assert (must_be_zero (0), 0);
       ***** error <Nonzero> must_be_zero (1);
       ***** xtest error ("This code generates an error");
     !!!!! known failure
     This code generates an error
     PASSES 4 out of 4 tests (1 expected failures)

Block type summary:
...................

‘%!test’
     check that entire block is correct

‘%!testif HAVE_XXX’
     check block only if Octave was compiled with feature HAVE_XXX.

‘%!xtest’
     check block, report a test failure but do not abort testing.

‘%!error’
     check for correct error message

‘%!warning’
     check for correct warning message

‘%!demo’
     demo only executes in interactive mode

‘%!#’
     comment: ignore everything within the block

‘%!shared x,y,z’
     declare variables for use in multiple tests

‘%!function’
     define a function for use in multiple tests

‘%!endfunction’
     close a function definition

‘%!assert (x, y, tol)’
     shorthand for ‘%!test assert (x, y, tol)’

   You can also create test scripts for built-in functions and your own
C++ functions.  To do so, put a file with the bare function name (no .m
extension) in a directory in the load path and it will be discovered by
the ‘test’ function.  Alternatively, you can embed tests directly in
your C++ code:

     /*
     %!test disp ("this is a test")
     */

or

     #if 0
     %!test disp ("this is a test")
     #endif

However, in this case the raw source code will need to be on the load
path and the user will have to remember to type ‘test ("funcname.cc")’.

 -- Function File: assert (COND)
 -- Function File: assert (COND, ERRMSG)
 -- Function File: assert (COND, ERRMSG, ...)
 -- Function File: assert (COND, MSG_ID, ERRMSG, ...)
 -- Function File: assert (OBSERVED, EXPECTED)
 -- Function File: assert (OBSERVED, EXPECTED, TOL)

     Produce an error if the specified condition is not met.

     ‘assert’ can be called in three different ways.

     ‘assert (COND)’
     ‘assert (COND, ERRMSG)’
     ‘assert (COND, ERRMSG, ...)’
     ‘assert (COND, MSG_ID, ERRMSG, ...)’
          Called with a single argument COND, ‘assert’ produces an error
          if COND is false (numeric zero).

          Any additional arguments are passed to the ‘error’ function
          for processing.

     ‘assert (OBSERVED, EXPECTED)’
          Produce an error if observed is not the same as expected.

          Note that OBSERVED and EXPECTED can be scalars, vectors,
          matrices, strings, cell arrays, or structures.

     ‘assert (OBSERVED, EXPECTED, TOL)’
          Produce an error if observed is not the same as expected but
          equality comparison for numeric data uses a tolerance TOL.

          If TOL is positive then it is an absolute tolerance which will
          produce an error if ‘abs (OBSERVED - EXPECTED) > abs (TOL)’.

          If TOL is negative then it is a relative tolerance which will
          produce an error if ‘abs (OBSERVED - EXPECTED) > abs (TOL *
          EXPECTED)’.

          If EXPECTED is zero TOL will always be interpreted as an
          absolute tolerance.

          If TOL is not scalar its dimensions must agree with those of
          OBSERVED and EXPECTED and tests are performed on an
          element-by-element basis.

     See also: *note fail: XREFfail, *note test: XREFtest, *note error:
     XREFerror, *note isequal: XREFisequal.

 -- Function File: fail (CODE)
 -- Function File: fail (CODE, PATTERN)
 -- Function File: fail (CODE, "warning")
 -- Function File: fail (CODE, "warning", PATTERN)

     Return true if CODE fails with an error message matching PATTERN,
     otherwise produce an error.

     CODE must be in the form of a string that is passed to the Octave
     interpreter via the ‘evalin’ function, i.e., a (quoted) string
     constant or a string variable.

     Note that if CODE runs successfully, rather than failing, the error
     printed is:

                    expected error <.> but got none

     If called with two arguments, the return value will be true only if
     CODE fails with an error message containing PATTERN (case
     sensitive).  If the code fails with a different error than the one
     specified in PATTERN then the message produced is:

                    expected <PATTERN>
                    but got <text of actual error>

     The angle brackets are not part of the output.

     When called with the "warning" option ‘fail’ will produce an error
     if executing the code produces no warning.

     See also: *note assert: XREFassert, *note error: XREFerror.


File: octave.info,  Node: Demonstration Functions,  Prev: Test Functions,  Up: Test and Demo Functions

B.2 Demonstration Functions
===========================

 -- Command: demo NAME
 -- Command: demo NAME N
 -- Function File: demo ("NAME")
 -- Function File: demo ("NAME", N)

     Run example code block N associated with the function NAME.

     If N is not specified, all examples are run.

     The preferred location for example code blocks is embedded within
     the script m-file immediately following the code that it exercises.
     Alternatively, the examples may be stored in a file with the same
     name but no extension located on Octave’s load path.  To separate
     examples from regular script code all lines are prefixed by ‘%!’.
     Each example must also be introduced by the keyword "demo" flush
     left to the prefix with no intervening spaces.  The remainder of
     the example can contain arbitrary Octave code.  For example:

          %!demo
          %! t = 0:0.01:2*pi;
          %! x = sin (t);
          %! plot (t, x);
          %! title ("one cycle of a sine wave");
          %! #-------------------------------------------------
          %! # the figure window shows one cycle of a sine wave

     Note that the code is displayed before it is executed so that a
     simple comment at the end suffices for labeling what is being
     shown.  For plots, labeling can also be done with ‘title’ or
     ‘text’.  It is generally *not* necessary to use ‘disp’ or ‘printf’
     within the demo.

     Demos are run in a stand-alone function environment with no access
     to external variables.  This means that every demo must have
     separate initialization code.  Alternatively, all demos can be
     combined into a single large demo with the code

          %! input ("Press <enter> to continue: ", "s");

     between the sections, but this usage is discouraged.  Other
     techniques to avoid multiple initialization blocks include using
     multiple plots with a new ‘figure’ command between each plot, or
     using ‘subplot’ to put multiple plots in the same window.

     Finally, because ‘demo’ evaluates within a function context it is
     not possible to define new functions within the code.  Anonymous
     functions make a good substitute in most instances.  If function
     blocks *must* be used then the code ‘eval (example ("function",
     n))’ will allow Octave to see them.  This has its own problems,
     however, as ‘eval’ only evaluates one line or statement at a time.
     In this case the function declaration must be wrapped with "if 1
     <demo stuff> endif" where "if" is on the same line as "demo".  For
     example:

          %!demo if 1
          %!  function y = f(x)
          %!    y = x;
          %!  endfunction
          %!  f(3)
          %! endif

     See also: *note rundemos: XREFrundemos, *note example: XREFexample,
     *note test: XREFtest.

 -- Command: example NAME
 -- Command: example NAME N
 -- Function File: example ("NAME")
 -- Function File: example ("NAME", N)
 -- Function File: [S, IDX] = example (...)

     Display the code for example N associated with the function NAME,
     but do not run it.

     If N is not specified, all examples are displayed.

     When called with output arguments, the examples are returned in the
     form of a string S, with IDX indicating the ending position of the
     various examples.

     See ‘demo’ for a complete explanation.

     See also: *note demo: XREFdemo, *note test: XREFtest.

 -- Function File: rundemos ()
 -- Function File: rundemos (DIRECTORY)
     Execute built-in demos for all m-files in the specified DIRECTORY.

     Demo blocks in any C++ source files (‘*.cc’) will also be executed
     for use with dynamically linked oct-file functions.

     If no directory is specified, operate on all directories in
     Octave’s search path for functions.

     See also: *note demo: XREFdemo, *note runtests: XREFruntests, *note
     path: XREFpath.

 -- Function File: runtests ()
 -- Function File: runtests (DIRECTORY)
     Execute built-in tests for all m-files in the specified DIRECTORY.

     Test blocks in any C++ source files (‘*.cc’) will also be executed
     for use with dynamically linked oct-file functions.

     If no directory is specified, operate on all directories in
     Octave’s search path for functions.

     See also: *note rundemos: XREFrundemos, *note test: XREFtest, *note
     path: XREFpath.

 -- Function File: speed (F, INIT, MAX_N, F2, TOL)
 -- Function File: [ORDER, N, T_F, T_F2] = speed (...)

     Determine the execution time of an expression (F) for various input
     values (N).

     The N are log-spaced from 1 to MAX_N.  For each N, an
     initialization expression (INIT) is computed to create any data
     needed for the test.  If a second expression (F2) is given then the
     execution times of the two expressions are compared.  When called
     without output arguments the results are printed to stdout and
     displayed graphically.

     ‘F’
          The code expression to evaluate.

     ‘MAX_N’
          The maximum test length to run.  The default value is 100.
          Alternatively, use ‘[min_n, max_n]’ or specify the N exactly
          with ‘[n1, n2, ..., nk]’.

     ‘INIT’
          Initialization expression for function argument values.  Use K
          for the test number and N for the size of the test.  This
          should compute values for all variables used by F.  Note that
          INIT will be evaluated first for k = 0, so things which are
          constant throughout the test series can be computed once.  The
          default value is ‘X = randn (N, 1)’.

     ‘F2’
          An alternative expression to evaluate, so that the speed of
          two expressions can be directly compared.  The default is
          ‘[]’.

     ‘TOL’
          Tolerance used to compare the results of expression F and
          expression F2.  If TOL is positive, the tolerance is an
          absolute one.  If TOL is negative, the tolerance is a relative
          one.  The default is ‘eps’.  If TOL is ‘Inf’, then no
          comparison will be made.

     ‘ORDER’
          The time complexity of the expression O(a*n^p).  This is a
          structure with fields ‘a’ and ‘p’.

     ‘N’
          The values N for which the expression was calculated *AND* the
          execution time was greater than zero.

     ‘T_F’
          The nonzero execution times recorded for the expression F in
          seconds.

     ‘T_F2’
          The nonzero execution times recorded for the expression F2 in
          seconds.  If required, the mean time ratio is simply ‘mean
          (T_f ./ T_f2)’.

     The slope of the execution time graph shows the approximate power
     of the asymptotic running time O(n^p).  This power is plotted for
     the region over which it is approximated (the latter half of the
     graph).  The estimated power is not very accurate, but should be
     sufficient to determine the general order of an algorithm.  It
     should indicate if, for example, the implementation is unexpectedly
     O(n^2) rather than O(n) because it extends a vector each time
     through the loop rather than pre-allocating storage.  In the
     current version of Octave, the following is not the expected O(n).

          speed ("for i = 1:n, y{i} = x(i); endfor", "", [1000, 10000])

     But it is if you preallocate the cell array ‘y’:

          speed ("for i = 1:n, y{i} = x(i); endfor", ...
                 "x = rand (n, 1); y = cell (size (x));", [1000, 10000])

     An attempt is made to approximate the cost of individual
     operations, but it is wildly inaccurate.  You can improve the
     stability somewhat by doing more work for each ‘n’.  For example:

          speed ("airy(x)", "x = rand (n, 10)", [10000, 100000])

     When comparing two different expressions (F, F2), the slope of the
     line on the speedup ratio graph should be larger than 1 if the new
     expression is faster.  Better algorithms have a shallow slope.
     Generally, vectorizing an algorithm will not change the slope of
     the execution time graph, but will shift it relative to the
     original.  For example:

          speed ("sum (x)", "", [10000, 100000], ...
                 "v = 0; for i = 1:length (x), v += x(i); endfor")

     The following is a more complex example.  If there was an original
     version of ‘xcorr’ using for loops and a second version using an
     FFT, then one could compare the run speed for various lags as
     follows, or for a fixed lag with varying vector lengths as follows:

          speed ("xcorr (x, n)", "x = rand (128, 1);", 100,
                 "xcorr_orig (x, n)", -100*eps)
          speed ("xcorr (x, 15)", "x = rand (20+n, 1);", 100,
                 "xcorr_orig (x, n)", -100*eps)

     Assuming one of the two versions is in xcorr_orig, this would
     compare their speed and their output values.  Note that the FFT
     version is not exact, so one must specify an acceptable tolerance
     on the comparison ‘100*eps’.  In this case, the comparison should
     be computed relatively, as ‘abs ((X - Y) ./ Y)’ rather than
     absolutely as ‘abs (X - Y)’.

     Type ‘example ("speed")’ to see some real examples or ‘demo
     ("speed")’ to run them.


File: octave.info,  Node: Tips and Standards,  Next: Contributing Guidelines,  Prev: Test and Demo Functions,  Up: Top

Appendix C Tips and Standards
*****************************

This chapter describes no additional features of Octave.  Instead it
gives advice on making effective use of the features described in the
previous chapters.

* Menu:

* Style Tips::                  Writing clean and robust programs.
* Comment Tips::                Conventions for writing comments.
* Function Headers::            Standard headers for functions.
* Documentation Tips::          Writing readable documentation strings.


File: octave.info,  Node: Style Tips,  Next: Comment Tips,  Up: Tips and Standards

C.1 Writing Clean Octave Programs
=================================

Here are some tips for avoiding common errors in writing Octave code
intended for widespread use:

   • Since all global variables share the same name space, and all
     functions share another name space, you should choose a short word
     to distinguish your program from other Octave programs.  Then take
     care to begin the names of all global variables, constants, and
     functions with the chosen prefix.  This helps avoid name conflicts.

     If you write a function that you think ought to be added to Octave
     under a certain name, such as ‘fiddle_matrix’, don’t call it by
     that name in your program.  Call it ‘mylib_fiddle_matrix’ in your
     program, and send mail to <maintainers@octave.org> suggesting that
     it be added to Octave.  If and when it is, the name can be changed
     easily enough.

     If one prefix is insufficient, your package may use two or three
     alternative common prefixes, so long as they make sense.

     Separate the prefix from the rest of the symbol name with an
     underscore ‘_’.  This will be consistent with Octave itself and
     with most Octave programs.

   • When you encounter an error condition, call the function ‘error’
     (or ‘usage’).  The ‘error’ and ‘usage’ functions do not return.
     *Note Errors::.

   • Please put a copyright notice on the file if you give copies to
     anyone.  Use the same lines that appear at the top of the function
     files distributed with Octave.  If you have not signed papers to
     assign the copyright to anyone else, then place your name in the
     copyright notice.


File: octave.info,  Node: Comment Tips,  Next: Function Headers,  Prev: Style Tips,  Up: Tips and Standards

C.2 Tips on Writing Comments
============================

Here are the conventions to follow when writing comments.

‘#’
     Comments that start with a single sharp-sign, ‘#’, should all be
     aligned to the same column on the right of the source code.  Such
     comments usually explain how the code on the same line does its
     job.  In the Emacs mode for Octave, the ‘M-;’
     (‘indent-for-comment’) command automatically inserts such a ‘#’ in
     the right place, or aligns such a comment if it is already present.

‘##’
     Comments that start with a double sharp-sign, ‘##’, should be
     aligned to the same level of indentation as the code.  Such
     comments usually describe the purpose of the following lines or the
     state of the program at that point.

The indentation commands of the Octave mode in Emacs, such as ‘M-;’
(‘indent-for-comment’) and ‘TAB’ (‘octave-indent-line’) automatically
indent comments according to these conventions, depending on the number
of semicolons.  *Note Manipulating Comments: (emacs)Comments.


File: octave.info,  Node: Function Headers,  Next: Documentation Tips,  Prev: Comment Tips,  Up: Tips and Standards

C.3 Conventional Headers for Octave Functions
=============================================

Octave has conventions for using special comments in function files to
give information such as who wrote them.  This section explains these
conventions.

   The top of the file should contain a copyright notice, followed by a
block of comments that can be used as the help text for the function.
Here is an example:

     ## Copyright (C) 1996, 1997, 2007 John W. Eaton
     ##
     ## This file is part of Octave.
     ##
     ## Octave is free software; you can redistribute it and/or
     ## modify it under the terms of the GNU General Public
     ## License as published by the Free Software Foundation;
     ## either version 3 of the License, or (at your option) any
     ## later version.
     ##
     ## Octave is distributed in the hope that it will be useful,
     ## but WITHOUT ANY WARRANTY; without even the implied
     ## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     ## PURPOSE.  See the GNU General Public License for more
     ## details.
     ##
     ## You should have received a copy of the GNU General Public
     ## License along with Octave; see the file COPYING.  If not,
     ## see <http://www.gnu.org/licenses/>.

     ## usage: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     ##
     ## Start a subprocess with two-way communication.  COMMAND
     ## specifies the name of the command to start.  ARGS is an
     ## array of strings containing options for COMMAND.  IN and
     ## OUT are the file ids of the input and streams for the
     ## subprocess, and PID is the process id of the subprocess,
     ## or -1 if COMMAND could not be executed.
     ##
     ## Example:
     ##
     ##  [in, out, pid] = popen2 ("sort", "-nr");
     ##  fputs (in, "these\nare\nsome\nstrings\n");
     ##  fclose (in);
     ##  while (ischar (s = fgets (out)))
     ##    fputs (stdout, s);
     ##  endwhile
     ##  fclose (out);

   Octave uses the first block of comments in a function file that do
not appear to be a copyright notice as the help text for the file.  For
Octave to recognize the first comment block as a copyright notice, it
must start with the word ‘Copyright’ after stripping the leading comment
characters.

   After the copyright notice and help text come several “header
comment” lines, each beginning with ‘## HEADER-NAME:’.  For example,

     ## Author: jwe
     ## Keywords: subprocesses input-output
     ## Maintainer: jwe

   Here is a table of the conventional possibilities for HEADER-NAME:

‘Author’
     This line states the name and net address of at least the principal
     author of the library.

          ## Author: John W. Eaton <jwe@octave.org>

‘Maintainer’
     This line should contain a single name/address as in the Author
     line, or an address only, or the string ‘jwe’.  If there is no
     maintainer line, the person(s) in the Author field are presumed to
     be the maintainers.  The example above is mildly bogus because the
     maintainer line is redundant.

     The idea behind the ‘Author’ and ‘Maintainer’ lines is to make
     possible a function to “send mail to the maintainer” without having
     to mine the name out by hand.

     Be sure to surround the network address with ‘<...>’ if you include
     the person’s full name as well as the network address.

‘Created’
     This optional line gives the original creation date of the file.
     For historical interest only.

‘Version’
     If you wish to record version numbers for the individual Octave
     program, put them in this line.

‘Adapted-By’
     In this header line, place the name of the person who adapted the
     library for installation (to make it fit the style conventions, for
     example).

‘Keywords’
     This line lists keywords.  Eventually, it will be used by an
     apropos command to allow people will find your package when they’re
     looking for things by topic area.  To separate the keywords, you
     can use spaces, commas, or both.

   Just about every Octave function ought to have the ‘Author’ and
‘Keywords’ header comment lines.  Use the others if they are
appropriate.  You can also put in header lines with other header
names—they have no standard meanings, so they can’t do any harm.


File: octave.info,  Node: Documentation Tips,  Prev: Function Headers,  Up: Tips and Standards

C.4 Tips for Documentation Strings
==================================

As noted above, documentation is typically in a commented header block
on an Octave function following the copyright statement.  The help
string shown above is an unformatted string and will be displayed as is
by Octave.  Here are some tips for the writing of documentation strings.

   • Every command, function, or variable intended for users to know
     about should have a documentation string.

   • An internal variable or subroutine of an Octave program might as
     well have a documentation string.

   • The first line of the documentation string should consist of a
     summary of the function.

     Subsequent lines may expand the general nature of the function.

     After the introduction there should be paragraphs describing the
     meaning and usage of each input, followed by the meaning and usage
     of each output.

     Finally, there may be more general information such as notes about
     the algorithm used, references to scientific papers, notes about
     any incompatibilities with MATLAB, etc.

   • For consistency, phrase the verb in the first sentence of a
     documentation string as an infinitive with “to” omitted.  For
     instance, use “Return the frob of A and B.” in preference to
     “Returns the frob of A and B.” Usually it looks good to do likewise
     for the rest of the first paragraph.  Subsequent paragraphs usually
     look better if they have proper subjects.

   • Write documentation strings in the active voice, not the passive,
     and in the present tense, not the future.  For instance, use
     “Return a list containing A and B.” instead of “A list containing A
     and B will be returned.”

   • Avoid using the word “cause” (or its equivalents) unnecessarily.
     Instead of, “Cause Octave to display text in boldface,” just write
     “Display text in boldface.”

   • Use two spaces between the period marking the end of a sentence and
     the word which opens the next sentence.  This convention has no
     effect for typeset formats like TeX, but improves the readability
     of the documentation in fixed-width environments such as the Info
     reader.

   • Do not start or end a documentation string with whitespace.

   • Format the documentation string so that it fits within an 80-column
     screen.  It is a good idea for most lines to be no wider than 60
     characters.

     However, rather than simply filling the entire documentation
     string, you can make it much more readable by choosing line breaks
     with care.  Use blank lines between topics if the documentation
     string is long.

   • *Do not* indent subsequent lines of a documentation string so that
     the text is lined up in the source code with the text of the first
     line.  This looks nice in the source code, but looks bizarre when
     users view the documentation.  Remember that the indentation before
     the starting double-quote is not part of the string!

   • When choosing variable names try to adhere to the following
     guidelines.

     vectors :
          x,y,z,t,w

     matrices :
          A,B,M

     strings :
          str,s

     filenames :
          fname

     cells,cellstrs :
          c,cstr

   • The documentation string for a variable that is a yes-or-no flag
     should start with words such as “Nonzero means...”, to make it
     clear that all nonzero values are equivalent and indicate
     explicitly what zero and nonzero mean.

   • When a function’s documentation string mentions the value of an
     argument of the function, use the argument name in capital letters
     as if it were a name for that value.  Thus, the documentation
     string of the operator ‘/’ refers to its second argument as
     ‘DIVISOR’, because the actual argument name is ‘divisor’.

     Also use all caps for meta-syntactic variables, such as when you
     show the decomposition of a list or vector into subunits, some of
     which may vary.

   Octave also allows extensive formatting of the help string of
functions using Texinfo.  The effect on the online documentation is
relatively small, but makes the help string of functions conform to the
help of Octave’s own functions.  However, the effect on the appearance
of printed or online documentation will be greatly improved.

   The fundamental building block of Texinfo documentation strings is
the Texinfo-macro ‘@deftypefn’, which takes three arguments: The class
the function is in, its output arguments, and the function’s signature.
Typical classes for functions include ‘Function File’ for standard
Octave functions, and ‘Loadable Function’ for dynamically linked
functions.  A skeletal Texinfo documentation string therefore looks like
this

     -*- texinfo -*-
     @deftypefn {Function File} {@var{ret} =} fn (...)
     @cindex index term
     Help text in Texinfo format.  Code samples should be marked
     like @code{sample of code} and variables should be marked
     as @var{variable}.
     @seealso{fn2, fn3}
     @end deftypefn

   This help string must be commented in user functions, or in the help
string of the ‘DEFUN_DLD’ macro for dynamically loadable functions.  The
important aspects of the documentation string are

-*- texinfo -*-
     This string signals Octave that the following text is in Texinfo
     format, and should be the first part of any help string in Texinfo
     format.

@deftypefn {class} ... @end deftypefn
     The entire help string should be enclosed within the block defined
     by deftypefn.

@cindex index term
     This generates an index entry, and can be useful when the function
     is included as part of a larger piece of documentation.  It is
     ignored within Octave’s help viewer.  Only one index term may
     appear per line but multiple @cindex lines are valid if the
     function should be filed under different terms.

@var{variable}
     All variables should be marked with this macro.  The markup of
     variables is then changed appropriately for display.

@code{sample of code}
     All samples of code should be marked with this macro for the same
     reasons as the @var macro.

@qcode{"sample_code"}
@qcode{’sample_code’}
     All samples of code which are quoted should use this more
     specialized macro.  This happens frequently when discussing
     graphics properties such as "position" or options such as
     "on"/"off".

@seealso{function2, function3}
     This is a comma separated list of function names that allows cross
     referencing from one function documentation string to another.

   Texinfo format has been designed to generate output for online
viewing with text terminals as well as generating high-quality printed
output.  To these ends, Texinfo has commands which control the diversion
of parts of the document into a particular output processor.  Three
formats are of importance: info, HTML, and TeX.  These are selected with

     @ifinfo
     Text area for info only
     @end ifinfo

     @ifhtml
     Text area for HTML only
     @end ifhtml

     @tex
     Text area for TeX only
     @end tex

   Note that often TeX output can be used in HTML documents and so often
the ‘@ifhtml’ blocks are unnecessary.  If no specific output processor
is chosen, by default, the text goes into all output processors.  It is
usual to have the above blocks in pairs to allow the same information to
be conveyed in all output formats, but with a different markup.
Currently, most Octave documentation only makes a distinction between
TeX and all other formats.  Therefore, the following construct is seen
repeatedly.

     @tex
     text for TeX only
     @end tex
     @ifnottex
     text for info, HTML, plaintext
     @end ifnottex

   Another important feature of Texinfo that is often used in Octave
help strings is the ‘@example’ environment.  An example of its use is

     @example
     @group
     @code{2 * 2}
     @result{} 4
     @end group
     @end example

which produces

     2 * 2
     ⇒ 4

   The ‘@group’ block prevents the example from being split across a
page boundary, while the ‘@result{}’ macro produces a right arrow
signifying the result of a command.  If your example is larger than 20
lines it is better _NOT_ to use grouping so that a reasonable page
boundary can be calculated.

   In many cases a function has multiple ways in which it can be called,
and the ‘@deftypefnx’ macro can be used to give alternatives.  For
example

     -*- texinfo -*-
     @deftypefn  {Function File} {@var{a} =} fn (@var{x}, ...)
     @deftypefnx {Function File} {@var{a} =} fn (@var{y}, ...)
     Help text in Texinfo format.
     @end deftypefn

   Many complete examples of Texinfo documentation can be taken from the
help strings for the Octave functions themselves.  A relatively complete
example of which is the ‘nchoosek’ function.  The Texinfo documentation
string for ‘nchoosek’ is

     -*- texinfo -*-
     @deftypefn  {Function File} {@var{c} =} nchoosek (@var{n}, @var{k})
     @deftypefnx {Function File} {@var{c} =} nchoosek (@var{set}, @var{k})

     Compute the binomial coefficient of @var{n} or list all possible
     combinations of a @var{set} of items.

     If @var{n} is a scalar then calculate the binomial coefficient
     of @var{n} and @var{k} which is defined as
     @tex
     $$
      {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!}
                    = {n! \over k! (n-k)!}
     $$
     @end tex
     @ifnottex

     @example
     @group
      /   \
      | n |    n (n-1) (n-2) @dots{} (n-k+1)       n!
      |   |  = ------------------------- =  ---------
      | k |               k!                k! (n-k)!
      \   /
     @end group
     @end example

     @end ifnottex
     @noindent
     This is the number of combinations of @var{n} items taken in groups of
     size @var{k}.

     If the first argument is a vector, @var{set}, then generate all
     combinations of the elements of @var{set}, taken @var{k} at a time, with
     one row per combination.  The result @var{c} has @var{k} columns and
     @w{@code{nchoosek (length (@var{set}), @var{k})}} rows.

     For example:

     How many ways can three items be grouped into pairs?

     @example
     @group
     nchoosek (3, 2)
        @result{} 3
     @end group
     @end example

     What are the possible pairs?

     @example
     @group
     nchoosek (1:3, 2)
        @result{}  1   2
            1   3
            2   3
     @end group
     @end example

     Programming Note: When calculating the binomial coefficient @code{nchoosek}
     works only for non-negative, integer arguments.  Use @code{bincoeff} for
     non-integer and negative scalar arguments, or for computing many binomial
     coefficients at once with vector inputs for @var{n} or @var{k}.

     @seealso{bincoeff, perms}
     @end deftypefn

which demonstrates most of the concepts discussed above.


File: octave.info,  Node: Contributing Guidelines,  Next: Obsolete Functions,  Prev: Tips and Standards,  Up: Top

Appendix D Contributing Guidelines
**********************************

This chapter is dedicated to those who wish to contribute code to
Octave.

* Menu:

* How to Contribute::
* Building the Development Sources::
* Basics of Generating a Changeset::
* General Guidelines::
* Octave Sources (m-files)::
* C++ Sources::
* Other Sources::


File: octave.info,  Node: How to Contribute,  Next: Building the Development Sources,  Up: Contributing Guidelines

D.1 How to Contribute
=====================

The mailing list for Octave development discussions is
<maintainers@octave.org>.  Patches should be submitted to Octave’s patch
tracker (https://savannah.gnu.org/patch/?func=additem&group=octave).
This concerns the development of Octave core, i.e., code that goes in to
Octave directly.  You may consider developing and publishing a package
instead; a great place for this is the allied Octave-Forge project
(<http://octave.sourceforge.net>).  Note that the Octave core project is
inherently more conservative and follows narrower rules.


File: octave.info,  Node: Building the Development Sources,  Next: Basics of Generating a Changeset,  Prev: How to Contribute,  Up: Contributing Guidelines

D.2 Building the Development Sources
====================================

The directions for building from the development sources change from
time to time, so you should read the resources for developers on the web
or in the development sources archive.  Start here:
<http://www.octave.org/get-involved.html>.


File: octave.info,  Node: Basics of Generating a Changeset,  Next: General Guidelines,  Prev: Building the Development Sources,  Up: Contributing Guidelines

D.3 Basics of Generating a Changeset
====================================

The best way to contribute is to create a Mercurial changeset and submit
it to the bug (http://savannah.gnu.org/bugs/?group=octave) or patch
(http://savannah.gnu.org/patch/?func=additem&group=octave) trackers(1).
Mercurial is the source code management system currently used to develop
Octave.  Other forms of contributions (e.g., simple diff patches) are
also acceptable, but they slow down the review process.  If you want to
make more contributions, you should really get familiar with Mercurial.
A good place to start is
<http://www.selenic.com/mercurial/wiki/index.cgi/Tutorial>.  There you
will also find help about how to install Mercurial.

   A simple contribution sequence could look like this:

     hg clone http://www.octave.org/hg/octave
                                  # make a local copy of the octave
                                  # source repository
     cd octave
     # change some sources...
     hg commit -m "make Octave the coolest software ever"
                                  # commit the changeset into your
                                  # local repository
     hg export -o ../cool.diff tip
                                  # export the changeset to a diff
                                  # file
     # attach ../cool.diff to your bug report

   You may want to get familiar with Mercurial queues to manage your
changesets.  To work with queues you must activate the extension mq with
the following entry in Mercurial’s configuration file ‘.hgrc’ (or
‘Mercurial.ini’ on Windows):

     [extensions]
     mq=

   Here is a slightly more complex example using Mercurial queues, where
work on two unrelated changesets is done in parallel and one of the
changesets is updated after discussion on the bug tracker:

     hg qnew nasty_bug            # create a new patch
     # change sources...
     hg qref                      # save the changes into the patch
     # change even more...
     hg qref -m "solution to nasty bug!"
                                  # save again with commit message
     hg export -o ../nasty.diff tip
                                  # export the patch
     # attach ../nasty.diff to your bug report
     hg qpop                      # undo the application of the patch
                                  # and remove the changes from the
                                  # source tree
     hg qnew doc_improvements     # create an unrelated patch
     # change doc sources...
     hg qref -m "could not find myfav.m in the doc"
                                  # save the changes into the patch
     hg export -o ../doc.diff tip
                                  # export the second patch
     # attach ../doc.diff to your bug report
     hg qpop
     # discussion in the bug tracker ...
     hg qpush nasty_bug           # apply the patch again
     # change sources yet again ...
     hg qref
     hg export -o ../nasty2.diff tip
     # attach ../nasty2.diff to your bug report

   Mercurial has a few more useful extensions that really should be
enabled.  They are not enabled by default due to a number of factors
(mostly because they don’t work in all terminal types).

   The following entries in the ‘.hgrc’ are recommended

     [extensions]
     graphlog=
     color=
     progress=
     pager=

   For the color extension, default color and formatting of ‘hg status’
can be modified by

     [color]
     status.modified = magenta bold
     status.added = green bold
     status.removed = red bold
     status.deleted = cyan bold
     status.unknown = black  bold
     status.ignored = black bold

   Sometimes a few further improvements for the pager extension are
necessary.  The following options should not be enabled unless paging is
not working correctly.

     [pager]
     # Some options for the less pager, see less(1) for their meaning.
     pager = LESS='FSRX' less

     # Some commands that aren't paged by default; also enable paging
     # for them
     attend = tags, help, annotate, cat, diff, export, status, \
              outgoing, incoming

   Enabling the described extensions should immediately lead to a
difference when using the command line version of hg.  Of these options,
the only one that enables a new command is graphlog.  It is recommanded
that to use the command ‘hg glog’, instead of ‘hg log’, for a better
feel about what commits are being based on.

   ---------- Footnotes ----------

   (1) Please use the patch tracker only for patches which add new
features.  If you have a patch to submit that fixes a bug, you should
use the bug tracker instead.


File: octave.info,  Node: General Guidelines,  Next: Octave Sources (m-files),  Prev: Basics of Generating a Changeset,  Up: Contributing Guidelines

D.4 General Guidelines
======================

All Octave’s sources are distributed under the GNU General Public
License (GPL). Currently, Octave uses GPL version 3.  For details about
this license, see <http://www.gnu.org/licenses/gpl.html>.  Therefore,
whenever you create a new source file, it should have the following
comment header (use appropriate year, name and comment marks):

     ## Copyright (C) 1996-2015 John W. Eaton <jwe@octave.org>
     ##
     ## This file is part of Octave.
     ##
     ## Octave is free software; you can redistribute it and/or modify it
     ## under the terms of the GNU General Public License as published by
     ## the Free Software Foundation; either version 3 of the License, or
     ## (at your option) any later version.
     ##
     ## Octave is distributed in the hope that it will be useful, but
     ## WITHOUT ANY WARRANTY; without even the implied warranty of
     ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     ## GNU General Public License for more details.
     ##
     ## You should have received a copy of the GNU General Public License
     ## along with Octave; see the file COPYING.  If not,
     ## see <http://www.gnu.org/licenses/>.

   Always include commit messages in changesets.  After making your
source changes, record and briefly describe the changes in your commit
message.  You should have previously configured your ‘.hgrc’ (or
‘Mercurial.ini’ on Windows) with your name and email, which will be
automatically added to your commit message.  Your commit message should
have a brief one-line explanation of what the commit does.  If you are
patching a bug, this one-line explanation should mention the bug number
at the end.  If your change is small and only touches one file then this
is typically sufficient.  If you are modifying several files, or several
parts of one file, you should enumerate your changes roughly following
the GNU coding standards for changelogs, as in the following example:

     look for methods before constructors

     * symtab.cc (symbol_table::fcn_info::fcn_info_rep::find):
     Look for class methods before constructors, contrary to MATLAB
     documentation.

     * test/ctor-vs-method: New directory of test classes.
     * test/test_ctor_vs_method.m: New file.
     * test/Makefile.am: Include ctor-vs-method/module.mk.
     (FCN_FILES): Include test_ctor_vs_method.m in the list.

In this example, the names of the file changed is listed first, and in
parentheses the name of the function in that file that was modified.
There is no need to mention the function for m-files that only contain
one function.  The commit message should describe what was changed, not
why it was changed.  Any explanation for why a change is needed should
appear as comments in the code, particularly if there is something that
might not be obvious to someone reading it later.

   When submitting code which addresses a known bug on the Octave bug
tracker (<http://bugs.octave.org>), please add ’(bug #XXXXX)’ to the
first line of the commit messages.  For example:

     Fix bug for complex input for gradient (bug #34292).

   The preferred comment mark for places that may need further attention
is ‘FIXME:’.


File: octave.info,  Node: Octave Sources (m-files),  Next: C++ Sources,  Prev: General Guidelines,  Up: Contributing Guidelines

D.5 Octave Sources (m-files)
============================

Don’t use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Indent the bodies of
statement blocks.  The recommended indent is 2 spaces.  When calling
functions, put spaces after commas and before the calling parentheses,
like this:

       x = max (sin (y+3), 2);

An exception are matrix or cell constructors:

       [sin(x), cos(x)]
       {sin(x), cos(x)}

Here, putting spaces after ‘sin’, ‘cos’ would result in a parse error.
For an indexing expression, do not put a space after the identifier
(this differentiates indexing and function calls nicely).  The space
after a comma is not necessary if index expressions are simple, i.e.,
you may write

       A(:,i,j)

but

       A([1:i-1;i+1:n], XI(:,2:n-1))

   Use lowercase names if possible.  Uppercase is acceptable for
variable names consisting of 1-2 letters.  Do not use mixed case names.
Function names must be lowercase.  Function names are global, so choose
them wisely.

   Always use a specific end-of-block statement (like ‘endif’,
‘endswitch’) rather than the generic ‘end’.

   Enclose the ‘if’, ‘while’, ‘until’, and ‘switch’ conditions in
parentheses, as in C:

     if (isvector (a))
       s = sum (a);
     endif

Do not do this, however, with the iteration counter portion of a ‘for’
statement.  Write:

     for i = 1:n
       b(i) = sum (a(:,i));
     endfor


File: octave.info,  Node: C++ Sources,  Next: Other Sources,  Prev: Octave Sources (m-files),  Up: Contributing Guidelines

D.6 C++ Sources
===============

Don’t use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Format function headers
like this:

     static bool
     matches_patterns (const string_vector& patterns, int pat_idx,
                       int num_pat, const std::string& name)

The function name should start in column 1, and multi-line argument
lists should be aligned on the first char after the open parenthesis.
You should put a space before the left open parenthesis and after
commas, for both function definitions and function calls.

   The recommended indent is 2 spaces.  When indenting, indent the
statement after control structures (like ‘if’, ‘while’, etc.).  If there
is a compound statement, indent _both_ the curly braces and the body of
the statement (so that the body gets indented by _two_ indents).
Example:

     if (have_args)
       {
         idx.push_back (first_args);
         have_args = false;
       }
     else
       idx.push_back (make_value_list (*p_args, *p_arg_nm, &tmp));

If you have nested ‘if’ statements, use extra braces for extra
clarification.

   Split long expressions in such a way that a continuation line starts
with an operator rather than identifier.  If the split occurs inside
braces, continuation should be aligned with the first char after the
innermost braces enclosing the split.  Example:

     SVD::type type = ((nargout == 0 || nargout == 1)
                       ? SVD::sigma_only
                       : (nargin == 2) ? SVD::economy : SVD::std);

Consider putting extra braces around a multi-line expression to make it
more readable, even if they are not necessary.  Also, do not hesitate to
put extra braces anywhere if it improves clarity.

   Declare variables just before they are needed.  Use local variables
of blocks—it helps optimization.  Don’t write a multi-line variable
declaration with a single type specification and multiple variables.  If
the variables don’t fit on single line, repeat the type specification.
Example:

     octave_value retval;

     octave_idx_type nr = b.rows ();
     octave_idx_type nc = b.cols ();

     double d1, d2;

   Use lowercase names if possible.  Uppercase is acceptable for
variable names consisting of 1-2 letters.  Do not use mixed case names.

   Use Octave’s types and classes if possible.  Otherwise, use the C++
standard library.  Use of STL containers and algorithms is encouraged.
Use templates wisely to reduce code duplication.  Avoid comma
expressions, labels and gotos, and explicit typecasts.  If you need to
typecast, use the modern C++ casting operators.  In functions, minimize
the number of ‘return’ statements—use nested ‘if’ statements if
possible.


File: octave.info,  Node: Other Sources,  Prev: C++ Sources,  Up: Contributing Guidelines

D.7 Other Sources
=================

Apart from C++ and Octave language (m-files), Octave’s sources include
files written in C, Fortran, M4, Perl, Unix shell, AWK, Texinfo, and
TeX.  There are not many rules to follow when using these other
languages; some of them are summarized below.  In any case, the golden
rule is: if you modify a source file, try to follow any conventions you
can detect in the file or other similar files.

   For C you should obviously follow all C++ rules that can apply.

   If you modify a Fortran file, you should stay within Fortran 77 with
common extensions like ‘END DO’.  Currently, we want all sources to be
compilable with the f2c and g77 compilers, without special flags if
possible.  This usually means that non-legacy compilers also accept the
sources.

   The M4 macro language is mainly used for Autoconf configuration
files.  You should follow normal M4 rules when contributing to these
files.  Some M4 files come from external source, namely the Autoconf
archive <http://autoconf-archive.cryp.to>.

   If you give a code example in the documentation written in Texinfo
with the ‘@example’ environment, you should be aware that the text
within such an environment will not be wrapped.  It is recommended that
you keep the lines short enough to fit on pages in the generated pdf or
ps documents.  Here is a ruler (in an ‘@example’ environment) for
finding the appropriate line width:

              1         2         3         4         5         6
     123456789012345678901234567890123456789012345678901234567890


File: octave.info,  Node: Obsolete Functions,  Next: Trouble,  Prev: Contributing Guidelines,  Up: Top

Appendix E Obsolete Functions
*****************************

After being marked as deprecated for two major releases, the following
functions have been removed from Octave.  The third column of the table
shows the version of Octave in which the function was removed.  Prior to
removal, each function in the list was marked as deprecated for at least
two major releases.  All deprecated functions issue warnings explaining
that they will be removed in a future version of Octave, and which
function should be used instead.

   Replacement functions do not always accept precisely the same
arguments as the obsolete function, but should provide equivalent
functionality.

Obsolete Function      Replacement            Version
----------------------------------------------------------
‘beta_cdf’             ‘betacdf’              3.4.0
‘beta_inv’             ‘betainv’              3.4.0
‘beta_pdf’             ‘betapdf’              3.4.0
‘beta_rnd’             ‘betarnd’              3.4.0
‘binomial_cdf’         ‘binocdf’              3.4.0
‘binomial_inv’         ‘binoinv’              3.4.0
‘binomial_pdf’         ‘binopdf’              3.4.0
‘binomial_rnd’         ‘binornd’              3.4.0
‘chisquare_cdf’        ‘chi2cdf’              3.4.0
‘chisquare_inv’        ‘chi2inv’              3.4.0
‘chisquare_pdf’        ‘chi2pdf’              3.4.0
‘chisquare_rnd’        ‘chi2rnd’              3.4.0
‘clearplot’            ‘clf’                  3.4.0
‘com2str’              ‘num2str’              3.4.0
‘exponential_cdf’      ‘expcdf’               3.4.0
‘exponential_inv’      ‘expinv’               3.4.0
‘exponential_pdf’      ‘exppdf’               3.4.0
‘exponential_rnd’      ‘exprnd’               3.4.0
‘f_cdf’                ‘fcdf’                 3.4.0
‘f_inv’                ‘finv’                 3.4.0
‘f_pdf’                ‘fpdf’                 3.4.0
‘f_rnd’                ‘frnd’                 3.4.0
‘gamma_cdf’            ‘gamcdf’               3.4.0
‘gamma_inv’            ‘gaminv’               3.4.0
‘gamma_pdf’            ‘gampdf’               3.4.0
‘gamma_rnd’            ‘gamrnd’               3.4.0
‘geometric_cdf’        ‘geocdf’               3.4.0
‘geometric_inv’        ‘geoinv’               3.4.0
‘geometric_pdf’        ‘geopdf’               3.4.0
‘geometric_rnd’        ‘geornd’               3.4.0
‘hypergeometric_cdf’   ‘hygecdf’              3.4.0
‘hypergeometric_inv’   ‘hygeinv’              3.4.0
‘hypergeometric_pdf’   ‘hygepdf’              3.4.0
‘hypergeometric_rnd’   ‘hygernd’              3.4.0
‘intersection’         ‘intersect’            3.4.0
‘is_bool’              ‘isbool’               3.4.0
‘is_complex’           ‘iscomplex’            3.4.0
‘is_list’              ‘islist’               3.4.0
‘is_matrix’            ‘ismatrix’             3.4.0
‘is_scalar’            ‘isscalar’             3.4.0
‘is_square’            ‘issquare’             3.4.0
‘is_stream’            ‘isstream’             3.4.0
‘is_struct’            ‘isstruct’             3.4.0
‘is_symmetric’         ‘issymmetric’          3.4.0
‘is_vector’            ‘isvector’             3.4.0
‘lognormal_cdf’        ‘logncdf’              3.4.0
‘lognormal_inv’        ‘logninv’              3.4.0
‘lognormal_pdf’        ‘lognpdf’              3.4.0
‘lognormal_rnd’        ‘lognrnd’              3.4.0
‘meshdom’              ‘meshgrid’             3.4.0
‘normal_cdf’           ‘normcdf’              3.4.0
‘normal_inv’           ‘norminv’              3.4.0
‘normal_pdf’           ‘normpdf’              3.4.0
‘normal_rnd’           ‘normrnd’              3.4.0
‘pascal_cdf’           ‘nbincdf’              3.4.0
‘pascal_inv’           ‘nbininv’              3.4.0
‘pascal_pdf’           ‘nbinpdf’              3.4.0
‘pascal_rnd’           ‘nbinrnd’              3.4.0
‘poisson_cdf’          ‘poisscdf’             3.4.0
‘poisson_inv’          ‘poissinv’             3.4.0
‘poisson_pdf’          ‘poisspdf’             3.4.0
‘poisson_rnd’          ‘poissrnd’             3.4.0
‘polyinteg’            ‘polyint’              3.4.0
‘struct_contains’      ‘isfield’              3.4.0
‘struct_elements’      ‘fieldnames’           3.4.0
‘t_cdf’                ‘tcdf’                 3.4.0
‘t_inv’                ‘tinv’                 3.4.0
‘t_pdf’                ‘tpdf’                 3.4.0
‘t_rnd’                ‘trnd’                 3.4.0
‘uniform_cdf’          ‘unifcdf’              3.4.0
‘uniform_inv’          ‘unifinv’              3.4.0
‘uniform_pdf’          ‘unifpdf’              3.4.0
‘uniform_rnd’          ‘unifrnd’              3.4.0
‘weibull_cdf’          ‘wblcdf’               3.4.0
‘weibull_inv’          ‘wblinv’               3.4.0
‘weibull_pdf’          ‘wblpdf’               3.4.0
‘weibull_rnd’          ‘wblrnd’               3.4.0
‘wiener_rnd’           ‘wienrnd’              3.4.0
‘create_set’           ‘unique’               3.6.0
‘dmult’                ‘diag (A) * B’         3.6.0
‘iscommand’            None                   3.6.0
‘israwcommand’         None                   3.6.0
‘lchol’                ‘chol (...,            3.6.0
                       "lower")’
‘loadimage’            ‘load’ or ‘imread’     3.6.0
‘mark_as_command’      None                   3.6.0
‘mark_as_rawcommand’   None                   3.6.0
‘spatan2’              ‘atan2’                3.6.0
‘spchol’               ‘chol’                 3.6.0
‘spchol2inv’           ‘chol2inv’             3.6.0
‘spcholinv’            ‘cholinv’              3.6.0
‘spcumprod’            ‘cumprod’              3.6.0
‘spcumsum’             ‘cumsum’               3.6.0
‘spdet’                ‘det’                  3.6.0
‘spdiag’               ‘sparse (diag          3.6.0
                       (...))’
‘spfind’               ‘find’                 3.6.0
‘sphcat’               ‘horzcat’              3.6.0
‘spinv’                ‘inv’                  3.6.0
‘spkron’               ‘kron’                 3.6.0
‘splchol’              ‘chol (...,            3.6.0
                       "lower")’
‘split’                ‘char (strsplit (s,    3.6.0
                       t))’
‘splu’                 ‘lu’                   3.6.0
‘spmax’                ‘max’                  3.6.0
‘spmin’                ‘min’                  3.6.0
‘spprod’               ‘prod’                 3.6.0
‘spqr’                 ‘qr’                   3.6.0
‘spsum’                ‘sum’                  3.6.0
‘spsumsq’              ‘sumsq’                3.6.0
‘spvcat’               ‘vertcat’              3.6.0
‘str2mat’              ‘char’                 3.6.0
‘unmark_command’       None                   3.6.0
‘unmark_rawcommand’    None                   3.6.0
‘autocor’              Octave-Forge signal    3.8.0
                       pkg, ‘xcor’
‘autocov’              Octave-Forge signal    3.8.0
                       pkg, ‘xcov’
‘betai’                ‘betainc’              3.8.0
‘cellidx’              ‘ismember’             3.8.0
‘cquad’                ‘quadcc’               3.8.0
‘dispatch’             None                   3.8.0
‘fstat’                ‘stat’                 3.8.0
‘gammai’               ‘gammainc’             3.8.0
‘glpkmex’              ‘glpk’                 3.8.0
‘is_duplicate_entry’   ‘unique’               3.8.0
‘is_global’            ‘isglobal’             3.8.0
‘krylovb’              ‘[Uret, ~, Ucols] =    3.8.0
                       krylov (...)’
‘perror’               None                   3.8.0
‘replot’               ‘refresh’              3.8.0
‘saveimage’            ‘imwrite’              3.8.0
‘setstr’               ‘char’                 3.8.0
‘strerror’             None                   3.8.0
‘values’               ‘unique’               3.8.0
‘cut’                  ‘histc’                4.0.0
‘cor’                  ‘corr’                 4.0.0
‘corrcoef’             ‘corr’                 4.0.0
‘__error_text__’       ‘lasterr’              4.0.0
‘error_text’           ‘lasterr’              4.0.0
‘polyderiv’            ‘polyder’              4.0.0
‘shell_cmd’            ‘system’               4.0.0
‘studentize’           ‘zscore’               4.0.0
‘sylvester_matrix’     ‘hadamard (2^k)’       4.0.0


File: octave.info,  Node: Trouble,  Next: Installation,  Prev: Obsolete Functions,  Up: Top

Appendix F Known Causes of Trouble
**********************************

This section describes known problems that affect users of Octave.  Most
of these are not Octave bugs per se—if they were, we would fix them.
But the result for a user may be like the result of a bug.

   Some of these problems are due to bugs in other software, some are
missing features that are too much work to add, and some are places
where people’s opinions differ as to what is best.

* Menu:

* Actual Bugs::                 Bugs we will fix later.
* Reporting Bugs::
* Service::


File: octave.info,  Node: Actual Bugs,  Next: Reporting Bugs,  Up: Trouble

F.1 Actual Bugs We Haven’t Fixed Yet
====================================

   • Output that comes directly from Fortran functions is not sent
     through the pager and may appear out of sequence with other output
     that is sent through the pager.  One way to avoid this is to force
     pending output to be flushed before calling a function that will
     produce output from within Fortran functions.  To do this, use the
     command

          fflush (stdout)

     Another possible workaround is to use the command

          page_screen_output (false);

     to turn the pager off.

   A list of ideas for future enhancements is distributed with Octave.
See the file ‘PROJECTS’ in the top level directory in the source
distribution.


File: octave.info,  Node: Reporting Bugs,  Next: Service,  Prev: Actual Bugs,  Up: Trouble

F.2 Reporting Bugs
==================

Your bug reports play an essential role in making Octave reliable.

   When you encounter a problem, the first thing to do is to see if it
is already known.  *Note Trouble::.  If it isn’t known, then you should
report the problem.

   Reporting a bug may help you by bringing a solution to your problem,
or it may not.  In any case, the principal function of a bug report is
to help the entire community by making the next version of Octave work
better.  Bug reports are your contribution to the maintenance of Octave.

   In order for a bug report to serve its purpose, you must include the
information that makes it possible to fix the bug.

* Menu:

* Bug Criteria::
* Bug Tracker::        Where to submit your bug report.
* Bug Reporting::      How to report a bug effectively.
* Sending Patches::    How to send a patch for Octave.


File: octave.info,  Node: Bug Criteria,  Next: Bug Tracker,  Up: Reporting Bugs

F.2.1 Have You Found a Bug?
---------------------------

If you are not sure whether you have found a bug, here are some
guidelines:

   • If Octave gets a fatal signal, for any input whatever, that is a
     bug.  Reliable interpreters never crash.

   • If Octave produces incorrect results, for any input whatever, that
     is a bug.

   • Some output may appear to be incorrect when it is in fact due to a
     program whose behavior is undefined, which happened by chance to
     give the desired results on another system.  For example, the range
     operator may produce different results because of differences in
     the way floating point arithmetic is handled on various systems.

   • If Octave produces an error message for valid input, that is a bug.

   • If Octave does not produce an error message for invalid input, that
     is a bug.  However, you should note that your idea of “invalid
     input” might be my idea of “an extension” or “support for
     traditional practice”.

   • If you are an experienced user of programs like Octave, your
     suggestions for improvement are welcome in any case.

