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

Oct-Files
=========

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.

 -- mkoctfile: [-options] 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.  Any output is stored in the OUTPUT variable and the exit status in the STATUS variable.  If called with no outputs and the compilation fails then Octave will emit an error.  If the programmer requests OUTPUT or STATUS, however, Octave will merely issue a warning and it is the programmer's responsibility to verify the command was successful.

     mkoctfile accepts the following options, all of which are optional except for the filename 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 options to the linker like "-Wl,-rpath=...". The quotes are needed since commas are interpreted as command separators.

     -W...
          Pass options to the assembler like "-Wa,OPTION".

     -c
          Compile but do not link.

     -g
          Enable debugging options for compilers.

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

     -p VAR
     --print VAR
          Print configuration variable VAR.  There are three categories of variables:

          Octave configuration variables that users may override with environment variables.  These are used in commands that mkoctfile executes.

                  ALL_CFLAGS                  INCLUDEDIR
                  ALL_CXXFLAGS                LAPACK_LIBS
                  ALL_FFLAGS                  LDFLAGS
                  ALL_LDFLAGS                 LD_STATIC_FLAG
                  BLAS_LIBS                   LFLAGS
                  CC                          LIBDIR
                  CFLAGS                      LIBOCTAVE
                  CPICFLAG                    LIBOCTINTERP
                  CPPFLAGS                    OCTAVE_LINK_OPTS
                  CXX                         OCTINCLUDEDIR
                  CXXFLAGS                    OCTAVE_LIBS
                  CXXLD                       OCTAVE_LINK_DEPS
                  CXXPICFLAG                  OCTLIBDIR
                  DL_LDFLAGS                  OCT_LINK_DEPS
                  F77                         OCT_LINK_OPTS
                  F77_INTEGER8_FLAG           RDYNAMIC_FLAG
                  FFLAGS                      SPECIAL_MATH_LIB
                  FPICFLAG                    XTRA_CFLAGS
                  INCFLAGS                    XTRA_CXXFLAGS

          Octave configuration variables as above, but currently unused by mkoctfile.

                  AR
                  DEPEND_EXTRA_SED_PATTERN
                  DEPEND_FLAGS
                  FFTW3F_LDFLAGS
                  FFTW3F_LIBS
                  FFTW3_LDFLAGS
                  FFTW3_LIBS
                  FFTW_LIBS
                  FLIBS
                  LIBS
                  RANLIB
                  READLINE_LIBS

          Octave configuration variables that are provided for informational purposes only.  Except for OCTAVE_HOME and OCTAVE_EXEC_HOME, users may not override these variables.

          If OCTAVE_HOME or OCTAVE_EXEC_HOME are set in the environment, then other variables are adjusted accordingly with OCTAVE_HOME or OCTAVE_EXEC_HOME substituted for the original value of the directory specified by the --prefix or --exec-prefix options that were used when Octave was configured.

                  API_VERSION                 LOCALFCNFILEDIR
                  ARCHLIBDIR                  LOCALOCTFILEDIR
                  BINDIR                      LOCALSTARTUPFILEDIR
                  CANONICAL_HOST_TYPE         LOCALVERARCHLIBDIR
                  DATADIR                     LOCALVERFCNFILEDIR
                  DATAROOTDIR                 LOCALVEROCTFILEDIR
                  DEFAULT_PAGER               MAN1DIR
                  EXEC_PREFIX                 MAN1EXT
                  EXEEXT                      MANDIR
                  FCNFILEDIR                  OCTAVE_EXEC_HOME
                  IMAGEDIR                    OCTAVE_HOME
                  INFODIR                     OCTAVE_VERSION
                  INFOFILE                    OCTDATADIR
                  LIBEXECDIR                  OCTDOCDIR
                  LOCALAPIARCHLIBDIR          OCTFILEDIR
                  LOCALAPIFCNFILEDIR          OCTFONTSDIR
                  LOCALAPIOCTFILEDIR          STARTUPFILEDIR
                  LOCALARCHLIBDIR

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

     --mex
          Assume creation of 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
                  .cp   C++ source
                  .cpp  C++ source
                  .CPP  C++ source
                  .cxx  C++ source
                  .c++  C++ source
                  .C    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")
     {
       octave_stdout << "Hello World has "
                     << args.length () << " input arguments and "
                     << nargout << " output arguments.\n";

       // Return empty matrices for any outputs
       octave_value_list retval (nargout);
       for (int i = 0; i < nargout; i++)
         retval(i) = octave_value (Matrix ());

       return retval;
     }

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 be---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 (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 how to 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 simply to study the examples in the manual in order to be able to use a class.

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

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 for all matrix and array types.

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

          Matrix a (2, 2)

     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 methods 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 get 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 () const
     The total number of elements in the matrix or array.

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

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

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

 -- Method: void resize (const dim_vector&)
 -- Method: void resize (nrows, ncols)
     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 ()
     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 as +, -, 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")
     {
       if (args.length () != 2)
         print_usage ();

       NDArray A = args(0).array_value ();
       NDArray B = args(1).array_value ();

       return octave_value (A + B);
     }

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 method.  If an error occurs when attempting to extract the value, Octave will print a message and throw an exception.  The reason to prefer this coding structure is that the arguments might be a type which is not an NDArray, but for which it would make sense to convert them to one.  The array_value method allows this conversion to be performed transparently when possible.  If you need to catch errors like this, and perform some kind of cleanup or other operation, you can catch the octave_execution_error exception.

A + B, operating on two NDArray objects 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

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")
     {
       if (args.length () != 1)
         print_usage ();

       octave_value_list retval;

       charMatrix ch = args(0).char_matrix_value ();

       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, '"');

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_values, and thus each element of the cell array can be treated like any other octave_value.  A simple example is

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

     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       if (args.length () != 1)
         print_usage ();

       Cell c = args(0).cell_value ();

       octave_value_list retval;
       retval.resize (c.numel ());    // faster code by pre-declaring size

       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_values one by one from the cell array and returns them as individual output arguments.  For example:

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

        1   2

     b3 = test

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")
     {
       if (args.length () != 2)
         print_usage ();

       if (! args(0).isstruct ())
         error ("structdemo: ARG1 must be a struct");

       octave_scalar_map arg0 = args(0).scalar_map_value ();
       //octave_map arg0 = args(0).map_value ();

       if (! args(1).is_string ())
         error ("structdemo: ARG2 must be a character string");

       std::string arg1 = args(1).string_value ();

       octave_value tmp = arg0.contents (arg1);
       //octave_value tmp = arg0.contents (arg1)(0);

       if (! tmp.is_defined ())
         error ("structdemo: struct does not have a field named '%s'\n",
                arg1.c_str ());

       octave_scalar_map st;

       st.assign ("selected", tmp);

       return octave_value (st);
     }

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 the single struct example we would 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.

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 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 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 it is to the NDArray class.

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 nnz = sm.nelem ();

returns the number of nonzero elements (like the interpreter function nnz).  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, 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.  In this case, the number of rows multiplied by the number of columns is more than two hundred times the maximum value that can be represented by an unsigned 32-bit int.  The use of numel should, therefore, be avoided unless it is known that it will not overflow.

Extreme care is also required when using the elem method or the () operator which perform essentially 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) << "\n";

is a great way of turning a sparse matrix into a dense one, and a very slow way at that since it reallocates the sparse object for each zero element in the matrix.

A simple 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; This is not a costly operation.  The example above, re-written to prevent sparse-to-dense conversion, is

     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) << "\n";

Finally, because the sparse types aren't represented by a contiguous block of memory, the fortran_vec method of 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, it is up to the user to respect the sparse matrix compressed column format or the matrix will become corrupted.

Creating Sparse Matrices in Oct-Files
.....................................

There are two useful strategies 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 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 indices 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.  It is possible to create a sparse matrix with excess storage, so having NZ greater than 4 in this example is also valid.  The disadvantage is that the matrix occupies more memory than strictly needed.

Of course, 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 to deallocating unused storage, maybe_compress 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 for the user to avoid adding 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 advanced 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 = 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 may 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;   // Guess the number of nz elements
     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 = 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_compress ();  // 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 because 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 avoid changing capacity.

Using Sparse Matrices in Oct-Files
..................................

Most of the same operators and functions for sparse matrices that are available from the Octave interpreter 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.

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 global_varval and global_assign from the current interpreter's symbol table.  Both functions take as first argument a string representing the variable name to be obtained or assigned.  The second argument of global_assign is the value to be assigned.  An example of the use of these two functions is

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

     DEFMETHOD_DLD (globaldemo, interp, args, , "Global Demo")
     {
       if (args.length () != 1)
         print_usage ();

       octave_value retval;

       std::string s = args(0).string_value ();

       octave::symbol_table& symtab = interp.get_symbol_table ();

       octave_value tmp = symtab.global_varval (s);

       if (tmp.is_defined ())
         retval = tmp;
       else
         retval = "Global variable not found";

       symtab.global_assign ("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

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 could be given as input.  It might be passed as one of

 1. Function Handle

 2. Anonymous Function Handle

 3. String

The code below demonstrates all four methods of passing a function to an oct-file.

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

     DEFMETHOD_DLD (funcdemo, interp, args, nargout, "Function Demo")
     {
       int nargin = args.length ();

       if (nargin < 2)
         print_usage ();

       octave_value_list newargs;

       for (octave_idx_type i = nargin - 1; i > 0; i--)
         newargs(i-1) = args(i);

       octave_value_list retval;

       if (args(0).is_function_handle () || args(0).is_inline_function ()
           || args(0).is_string ())
         retval = interp.feval (args(0), newargs, nargout);
       else
         error ("funcdemo: INPUT must be string, inline, or function handle");

       return retval;
     }

The first input to the demonstration code is a user-supplied function and the remaining arguments are all passed to the function.

     funcdemo (@sin, 1)
     => 0.84147
     funcdemo (@(x) 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 all internal function names begin and end with the character sequence __.

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

When calling functions that are implemented in Fortran code, some pecularities have to be taken into account.  Symbol names in Fortran are case-insensitive, and depending on the used Fortran compiler, function names are either exported with all lower-case or with all upper-case characters.  Additionally, some compilers append none, one or two underscores "_" at the end of exported function names.  This is called "name-mangling".

Octave supplies macros that allow writing code that automatically handles the name-mangling for a number of different Fortran compilers.  These macros are F77_FUNC and F77_FUNC_.  The former should be used for Fortran functions that do not contain any underscores in their name.  The latter should be used for Fortran functions with underscores in their names.  Both macros take two arguments: The first is the Fortran function name in all lower-case characters.  The second is the same Fortran function name in all upper-case characters.

Additionally to the name-mangling, different compilers are using different calling conventions for some types.  Octave defines the following preprocessor macros to allow writing code that can be used with different Fortran calling conventions.

Note that we don't attempt to handle Fortran functions, we always use subroutine wrappers for them and pass the return value as an extra argument.

Use the following macros to pass character strings from C to Fortran:

       F77_CHAR_ARG(x)
       F77_CONST_CHAR_ARG(x)
       F77_CXX_STRING_ARG(x)
       F77_CHAR_ARG_LEN(l)
       F77_CHAR_ARG_DECL
       F77_CONST_CHAR_ARG_DECL
       F77_CHAR_ARG_LEN_DECL

Use the following macros to write C-language functions that accept Fortran-style character strings:

       F77_CHAR_ARG_DEF(s, len)
       F77_CONST_CHAR_ARG_DEF(s, len)
       F77_CHAR_ARG_LEN_DEF(len)
       F77_CHAR_ARG_USE(s)
       F77_CHAR_ARG_LEN_USE(s, len)

Use the following macros for Fortran types in C++ code:

F77_INT4
     Equivalent to Fortran INTEGER*4 type

F77_DBLE
     Equivalent to Fortran DOUBLE PRECISION type

F77_REAL
     Equivalent to Fortran REAL type

F77_CMPLX
     Equivalent to Fortran COMPLEX type

F77_DBLE_CMPLX
     Equivalent to Fortran DOUBLE COMPLEX type

F77_LOGICAL
     Equivalent to Fortran LOGICAL type

F77_RET_T
     Return type of a C++ function that acts like a Fortran subroutine.

Use the following macros to return from C-language functions that are supposed to act like Fortran subroutines.  F77_NORETURN is intended to be used as the last statement of such a function that has been tagged with a "noreturn" attribute.

       F77_RETURN(retval)
       F77_NORETURN(retval)

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.

The following example shows the inclusion of a Fortran function in an oct-file, where the C++ wrapper is

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortransub, FORTRANSUB)
         (const F77_INT&, F77_DBLE*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
     {
       if (args.length () != 1)
         print_usage ();

       NDArray a = args(0).array_value ();

       double *av = a.fortran_vec ();
       octave_idx_type na = a.numel ();

       OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

       F77_FUNC (fortransub, FORTRANSUB)
                 (na, av, ctmp F77_CHAR_ARG_LEN (128));

       return ovl (a, std::string (ctmp));
     }

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

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.

Input Parameter Checking in Oct-Files
-------------------------------------

Because 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. (see ov.h).  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")
     {
       if (args.length () != 1)
         print_usage ();

       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 octave_value_list ();
     }

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

Exception and Error Handling in Oct-Files
-----------------------------------------

Another important feature of Octave is its ability to react to the user typing Control-C during extended calculations.  This ability is based on the C++ exception handler, where memory allocated by the C++ new/delete methods is automatically released when the exception is treated.  When writing an oct-file which may run for a long time the programmer must periodically use the macro OCTAVE_QUIT, in order to allow Octave to check and possibly respond to a user typing Control-C.  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 detect and acknowledge a Control-C key sequence.  Without this macro, the user must either wait for the oct-file function to return before the interrupt is processed, or the user must press Control-C three times which will force Octave to exit completely.

The OCTAVE_QUIT macro does impose a very small performance penalty; For loops that are known to be small it may not make sense to include OCTAVE_QUIT.

When creating an oct-file that uses an external library, 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 code 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 (The unwind_protect Statement) can also be used in oct-files.  In conjunction with the exception handling of Octave, it ensures that certain recovery code is always run 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")
     {
       if (args.length () < 2)
         print_usage ();

       NDArray a = args(0).array_value ();
       NDArray b = args(1).array_value ();

       // Create unwind_action objects.  At the end of the enclosing scope,
       // destructors for these objects will call the given functions with
       // the specified arguments.

       octave::unwind_action restore_warning_handler
         (set_liboctave_warning_handler, current_liboctave_warning_handler);

       octave::unwind_action restore_warning_with_id_handler
         (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);

       return octave_value (quotient (a, b));
     }

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.

Documentation and Testing of Oct-Files
--------------------------------------

The documentation for an oct-file is contained in 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, however there are some issues 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 multi-line 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 {} {} 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 each line of text is terminated by \n\ which is an embedded newline 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 (see 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---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))
     */

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

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

 -- mex: [-options] file ...
 -- status =: mex (...)
     Compile source code written in C, C++, or Fortran, to a MEX file.

     STATUS is the return status of the mkoctfile function.

     If the compilation fails, and the output argument is not requested, an error is raised.  If the programmer requests STATUS, however, Octave will merely issue a warning and it is the programmer's responsibility to verify the command was successful.

     This is equivalent to mkoctfile --mex [-options] file.

     mkoctfile, mexext

 -- EXT =: mexext ()
     Return the filename extension used for MEX files.

     Programming Note: Octave uses the extension mex for all MEX files regardless of the operating system (Linux, Windows, Apple) or the bit-width (32-bit or 64-bit) of the hardware. mex

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);

       /* Return empty matrices for any outputs */
       int i;
       for (i = 0; i < nlhs; i++)
         plhs[i] = mxCreateDoubleMatrix (0, 0, mxREAL);
     }

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.  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.  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, there would need to be a file myhello.m which 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 the file myfunc.c, and 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 function's 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.

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.  mxArray serves essentially the same purpose as the octave_value class in oct-files in that it acts as a container for all 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 in an array is mxGetPr.  Because 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 for 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];
         }
     }

An example of its use is

     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 (MxN matrix).

Character Strings in Mex-Files
------------------------------

As mex-files do not make the distinction between single and double quoted strings that Octave does, there is perhaps less complexity in the use of strings and character matrices.  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.

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 duplicates 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);

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

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 implementations sparse matrices are required to be two-dimensional.  The only difference of importance to the programmer 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

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 within a mex-file.

Standalone Programs
===================

The libraries Octave uses itself 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 ()
     {
       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/interpreter.h>

     int
     main ()
     {
       // Create interpreter.

       octave::interpreter interpreter;

       try
         {
           // Inhibit reading history file by calling
           //
           //   interpreter.initialize_history (false);

           // Set custom load path here if you wish by calling
           //
           //   interpreter.initialize_load_path (false);

           // Perform final initialization of interpreter, including
           // executing commands from startup files by calling
           //
           //   interpreter.initialize ();
           //
           //   if (! interpreter.is_initialized ())
           //     {
           //       std::cerr << "Octave interpreter initialization failed!"
           //                 << std::endl;
           //       exit (1);
           //     }
           //
           // You may skip this step if you don't need to do anything
           // between reading the startup files and telling the interpreter
           // that you are ready to execute commands.

           // Tell the interpreter that we're ready to execute commands:

           int status = interpreter.execute ();

           if (status != 0)
             {
               std::cerr << "creating embedded Octave interpreter failed!"
                         << std::endl;
               return status;
             }

           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 = octave::feval ("gcd", in, 1);

           if (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";
         }
       catch (const octave::exit_exception& ex)
         {
           std::cerr << "Octave interpreter exited with status = "
                     << ex.exit_status () << std::endl;
         }
       catch (const octave::execution_exception&)
         {
           std::cerr << "error encountered in Octave evaluator!" << std::endl;
         }

       return 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 re-iterating that, if only built-in functions are to be called from a C++ standalone program then it does not need to initialize the interpreter. 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 a 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 ()
     {
       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 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
     $

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 joPas (http://jopas.sourceforge.net).

Making Java Classes Available
-----------------------------

Java finds classes by searching a CLASSPATH which 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, and then the DYNAMIC CLASSPATH.  Classes appearing in the STATIC CLASSPATH, 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 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 javaclasspath.txt in the m-file directory where Octave Java functions live.  This is where the function 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 JAR archives 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");

How to use Java from within Octave
----------------------------------

The function javaObject creates Java objects. In fact it invokes the public constructor of the class with the given name and with the given parameters.

The following example shows how to invoke the constructors BigDecimal(double) and BigDecimal(String) of the builtin Java class java.math.BigDecimal.

     javaObject ("java.math.BigDecimal",  1.001 );
     javaObject ("java.math.BigDecimal", "1.001");

Note that parameters of the Octave type double are implicitly converted into the Java type double and the Octave type (array of) char is converted into the java type String.  A Java object created by javaObject is never automatically converted into an Octave type but remains a Java object.  It can be assigned to an Octave variable.

     a = 1.001;
     b = javaObject ("java.math.BigDecimal", a);

Using isjava, it is possible to check whether a variable is a Java object and its class can be determined as well.  In addition to the previous example:

     isjava (a)
     => ans = 0
     class (a)
     => ans = double
     isjava (b)
     => ans = 1
     class (b)
     => ans = java.math.BigDecimal

The example above can be carried out using only Java objects:

     a = javaObject ("java.lang.Double", 1.001);
     b = javaObject ("java.math.BigDecimal", a);

     isjava (a)
     => ans = 1
     class (a)
     => ans = java.lang.Double
     isjava (b)
     => ans = 1
     class (b)
     => ans = java.math.BigDecimal

One can see, that even a java.lang.Double is not converted to an Octave double, when created by javaObject. But ambiguities might arise, if the Java classes java.lang.Double or double are parameters of a method (or a constructor).  In this case they can be converted into one another, depending on the context.

Via javaObject one may create all kinds of Java objects but arrays.  The latter are created through javaArray.

It is possible to invoke public member methods on Java objects in Java syntax:

     a.toString
     => ans = 1.001
     b.toString
     => ans = 1.000999999999999889865...

The second result may be surprising, but simply comes from the fact, that 1.001 cannot exactly be represented as double, due to rounding. Note that unlike in Java, in Octave methods without arguments can be invoked with and without parentheses ().

Currently it is not possible to invoke static methods with a Java like syntax from within Octave.  Instead, one has to use the function javaMethod as in the following example:

     java.math.BigDecimal.valueOf(1.001);                    # does not work
     javaMethod ("valueOf", "java.math.BigDecimal", 1.001);  # workaround

As mentioned before, method and constructor parameters are converted automatically between Octave and Java types, if appropriate.  For functions this is also true with return values, whereas for constructors this is not.

It is also possible to access public fields of Java objects from within Octave using Java syntax, with the limitation of static fields:

     java.math.BigDecimal.ONE;                  # does not work
     java_get ("java.math.BigDecimal", "ONE");  # workaround

Accordingly, with java_set the value of a field can be set.  Note that only public Java fields are accessible from within Octave.

The following example indicates that in Octave empty brackets [] represent Java's null value and how Java exceptions are represented.

     javaObject ("java.math.BigDecimal", []);
     => error: [java] java.lang.NullPointerException

It is not recommended to represent Java's null value by empty brackets [], because null has no type whereas [] has type double.

In Octave it is possible to provide limited Java reflection by listing the public fields and methods of a Java object, both static or not.

     fieldnames (<Java object>)
     methods (<Java object>)

Finally, an examples is shown how to access the stack trace from within Octave, where the function debug_java is used to set and to get the current debug state.  In debug mode, the Java error and the stack trace are displayed.

     debug_java (true)  # use "false" to omit display of stack trace
     debug_java ()
     => ans = 1
     javaObject ("java.math.BigDecimal", "1") ...
       .divide (javaObject ("java.math.BigDecimal", "0"))

Set up the JVM
--------------

In order to execute Java code Octave creates a Java Virtual Machine (JVM).  By default the version of the JVM is used that was detected during configuration on Unix-like systems or that is pointed to from the registry keys at HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\JRE or HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment on Windows.  The default path to the JVM can be overridden by setting the environment variable JAVA_HOME to the path where the JVM is installed.  On Windows that might be, for example, C:\Program Files\Java\jre-10.0.2.  Make sure that you select a directory that contains the JVM with a bit-ness that matches Octave's.

The JVM is only loaded once per Octave session.  Thus, to change the used version of the JVM, you might have to re-start Octave.  To check which version of the JVM is currently being used, run version -java.

The 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 (see javamem).  The memory pool is shared by all Java objects running in the JVM.  This strict memory limit is intended mainly to avoid runaway applications inside web browsers or in enterprise servers which 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 enter you enter lines containing -X and -D options that are then passed 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

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.

 -- JOBJ =: javaObject (CLASSNAME)
 -- 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")

     javaMethod, javaArray

 -- JARY =: javaArray (CLASSNAME, SZ)
 -- 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";

     javaObject

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.

 -- TF =: isjava (X)
     Return true if X is a Java object. class, typeinfo, isa, javaObject

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

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

     java_set, javaMethod, javaObject

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

     java_get, javaMethod, javaObject

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

 -- RET =: javaMethod (METHODNAME, OBJ)
 -- 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.

     methods, javaObject

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.

 -- javaclasspath: ()
 -- DPATH =: javaclasspath ()
 -- [DPATH, SPATH] =: javaclasspath ()
 -- 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.

     javaaddpath, javarmpath

 -- javaaddpath: (CLSPATH)
 -- javaaddpath: (CLSPATH1, ...)
 -- javaaddpath: ({CLSPATH1, ...})
 -- javaaddpath: (..., "-end")
     Add CLSPATH to the beginning of 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, or by using a cell array of strings.

     If the final argument is "-end", append the new element to the end of the current classpath.

     javarmpath, javaclasspath

 -- javarmpath: (CLSPATH)
 -- javarmpath: (CLSPATH1, ...)
 -- 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, or by using a cell array of strings. javaaddpath, javaclasspath

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

 -- MSG =: javachk (FEATURE)
 -- MSG =: javachk (FEATURE, CALLER)
     Check for the presence of the Java FEATURE in the current session. Return an error structure if FEATURE is not available, not enabled, or not recognized.

     Possible recognized 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 not supported, a scalar struct with field "message" and "identifier" is returned.  The field "message" contains an error message mentioning FEATURE as well as the optional user-specified CALLER.  This structure is suitable for passing in to the error function.

     If FEATURE is supported and available, an empty struct array is returned with fields "message" and "identifier".

     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 or specific Java runtime features.

     Compatibility Note: The feature "desktop" is never available since Octave has no Java-based desktop.

     usejava, error

 -- TF =: 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. javachk

 -- javamem: ()
 -- 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.

 -- VAL =: java_matrix_autoconversion ()
 -- OLD_VAL =: java_matrix_autoconversion (NEW_VAL)
 -- OLD_VAL =: 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. java_unsigned_autoconversion, debug_java

 -- VAL =: java_unsigned_autoconversion ()
 -- OLD_VAL =: java_unsigned_autoconversion (NEW_VAL)
 -- OLD_VAL =: 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. java_matrix_autoconversion, debug_java

 -- VAL =: debug_java ()
 -- OLD_VAL =: debug_java (NEW_VAL)
 -- OLD_VAL =: 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. java_matrix_autoconversion, java_unsigned_autoconversion