This is /home/jwe/src/octave-stable/doc/interpreter/octave.info, produced by makeinfo version 4.13 from /home/jwe/src/octave-stable/doc/interpreter/octave.texi.

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007,
2011 John W. Eaton.

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

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

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


File: octave.info,  Node: Multi-dimensional Interpolation,  Prev: One-dimensional Interpolation,  Up: Interpolation

28.2 Multi-dimensional Interpolation
====================================

There are three multi-dimensional interpolation functions in Octave,
with similar capabilities.  Methods using Delaunay tessellation are
described in *note Interpolation on Scattered Data::.

 -- Function File: ZI = interp2 (X, Y, Z, XI, YI)
 -- Function File: ZI = interp2 (Z, XI, YI)
 -- Function File: ZI = interp2 (Z, N)
 -- Function File: ZI = interp2 (..., METHOD)
 -- Function File: ZI = interp2 (..., METHOD, EXTRAPVAL)
     Two-dimensional interpolation.  X, Y and Z describe a surface
     function.  If X and Y are vectors their length must correspondent
     to the size of Z.  X and Y must be monotonic.  If they are
     matrices they must have the `meshgrid' format.

    `interp2 (X, Y, Z, XI, YI, ...)'
          Returns a matrix corresponding to the points described by the
          matrices XI, YI.

          If the last argument is a string, the interpolation method can
          be specified.  The method can be 'linear', 'nearest' or
          'cubic'.  If it is omitted 'linear' interpolation is assumed.

    `interp2 (Z, XI, YI)'
          Assumes `X = 1:rows (Z)' and `Y = 1:columns (Z)'

    `interp2 (Z, N)'
          Interleaves the matrix Z n-times.  If N is omitted a value of
          `N = 1' is assumed.

     The variable METHOD defines the method to use for the
     interpolation.  It can take one of the following values

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'pchip'
          Piecewise cubic Hermite interpolating polynomial.

    'cubic'
          Cubic interpolation from four nearest neighbors.

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     If a scalar value EXTRAPVAL is defined as the final value, then
     values outside the mesh as set to this value.  Note that in this
     case METHOD must be defined as well.  If EXTRAPVAL is not defined
     then NA is assumed.

     *See also:* *note interp1: doc-interp1.

 -- Function File: VI = interp3 (X, Y, Z, V, XI, YI, ZI)
 -- Function File: VI = interp3 (V, XI, YI, ZI)
 -- Function File: VI = interp3 (V, M)
 -- Function File: VI = interp3 (V)
 -- Function File: VI = interp3 (..., METHOD)
 -- Function File: VI = interp3 (..., METHOD, EXTRAPVAL)
     Perform 3-dimensional interpolation.  Each element of the
     3-dimensional array V represents a value at a location given by
     the parameters X, Y, and Z.  The parameters X, X, and Z are either
     3-dimensional arrays of the same size as the array V in the
     'meshgrid' format or vectors.  The parameters XI, etc.  respect a
     similar format to X, etc., and they represent the points at which
     the array VI is interpolated.

     If X, Y, Z are omitted, they are assumed to be `x = 1 : size (V,
     2)', `y = 1 : size (V, 1)' and `z = 1 : size (V, 3)'.  If M is
     specified, then the interpolation adds a point half way between
     each of the interpolation points.  This process is performed M
     times.  If only V is specified, then M is assumed to be `1'.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'cubic'
          Cubic interpolation from four nearest neighbors (not
          implemented yet).

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     The default method is 'linear'.

     If EXTRAP is the string 'extrap', then extrapolate values beyond
     the endpoints.  If EXTRAP is a number, replace values beyond the
     endpoints with that number.  If EXTRAP is missing, assume NA.

     *See also:* *note interp1: doc-interp1, *note interp2:
     doc-interp2, *note spline: doc-spline, *note meshgrid:
     doc-meshgrid.

 -- Function File: VI = interpn (X1, X2, ..., V, Y1, Y2, ...)
 -- Function File: VI = interpn (V, Y1, Y2, ...)
 -- Function File: VI = interpn (V, M)
 -- Function File: VI = interpn (V)
 -- Function File: VI = interpn (..., METHOD)
 -- Function File: VI = interpn (..., METHOD, EXTRAPVAL)
     Perform N-dimensional interpolation, where N is at least two.
     Each element of the N-dimensional array V represents a value at a
     location given by the parameters X1, X2, ..., XN.  The parameters
     X1, X2, ..., XN are either N-dimensional arrays of the same size
     as the array V in the 'ndgrid' format or vectors.  The parameters
     Y1, etc. respect a similar format to X1, etc., and they represent
     the points at which the array VI is interpolated.

     If X1, ..., XN are omitted, they are assumed to be `x1 = 1 : size
     (V, 1)', etc.  If M is specified, then the interpolation adds a
     point half way between each of the interpolation points.  This
     process is performed M times.  If only V is specified, then M is
     assumed to be `1'.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'cubic'
          Cubic interpolation from four nearest neighbors (not
          implemented yet).

    'spline'
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     The default method is 'linear'.

     If EXTRAPVAL is the scalar value, use it to replace the values
     beyond the endpoints with that number.  If EXTRAPVAL is missing,
     assume NA.

     *See also:* *note interp1: doc-interp1, *note interp2:
     doc-interp2, *note spline: doc-spline, *note ndgrid: doc-ndgrid.

   A significant difference between `interpn' and the other two
multi-dimensional interpolation functions is the fashion in which the
dimensions are treated.  For `interp2' and `interp3', the 'y' axis is
considered to be the columns of the matrix, whereas the 'x' axis
corresponds to the rows of the array.  As Octave indexes arrays in
column major order, the first dimension of any array is the columns, and
so `interpn' effectively reverses the 'x' and 'y' dimensions.  Consider
the example,

     x = y = z = -1:1;
     f = @(x,y,z) x.^2 - y - z.^2;
     [xx, yy, zz] = meshgrid (x, y, z);
     v = f (xx,yy,zz);
     xi = yi = zi = -1:0.1:1;
     [xxi, yyi, zzi] = meshgrid (xi, yi, zi);
     vi = interp3(x, y, z, v, xxi, yyi, zzi, 'spline');
     [xxi, yyi, zzi] = ndgrid (xi, yi, zi);
     vi2 = interpn(x, y, z, v, xxi, yyi, zzi, 'spline');
     mesh (zi, yi, squeeze (vi2(1,:,:)));

where `vi' and `vi2' are identical.  The reversal of the dimensions is
treated in the `meshgrid' and `ndgrid' functions respectively.

   In additional the support function `bicubic' that underlies the
cubic interpolation of `interp2' function can be called directly.

 -- Function File: ZI = bicubic (X, Y, Z, XI, YI, EXTRAPVAL)
     Return a matrix ZI corresponding to the bicubic interpolations at
     XI and YI of the data supplied as X, Y and Z.  Points outside the
     grid are set to EXTRAPVAL.

     See `http://wiki.woodpecker.org.cn/moin/Octave/Bicubic' for
     further information.

     *See also:* *note interp2: doc-interp2.


File: octave.info,  Node: Geometry,  Next: Signal Processing,  Prev: Interpolation,  Up: Top

29 Geometry
***********

Much of the geometry code in Octave is based on the Qhull library(1).
Some of the documentation for Qhull, particularly for the options that
can be passed to `delaunay', `voronoi' and `convhull', etc., is
relevant to Octave users.

* Menu:

* Delaunay Triangulation::
* Voronoi Diagrams::
* Convex Hull::
* Interpolation on Scattered Data::

   ---------- Footnotes ----------

   (1) Barber, C.B., Dobkin, D.P., and Huhdanpaa, H.T., `The Quickhull
Algorithm for Convex Hulls', ACM Trans. on Mathematical Software,
22(4):469-483, Dec 1996, `http://www.qhull.org'


File: octave.info,  Node: Delaunay Triangulation,  Next: Voronoi Diagrams,  Up: Geometry

29.1 Delaunay Triangulation
===========================

The Delaunay triangulation is constructed from a set of circum-circles.
These circum-circles are chosen so that there are at least three of the
points in the set to triangulation on the circumference of the
circum-circle.  None of the points in the set of points falls within
any of the circum-circles.

   In general there are only three points on the circumference of any
circum-circle.  However, in some cases, and in particular for the case
of a regular grid, 4 or more points can be on a single circum-circle.
In this case the Delaunay triangulation is not unique.

 -- Function File: TRI = delaunay (X, Y)
 -- Function File: TRI = delaunay (X, Y, OPT)
     The return matrix of size [n, 3] contains a set triangles which are
     described by the indices to the data point x and y vector.  The
     triangulation satisfies the Delaunay circum-circle criterion.  No
     other data point is in the circum-circle of the defining triangle.

     A third optional argument, which must be a string, contains extra
     options passed to the underlying qhull command.  See the
     documentation for the Qhull library for details.

          x = rand (1, 10);
          y = rand (size (x));
          T = delaunay (x, y);
          X = [x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1))];
          Y = [y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1))];
          axis ([0,1,0,1]);
          plot (X, Y, "b", x, y, "r*");

     *See also:* *note voronoi: doc-voronoi, *note delaunay3:
     doc-delaunay3, *note delaunayn: doc-delaunayn.

   The 3- and N-dimensional extension of the Delaunay triangulation are
given by `delaunay3' and `delaunayn' respectively.  `delaunay3' returns
a set of tetrahedra that satisfy the Delaunay circum-circle criteria.
Similarly, `delaunayn' returns the N-dimensional simplex satisfying the
Delaunay circum-circle criteria.  The N-dimensional extension of a
triangulation is called a tessellation.

 -- Function File: T = delaunay3 (X, Y, Z)
 -- Function File: T = delaunay3 (X, Y, Z, OPT)
     A matrix of size [n, 4] is returned.  Each row contains a set of
     tetrahedron which are described by the indices to the data point
     vectors (x,y,z).

     A fourth optional argument, which must be a string or cell array
     of strings, contains extra options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details.

     *See also:* *note delaunay: doc-delaunay, *note delaunayn:
     doc-delaunayn.

 -- Function File: T = delaunayn (P)
 -- Function File: T = delaunayn (P, OPT)
     Form the Delaunay triangulation for a set of points.  The Delaunay
     triangulation is a tessellation of the convex hull of the points
     such that no n-sphere defined by the n-triangles contains any
     other points from the set.  The input matrix P of size `[n, dim]'
     contains n points in a space of dimension dim.  The return matrix
     T has the size `[m, dim+1]'.  It contains for each row a set of
     indices to the points, which describes a simplex of dimension dim.
     For example, a 2-D simplex is a triangle and 3-D simplex is a
     tetrahedron.

     Extra options for the underlying Qhull command can be specified by
     the second argument.  This argument is a cell array of strings.
     The default options depend on the dimension of the input:

        * 2D and 3D: OPT = `{"Qt", "Qbb", "Qc"}'

        * 4D and higher: OPT = `{"Qt", "Qbb", "Qc", "Qz"}'

     If OPT is [], then the default arguments are used.  If OPT is
     `{""}', then none of the default arguments are used by Qhull.  See
     the Qhull documentation for the available options.

     All options can also be specified as single string, for example
     `"Qt Qbb Qc Qz"'.


   An example of a Delaunay triangulation of a set of points is

     rand ("state", 2);
     x = rand (10, 1);
     y = rand (10, 1);
     T = delaunay (x, y);
     X = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
     Y = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
     axis ([0, 1, 0, 1]);
     plot(X, Y, "b", x, y, "r*");

* Menu:

* Plotting the Triangulation::
* Identifying Points in Triangulation::


File: octave.info,  Node: Plotting the Triangulation,  Next: Identifying Points in Triangulation,  Up: Delaunay Triangulation

29.1.1 Plotting the Triangulation
---------------------------------

Octave has the functions `triplot', `trimesh', and `trisurf' to plot
the Delaunay triangulation of a 2-dimensional set of points.

 -- Function File:  triplot (TRI, X, Y)
 -- Function File:  triplot (TRI, X, Y, LINESPEC)
 -- Function File: H = triplot (...)
     Plot a triangular mesh in 2D.  The variable TRI is the triangular
     meshing of the points `(X, Y)' which is returned from `delaunay'.
     If given, the LINESPEC determines the properties to use for the
     lines.  The output argument H is the graphic handle of the plot.

     *See also:* *note plot: doc-plot, *note trimesh: doc-trimesh,
     *note trisurf: doc-trisurf, *note delaunay: doc-delaunay.

 -- Function File:  trimesh (TRI, X, Y, Z)
 -- Function File: H = trimesh (...)
     Plot a triangular mesh in 3D.  The variable TRI is the triangular
     meshing of the points `(X, Y)' which is returned from `delaunay'.
     The variable Z is value at the point `(X, Y)'.  The output
     argument H is the graphic handle of the plot.

     *See also:* *note triplot: doc-triplot, *note trisurf:
     doc-trisurf, *note delaunay3: doc-delaunay3.

 -- Function File:  trisurf (TRI, X, Y, Z)
 -- Function File: H = trisurf (...)
     Plot a triangular surface in 3D.  The variable TRI is the
     triangular meshing of the points `(X, Y)' which is returned from
     `delaunay'.  The variable Z is value at the point `(X, Y)'.  The
     output argument H is the graphic handle of the plot.

     *See also:* *note triplot: doc-triplot, *note trimesh:
     doc-trimesh, *note delaunay3: doc-delaunay3.

   The difference between `triplot', and `trimesh' or `triplot', is
that the former only plots the 2-dimensional triangulation itself,
whereas the second two plot the value of a function `f (X, Y)'.  An
example of the use of the `triplot' function is

     rand ("state", 2)
     x = rand (20, 1);
     y = rand (20, 1);
     tri = delaunay (x, y);
     triplot (tri, x, y);

which plots the Delaunay triangulation of a set of random points in
2-dimensions.


File: octave.info,  Node: Identifying Points in Triangulation,  Prev: Plotting the Triangulation,  Up: Delaunay Triangulation

29.1.2 Identifying Points in Triangulation
------------------------------------------

It is often necessary to identify whether a particular point in the
N-dimensional space is within the Delaunay tessellation of a set of
points in this N-dimensional space, and if so which N-simplex contains
the point and which point in the tessellation is closest to the desired
point.  The functions `tsearch' and `dsearch' perform this function in
a triangulation, and `tsearchn' and `dsearchn' in an N-dimensional
tessellation.

   To identify whether a particular point represented by a vector P
falls within one of the simplices of an N-simplex, we can write the
Cartesian coordinates of the point in a parametric form with respect to
the N-simplex.  This parametric form is called the Barycentric
Coordinates of the point.  If the points defining the N-simplex are
given by `N + 1' vectors T(I,:), then the Barycentric coordinates
defining the point P are given by

     P = sum (BETA(1:N+1) * T(1:N+1),:)

where there are `N + 1' values `BETA(I)' that together as a vector
represent the Barycentric coordinates of the point P.  To ensure a
unique solution for the values of `BETA(I)' an additional criteria of

     sum (BETA(1:N+1)) == 1

is imposed, and we can therefore write the above as

     P - T(end, :) = BETA(1:end-1) * (T(1:end-1, :)
           - ones(N, 1) * T(end, :)

Solving for BETA we can then write

     BETA(1:end-1) = (P - T(end, :)) / (T(1:end-1, :)
           - ones(N, 1) * T(end, :))
     BETA(end) = sum(BETA(1:end-1))

which gives the formula for the conversion of the Cartesian coordinates
of the point P to the Barycentric coordinates BETA.  An important
property of the Barycentric coordinates is that for all points in the
N-simplex

     0 <= BETA(I) <= 1

Therefore, the test in `tsearch' and `tsearchn' essentially only needs
to express each point in terms of the Barycentric coordinates of each
of the simplices of the N-simplex and test the values of BETA.  This is
exactly the implementation used in `tsearchn'.  `tsearch' is optimized
for 2-dimensions and the Barycentric coordinates are not explicitly
formed.

 -- Loadable Function: IDX = tsearch (X, Y, T, XI, YI)
     Search for the enclosing Delaunay convex hull.  For `T = delaunay
     (X, Y)', finds the index in T containing the points `(XI, YI)'.
     For points outside the convex hull, IDX is NaN.

     *See also:* *note delaunay: doc-delaunay, *note delaunayn:
     doc-delaunayn.

 -- Function File: [IDX, P] = tsearchn (X, T, XI)
     Search for the enclosing Delaunay convex hull.  For `T = delaunayn
     (X)', finds the index in T containing the points XI.  For points
     outside the convex hull, IDX is NaN.  If requested `tsearchn' also
     returns the Barycentric coordinates P of the enclosing triangles.

     *See also:* *note delaunay: doc-delaunay, *note delaunayn:
     doc-delaunayn.

   An example of the use of `tsearch' can be seen with the simple
triangulation

     X = [-1; -1; 1; 1];
     Y = [-1; 1; -1; 1];
     TRI = [1, 2, 3; 2, 3, 1];

consisting of two triangles defined by TRI.  We can then identify which
triangle a point falls in like

     tsearch (X, Y, TRI, -0.5, -0.5)
     => 1
     tsearch (X, Y, TRI, 0.5, 0.5)
     => 2

and we can confirm that a point doesn't lie within one of the triangles
like

     tsearch (X, Y, TRI, 2, 2)
     => NaN

   The `dsearch' and `dsearchn' find the closest point in a
tessellation to the desired point.  The desired point does not
necessarily have to be in the tessellation, and even if it the returned
point of the tessellation does not have to be one of the vertexes of the
N-simplex within which the desired point is found.

 -- Function File: IDX = dsearch (X, Y, TRI, XI, YI)
 -- Function File: IDX = dsearch (X, Y, TRI, XI, YI, S)
     Return the index IDX or the closest point in `X, Y' to the
     elements `[XI(:), YI(:)]'.  The variable S is accepted for
     compatibility but is ignored.

     *See also:* *note dsearchn: doc-dsearchn, *note tsearch:
     doc-tsearch.

 -- Function File: IDX = dsearchn (X, TRI, XI)
 -- Function File: IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- Function File: IDX = dsearchn (X, XI)
 -- Function File: [IDX, D] = dsearchn (...)
     Return the index IDX or the closest point in X to the elements XI.
     If OUTVAL is supplied, then the values of XI that are not
     contained within one of the simplices TRI are set to OUTVAL.
     Generally, TRI is returned from `delaunayn (X)'.

     *See also:* *note dsearch: doc-dsearch, *note tsearch: doc-tsearch.

   An example of the use of `dsearch', using the above values of X, Y
and TRI is

     dsearch (X, Y, TRI, -2, -2)
     => 1

   If you wish the points that are outside the tessellation to be
flagged, then `dsearchn' can be used as

     dsearchn ([X, Y], TRI, [-2, -2], NaN)
     => NaN
     dsearchn ([X, Y], TRI, [-0.5, -0.5], NaN)
     => 1

where the point outside the tessellation are then flagged with `NaN'.


File: octave.info,  Node: Voronoi Diagrams,  Next: Convex Hull,  Prev: Delaunay Triangulation,  Up: Geometry

29.2 Voronoi Diagrams
=====================

A Voronoi diagram or Voronoi tessellation of a set of points S in an
N-dimensional space, is the tessellation of the N-dimensional space
such that all points in `V(P)', a partitions of the tessellation where
P is a member of S, are closer to P than any other point in S.  The
Voronoi diagram is related to the Delaunay triangulation of a set of
points, in that the vertexes of the Voronoi tessellation are the
centers of the circum-circles of the simplices of the Delaunay
tessellation.

 -- Function File:  voronoi (X, Y)
 -- Function File:  voronoi (X, Y, "plotstyle")
 -- Function File:  voronoi (X, Y, "plotstyle", OPTIONS)
 -- Function File: [VX, VY] = voronoi (...)
     Plot Voronoi diagram of points `(X, Y)'.  The Voronoi facets with
     points at infinity are not drawn.  [VX, VY] = voronoi(...) returns
     the vertices instead of plotting the diagram. plot (VX, VY) shows
     the Voronoi diagram.

     A fourth optional argument, which must be a string, contains extra
     options passed to the underlying qhull command.  See the
     documentation for the Qhull library for details.

            x = rand (10, 1);
            y = rand (size (x));
            h = convhull (x, y);
            [vx, vy] = voronoi (x, y);
            plot (vx, vy, "-b", x, y, "o", x(h), y(h), "-g")
            legend ("", "points", "hull");

     *See also:* *note voronoin: doc-voronoin, *note delaunay:
     doc-delaunay, *note convhull: doc-convhull.

 -- Function File: [C, F] = voronoin (PTS)
 -- Function File: [C, F] = voronoin (PTS, OPTIONS)
     Compute N-dimensional Voronoi facets.  The input matrix PTS of
     size [n, dim] contains n points of dimension dim.  C contains the
     points of the Voronoi facets.  The list F contains for each facet
     the indices of the Voronoi points.

     A second optional argument, which must be a string, contains extra
     options passed to the underlying qhull command.  See the
     documentation for the Qhull library for details.

     *See also:* *note voronoin: doc-voronoin, *note delaunay:
     doc-delaunay, *note convhull: doc-convhull.

   An example of the use of `voronoi' is

     rand("state",9);
     x = rand(10,1);
     y = rand(10,1);
     tri = delaunay (x, y);
     [vx, vy] = voronoi (x, y, tri);
     triplot (tri, x, y, "b");
     hold on;
     plot (vx, vy, "r");

   Additional information about the size of the facets of a Voronoi
diagram, and which points of a set of points is in a polygon can be had
with the `polyarea' and `inpolygon' functions respectively.

 -- Function File:  polyarea (X, Y)
 -- Function File:  polyarea (X, Y, DIM)
     Determines area of a polygon by triangle method.  The variables X
     and Y define the vertex pairs, and must therefore have the same
     shape.  They can be either vectors or arrays.  If they are arrays
     then the columns of X and Y are treated separately and an area
     returned for each.

     If the optional DIM argument is given, then `polyarea' works along
     this dimension of the arrays X and Y.


   An example of the use of `polyarea' might be

     rand ("state", 2);
     x = rand (10, 1);
     y = rand (10, 1);
     [c, f] = voronoin ([x, y]);
     af = zeros (size(f));
     for i = 1 : length (f)
       af(i) = polyarea (c (f {i, :}, 1), c (f {i, :}, 2));
     endfor

   Facets of the Voronoi diagram with a vertex at infinity have infinity
area.  A simplified version of `polyarea' for rectangles is available
with `rectint'

 -- Function File: AREA = rectint (A, B)
     Compute the area of intersection of rectangles in A and rectangles
     in B.  Rectangles are defined as [x y width height] where x and y
     are the minimum values of the two orthogonal dimensions.

     If A or B are matrices, then the output, AREA, is a matrix where
     the i-th row corresponds to the i-th row of a and the j-th column
     corresponds to the j-th row of b.

     *See also:* *note polyarea: doc-polyarea.

 -- Function File: [IN, ON] = inpolygon (X, Y, XV, YV)
     For a polygon defined by vertex points `(XV, YV)', determine if
     the points `(X, Y)' are inside or outside the polygon.  The
     variables X, Y, must have the same dimension.  The optional output
     ON gives the points that are on the polygon.


   An example of the use of `inpolygon' might be

     randn ("state", 2);
     x = randn (100, 1);
     y = randn (100, 1);
     vx = cos (pi * [-1 : 0.1: 1]);
     vy = sin (pi * [-1 : 0.1 : 1]);
     in = inpolygon (x, y, vx, vy);
     plot(vx, vy, x(in), y(in), "r+", x(!in), y(!in), "bo");
     axis ([-2, 2, -2, 2]);


File: octave.info,  Node: Convex Hull,  Next: Interpolation on Scattered Data,  Prev: Voronoi Diagrams,  Up: Geometry

29.3 Convex Hull
================

The convex hull of a set of points is the minimum convex envelope
containing all of the points.  Octave has the functions `convhull' and
`convhulln' to calculate the convex hull of 2-dimensional and
N-dimensional sets of points.

 -- Function File: H = convhull (X, Y)
 -- Function File: H = convhull (X, Y, OPT)
     Return the index vector to the points of the enclosing convex
     hull.  The data points are defined by the x and y vectors.

     A third optional argument, which must be a string, contains extra
     options passed to the underlying qhull command.  See the
     documentation for the Qhull library for details.

     *See also:* *note delaunay: doc-delaunay, *note convhulln:
     doc-convhulln.

 -- Loadable Function: H = convhulln (P)
 -- Loadable Function: H = convhulln (P, OPT)
 -- Loadable Function: [H, V] = convhulln (...)
     Return an index vector to the points of the enclosing convex hull.
     The input matrix of size [n, dim] contains n points of dimension
     dim.

     If a second optional argument is given, it must be a string or
     cell array of strings containing options for the underlying qhull
     command.  (See the Qhull documentation for the available options.)
     The default options are "s Qci Tcv".  If the second output V is
     requested the volume of the convex hull is calculated.

     *See also:* *note convhull: doc-convhull, *note delaunayn:
     doc-delaunayn.

   An example of the use of `convhull' is

     x = -3:0.05:3;
     y = abs (sin (x));
     k = convhull (x, y);
     plot (x(k), y(k), "r-", x, y, "b+");
     axis ([-3.05, 3.05, -0.05, 1.05]);


File: octave.info,  Node: Interpolation on Scattered Data,  Prev: Convex Hull,  Up: Geometry

29.4 Interpolation on Scattered Data
====================================

An important use of the Delaunay tessellation is that it can be used to
interpolate from scattered data to an arbitrary set of points.  To do
this the N-simplex of the known set of points is calculated with
`delaunay', `delaunay3' or `delaunayn'.  Then the simplices in to which
the desired points are found are identified.  Finally the vertices of
the simplices are used to interpolate to the desired points.  The
functions that perform this interpolation are `griddata', `griddata3'
and `griddatan'.

 -- Function File: ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- Function File: [XI, YI, ZI] = griddata (X, Y, Z, XI, YI, METHOD)
     Generate a regular mesh from irregular data using interpolation.
     The function is defined by `Z = f (X, Y)'.  Inputs `X, Y, Z' are
     vectors of the same length or `X, Y' are vectors and `Z' is matrix.

     The interpolation points are all `(XI, YI)'.  If XI, YI are
     vectors then they are made into a 2-D mesh.

     The interpolation method can be `"nearest"', `"cubic"' or
     `"linear"'.  If method is omitted it defaults to `"linear"'.

     *See also:* *note delaunay: doc-delaunay.

 -- Function File: VI = griddata3 (X, Y, Z, V XI, YI, ZI, METHOD,
          OPTIONS)
     Generate a regular mesh from irregular data using interpolation.
     The function is defined by `Y = f (X,Y,Z)'.  The interpolation
     points are all XI.

     The interpolation method can be `"nearest"' or `"linear"'.  If
     method is omitted it defaults to `"linear"'.

     *See also:* *note griddata: doc-griddata, *note delaunayn:
     doc-delaunayn.

 -- Function File: YI = griddatan (X, Y, XI, METHOD, OPTIONS)
     Generate a regular mesh from irregular data using interpolation.
     The function is defined by `Y = f (X)'.  The interpolation points
     are all XI.

     The interpolation method can be `"nearest"' or `"linear"'.  If
     method is omitted it defaults to `"linear"'.

     *See also:* *note griddata: doc-griddata, *note delaunayn:
     doc-delaunayn.

   An example of the use of the `griddata' function is

     rand("state",1);
     x=2*rand(1000,1)-1;
     y=2*rand(size(x))-1;
     z=sin(2*(x.^2+y.^2));
     [xx,yy]=meshgrid(linspace(-1,1,32));
     griddata(x,y,z,xx,yy);

that interpolates from a random scattering of points, to a uniform grid.


File: octave.info,  Node: Signal Processing,  Next: Image Processing,  Prev: Geometry,  Up: Top

30 Signal Processing
********************

This chapter describes the signal processing and fast Fourier transform
functions available in Octave.  Fast Fourier transforms are computed
with the FFTW or FFTPACK libraries depending on how Octave is built.

 -- Function File:  detrend (X, P)
     If X is a vector, `detrend (X, P)' removes the best fit of a
     polynomial of order P from the data X.

     If X is a matrix, `detrend (X, P)' does the same for each column
     in X.

     The second argument is optional.  If it is not specified, a value
     of 1 is assumed.  This corresponds to removing a linear trend.

     The order of the polynomial can also be given as a string, in
     which case P must be either "constant" (corresponds to `P=0') or
     "linear" (corresponds to `P=1').

     *See also:* *note polyfit: doc-polyfit.

 -- Loadable Function:  fft (X)
 -- Loadable Function:  fft (X, N)
 -- Loadable Function:  fft (X, N, DIM)
     Compute the discrete Fourier transform of A using a Fast Fourier
     Transform (FFT) algorithm.

     The FFT is calculated along the first non-singleton dimension of
     the array.  Thus if X is a matrix, `fft (X)' computes the FFT for
     each column of X.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of X to use, or an empty matrix
     to specify that its value should be ignored.  If N is larger than
     the dimension along which the FFT is calculated, then X is resized
     and padded with zeros.  Otherwise, if N is smaller than the
     dimension along which the FFT is calculated, then X is truncated.

     If called with three arguments, DIM is an integer specifying the
     dimension of the matrix along which the FFT is performed

     *See also:* *note ifft: doc-ifft, *note fft2: doc-fft2, *note
     fftn: doc-fftn, *note fftw: doc-fftw.

   Octave uses the FFTW libraries to perform FFT computations.  When
Octave starts up and initializes the FFTW libraries, they read a system
wide file (on a Unix system, it is typically `/etc/fftw/wisdom') that
contains information useful to speed up FFT computations.  This
information is called the _wisdom_.  The system-wide file allows wisdom
to be shared between all applications using the FFTW libraries.

   Use the `fftw' function to generate and save wisdom.  Using the
utilities provided together with the FFTW libraries (`fftw-wisdom' on
Unix systems), you can even add wisdom generated by Octave to the
system-wide wisdom file.

 -- Loadable Function: METHOD = fftw ('planner')
 -- Loadable Function:  fftw ('planner', METHOD)
 -- Loadable Function: WISDOM = fftw ('dwisdom')
 -- Loadable Function:  fftw ('dwisdom', WISDOM)
     Manage FFTW wisdom data.  Wisdom data can be used to significantly
     accelerate the calculation of the FFTs, but implies an initial cost
     in its calculation.  When the FFTW libraries are initialized, they
     read a system wide wisdom file (typically in `/etc/fftw/wisdom'),
     allowing wisdom to be shared between applications other than
     Octave.  Alternatively, the `fftw' function can be used to import
     wisdom.  For example,

          WISDOM = fftw ('dwisdom')

     will save the existing wisdom used by Octave to the string WISDOM.
     This string can then be saved to a file and restored using the
     `save' and `load' commands respectively.  This existing wisdom can
     be reimported as follows

          fftw ('dwisdom', WISDOM)

     If WISDOM is an empty matrix, then the wisdom used is cleared.

     During the calculation of Fourier transforms further wisdom is
     generated.  The fashion in which this wisdom is generated is also
     controlled by the `fftw' function.  There are five different
     manners in which the wisdom can be treated:

    'estimate'
          Specifies that no run-time measurement of the optimal means of
          calculating a particular is performed, and a simple heuristic
          is used to pick a (probably sub-optimal) plan.  The advantage
          of this method is that there is little or no overhead in the
          generation of the plan, which is appropriate for a Fourier
          transform that will be calculated once.

    'measure'
          In this case a range of algorithms to perform the transform
          is considered and the best is selected based on their
          execution time.

    'patient'
          Similar to 'measure', but a wider range of algorithms is
          considered.

    'exhaustive'
          Like 'measure', but all possible algorithms that may be used
          to treat the transform are considered.

    'hybrid'
          As run-time measurement of the algorithm can be expensive,
          this is a compromise where 'measure' is used for transforms
          up to the size of 8192 and beyond that the 'estimate' method
          is used.

     The default method is 'estimate'.  The current method can be
     queried with

          METHOD = fftw ('planner')

     or set by using

          fftw ('planner', METHOD)

     Note that calculated wisdom will be lost when restarting Octave.
     However, the wisdom data can be reloaded if it is saved to a file
     as described above.  Saved wisdom files should not be used on
     different platforms since they will not be efficient and the point
     of calculating the wisdom is lost.

     *See also:* *note fft: doc-fft, *note ifft: doc-ifft, *note fft2:
     doc-fft2, *note ifft2: doc-ifft2, *note fftn: doc-fftn, *note
     ifftn: doc-ifftn.

 -- Loadable Function:  ifft (X)
 -- Loadable Function:  ifft (X, N)
 -- Loadable Function:  ifft (X, N, DIM)
     Compute the inverse discrete Fourier transform of A using a Fast
     Fourier Transform (FFT) algorithm.

     The inverse FFT is calculated along the first non-singleton
     dimension of the array.  Thus if X is a matrix, `fft (X)' computes
     the inverse FFT for each column of X.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of X to use, or an empty matrix
     to specify that its value should be ignored.  If N is larger than
     the dimension along which the inverse FFT is calculated, then X is
     resized and padded with zeros.  Otherwise, if N is smaller than
     the dimension along which the inverse FFT is calculated, then X is
     truncated.

     If called with three arguments, DIM is an integer specifying the
     dimension of the matrix along which the inverse FFT is performed

     *See also:* *note fft: doc-fft, *note ifft2: doc-ifft2, *note
     ifftn: doc-ifftn, *note fftw: doc-fftw.

 -- Loadable Function:  fft2 (A)
 -- Loadable Function:  fft2 (A, M, N)
     Compute the two-dimensional discrete Fourier transform of A using
     a Fast Fourier Transform (FFT) algorithm.

     The optional arguments M and N may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

     If A is a multi-dimensional matrix, each two-dimensional sub-matrix
     of A is treated separately.

     *See also:* ifft2, fft, fftn, fftw.

 -- Loadable Function:  ifft2 (A)
 -- Loadable Function:  ifft2 (A, M, N)
     Compute the inverse two-dimensional discrete Fourier transform of A
     using a Fast Fourier Transform (FFT) algorithm.

     The optional arguments M and N may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

     If A is a multi-dimensional matrix, each two-dimensional sub-matrix
     of A is treated separately

     *See also:* fft2, ifft, ifftn, fftw.

 -- Loadable Function:  fftn (A)
 -- Loadable Function:  fftn (A, SIZE)
     Compute the N-dimensional discrete Fourier transform of A using a
     Fast Fourier Transform (FFT) algorithm.

     The optional vector argument SIZE may be used specify the
     dimensions of the array to be used.  If an element of SIZE is
     smaller than the corresponding dimension of A, then the dimension
     of A is truncated prior to performing the FFT.  Otherwise, if an
     element of SIZE is larger than the corresponding dimension then A
     is resized and padded with zeros.

     *See also:* *note ifftn: doc-ifftn, *note fft: doc-fft, *note
     fft2: doc-fft2, *note fftw: doc-fftw.

 -- Loadable Function:  ifftn (A)
 -- Loadable Function:  ifftn (A, SIZE)
     Compute the inverse N-dimensional discrete Fourier transform of A
     using a Fast Fourier Transform (FFT) algorithm.

     The optional vector argument SIZE may be used specify the
     dimensions of the array to be used.  If an element of SIZE is
     smaller than the corresponding dimension of A, then the dimension
     of A is truncated prior to performing the inverse FFT.  Otherwise,
     if an element of SIZE is larger than the corresponding dimension
     then A is resized and padded with zeros.

     *See also:* *note fftn: doc-fftn, *note ifft: doc-ifft, *note
     ifft2: doc-ifft2, *note fftw: doc-fftw.

 -- Function File:  fftconv (X, Y)
 -- Function File:  fftconv (X, Y, N)
     Convolve two vectors using the FFT for computation.

     `c = fftconv (X, Y)' returns a vector of length equal to `length
     (X) + length (Y) - 1'.  If X and Y are the coefficient vectors of
     two polynomials, the returned value is the coefficient vector of
     the product polynomial.

     The computation uses the FFT by calling the function `fftfilt'.  If
     the optional argument N is specified, an N-point FFT is used.

     *See also:* *note deconv: doc-deconv, *note conv: doc-conv, *note
     conv2: doc-conv2.

 -- Function File:  fftfilt (B, X, N)
     With two arguments, `fftfilt' filters X with the FIR filter B
     using the FFT.

     Given the optional third argument, N, `fftfilt' uses the
     overlap-add method to filter X with B using an N-point FFT.

     If X is a matrix, filter each column of the matrix.

     *See also:* *note filter: doc-filter, *note filter2: doc-filter2.

 -- Loadable Function: y = filter (B, A, X)
 -- Loadable Function: [Y, SF] = filter (B, A, X, SI)
 -- Loadable Function: [Y, SF] = filter (B, A, X, [], DIM)
 -- Loadable Function: [Y, SF] = filter (B, A, X, SI, DIM)
     Return the solution to the following linear, time-invariant
     difference equation:

             N                   M
            SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k)      for 1<=n<=length(x)
            k=0                 k=0

     where  N=length(a)-1 and M=length(b)-1.  over the first
     non-singleton dimension of X or over DIM if supplied.  An
     equivalent form of this equation is:

                      N                   M
            y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k)  for 1<=n<=length(x)
                     k=1                 k=0

     where  c = a/a(1) and d = b/a(1).

     If the fourth argument SI is provided, it is taken as the initial
     state of the system and the final state is returned as SF.  The
     state vector is a column vector whose length is equal to the
     length of the longest coefficient vector minus one.  If SI is not
     supplied, the initial state vector is set to all zeros.

     In terms of the Z Transform, y is the result of passing the
     discrete- time signal x through a system characterized by the
     following rational system function:

                       M
                      SUM d(k+1) z^(-k)
                      k=0
            H(z) = ----------------------
                         N
                    1 + SUM c(k+1) z^(-k)
                        k=1

     *See also:* *note filter2: doc-filter2, *note fftfilt:
     doc-fftfilt, *note freqz: doc-freqz.

 -- Function File: Y = filter2 (B, X)
 -- Function File: Y = filter2 (B, X, SHAPE)
     Apply the 2-D FIR filter B to X.  If the argument SHAPE is
     specified, return an array of the desired shape.  Possible values
     are:

    'full'
          pad X with zeros on all sides before filtering.

    'same'
          unpadded X (default)

    'valid'
          trim X after filtering so edge effects are no included.

     Note this is just a variation on convolution, with the parameters
     reversed and B rotated 180 degrees.

     *See also:* *note conv2: doc-conv2.

 -- Function File: [H, W] = freqz (B, A, N, "whole")
     Return the complex frequency response H of the rational IIR filter
     whose numerator and denominator coefficients are B and A,
     respectively.  The response is evaluated at N angular frequencies
     between 0 and  2*pi.

     The output value W is a vector of the frequencies.

     If the fourth argument is omitted, the response is evaluated at
     frequencies between 0 and  pi.

     If N is omitted, a value of 512 is assumed.

     If A is omitted, the denominator is assumed to be 1 (this
     corresponds to a simple FIR filter).

     For fastest computation, N should factor into a small number of
     small primes.

 -- Function File: H = freqz (B, A, W)
     Evaluate the response at the specific frequencies in the vector W.
     The values for W are measured in radians.

 -- Function File: [...] = freqz (..., FS)
     Return frequencies in Hz instead of radians assuming a sampling
     rate FS.  If you are evaluating the response at specific
     frequencies W, those frequencies should be requested in Hz rather
     than radians.

 -- Function File:  freqz (...)
     Plot the pass band, stop band and phase response of H rather than
     returning them.

 -- Function File:  freqz_plot (W, H)
     Plot the pass band, stop band and phase response of H.

 -- Function File:  sinc (X)
     Return  sin(pi*x)/(pi*x).

 -- Function File: B = unwrap (X)
 -- Function File: B = unwrap (X, TOL)
 -- Function File: B = unwrap (X, TOL, DIM)
     Unwrap radian phases by adding multiples of 2*pi as appropriate to
     remove jumps greater than TOL.  TOL defaults to pi.

     Unwrap will work along the dimension DIM.  If DIM is unspecified
     it defaults to the first non-singleton dimension.

 -- Function File: [A, B] = arch_fit (Y, X, P, ITER, GAMMA, A0, B0)
     Fit an ARCH regression model to the time series Y using the
     scoring algorithm in Engle's original ARCH paper.  The model is

          y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),
          h(t) = a(1) + a(2) * e(t-1)^2 + ... + a(p+1) * e(t-p)^2

     in which e(t) is N(0, h(t)), given a time-series vector Y up to
     time t-1 and a matrix of (ordinary) regressors X up to t.  The
     order of the regression of the residual variance is specified by P.

     If invoked as `arch_fit (Y, K, P)' with a positive integer K, fit
     an ARCH(K, P) process, i.e., do the above with the t-th row of X
     given by

          [1, y(t-1), ..., y(t-k)]

     Optionally, one can specify the number of iterations ITER, the
     updating factor GAMMA, and initial values a0 and b0 for the
     scoring algorithm.

 -- Function File:  arch_rnd (A, B, T)
     Simulate an ARCH sequence of length T with AR coefficients B and
     CH coefficients A.  I.e., the result y(t) follows the model

          y(t) = b(1) + b(2) * y(t-1) + ... + b(lb) * y(t-lb+1) + e(t),

     where e(t), given Y up to time t-1, is N(0, h(t)), with

          h(t) = a(1) + a(2) * e(t-1)^2 + ... + a(la) * e(t-la+1)^2

 -- Function File: [PVAL, LM] = arch_test (Y, X, P)
     For a linear regression model

          y = x * b + e

     perform a Lagrange Multiplier (LM) test of the null hypothesis of
     no conditional heteroscedascity against the alternative of CH(P).

     I.e., the model is

          y(t) = b(1) * x(t,1) + ... + b(k) * x(t,k) + e(t),

     given Y up to t-1 and X up to t, e(t) is N(0, h(t)) with

          h(t) = v + a(1) * e(t-1)^2 + ... + a(p) * e(t-p)^2,

     and the null is a(1) == ... == a(p) == 0.

     If the second argument is a scalar integer, k, perform the same
     test in a linear autoregression model of order k, i.e., with

          [1, y(t-1), ..., y(t-K)]

     as the t-th row of X.

     Under the null, LM approximately has a chisquare distribution with
     P degrees of freedom and PVAL is the p-value (1 minus the CDF of
     this distribution at LM) of the test.

     If no output argument is given, the p-value is displayed.

 -- Function File:  arma_rnd (A, B, V, T, N)
     Return a simulation of the ARMA model

          x(n) = a(1) * x(n-1) + ... + a(k) * x(n-k)
               + e(n) + b(1) * e(n-1) + ... + b(l) * e(n-l)

     in which K is the length of vector A, L is the length of vector B
     and E is Gaussian white noise with variance V.  The function
     returns a vector of length T.

     The optional parameter N gives the number of dummy X(I) used for
     initialization, i.e., a sequence of length T+N is generated and
     X(N+1:T+N) is returned.  If N is omitted, N = 100 is used.

 -- Function File:  autoreg_matrix (Y, K)
     Given a time series (vector) Y, return a matrix with ones in the
     first column and the first K lagged values of Y in the other
     columns.  I.e., for T > K, `[1, Y(T-1), ..., Y(T-K)]' is the t-th
     row of the result.  The resulting matrix may be used as a
     regressor matrix in autoregressions.

 -- Function File:  bartlett (M)
     Return the filter coefficients of a Bartlett (triangular) window of
     length M.

     For a definition of the Bartlett window, see e.g., A. V. Oppenheim
     & R. W. Schafer, `Discrete-Time Signal Processing'.

 -- Function File:  blackman (M)
     Return the filter coefficients of a Blackman window of length M.

     For a definition of the Blackman window, see e.g., A. V. Oppenheim
     & R. W. Schafer, `Discrete-Time Signal Processing'.

 -- Function File: [D, DD] = diffpara (X, A, B)
     Return the estimator D for the differencing parameter of an
     integrated time series.

     The frequencies from [2*pi*a/t, 2*pi*b/T] are used for the
     estimation.  If B is omitted, the interval [2*pi/T, 2*pi*a/T] is
     used.  If both B and A are omitted then a = 0.5 * sqrt (T) and b =
     1.5 * sqrt (T) is used, where T is the sample size.  If X is a
     matrix, the differencing parameter of each column is estimated.

     The estimators for all frequencies in the intervals described
     above is returned in DD.  The value of D is simply the mean of DD.

     Reference: P.J. Brockwell & R.A. Davis. `Time Series: Theory and
     Methods'. Springer 1987.

 -- Function File:  durbinlevinson (C, OLDPHI, OLDV)
     Perform one step of the Durbin-Levinson algorithm.

     The vector C specifies the autocovariances `[gamma_0, ...,
     gamma_t]' from lag 0 to T, OLDPHI specifies the coefficients based
     on C(T-1) and OLDV specifies the corresponding error.

     If OLDPHI and OLDV are omitted, all steps from 1 to T of the
     algorithm are performed.

 -- Function File:  fftshift (X)
 -- Function File:  fftshift (X, DIM)
     Perform a shift of the vector X, for use with the `fft' and `ifft'
     functions, in order the move the frequency 0 to the center of the
     vector or matrix.

     If X is a vector of N elements corresponding to N time samples
     spaced of Dt each, then `fftshift (fft (X))' corresponds to
     frequencies

          f = ((1:N) - ceil(N/2)) / N / Dt

     If X is a matrix, the same holds for rows and columns.  If X is an
     array, then the same holds along each dimension.

     The optional DIM argument can be used to limit the dimension along
     which the permutation occurs.

 -- Function File:  ifftshift (X)
 -- Function File:  ifftshift (X, DIM)
     Undo the action of the `fftshift' function.  For even length X,
     `fftshift' is its own inverse, but odd lengths differ slightly.

 -- Function File:  fractdiff (X, D)
     Compute the fractional differences (1-L)^d x where L denotes the
     lag-operator and d is greater than -1.

 -- Function File:  hamming (M)
     Return the filter coefficients of a Hamming window of length M.

     For a definition of the Hamming window, see e.g., A. V. Oppenheim &
     R. W. Schafer, `Discrete-Time Signal Processing'.

 -- Function File:  hanning (M)
     Return the filter coefficients of a Hanning window of length M.

     For a definition of this window type, see e.g., A. V. Oppenheim &
     R. W. Schafer, `Discrete-Time Signal Processing'.

 -- Function File:  hurst (X)
     Estimate the Hurst parameter of sample X via the rescaled range
     statistic.  If X is a matrix, the parameter is estimated for every
     single column.

 -- Function File: PP = pchip (X, Y)
 -- Function File: YI = pchip (X, Y, XI)
     Piecewise Cubic Hermite interpolating polynomial.  Called with two
     arguments, the piecewise polynomial PP is returned, that may later
     be used with `ppval' to evaluate the polynomial at specific points.

     The variable X must be a strictly monotonic vector (either
     increasing or decreasing).  While Y can be either a vector or
     array.  In the case where Y is a vector, it must have a length of
     N.  If Y is an array, then the size of Y must have the form `[S1,
     S2, ..., SK, N]' The array is then reshaped internally to a matrix
     where the leading dimension is given by `S1 * S2 * ... * SK' and
     each row in this matrix is then treated separately.  Note that this
     is exactly the opposite treatment than `interp1' and is done for
     compatibility.

     Called with a third input argument, `pchip' evaluates the
     piecewise polynomial at the points XI.  There is an equivalence
     between `ppval (pchip (X, Y), XI)' and `pchip (X, Y, XI)'.

     *See also:* *note spline: doc-spline, *note ppval: doc-ppval,
     *note mkpp: doc-mkpp, *note unmkpp: doc-unmkpp.

 -- Function File: [Pxx, W] = periodogram (X)
     For a data matrix X from a sample of size N, return the
     periodogram.  The angular frequency is returned in W.

     [Pxx,w] = periodogram (X).

     [Pxx,w] = periodogram (X,win).

     [Pxx,w] = periodogram (X,win,nfft).

     [Pxx,f] = periodogram (X,win,nfft,Fs).

     [Pxx,f] = periodogram (X,win,nfft,Fs,"range").

        * x: data; if real-valued a one-sided spectrum is estimated, if
          complex-valued or range indicates "twosided", the full
          spectrum is estimated.

        * win: weight data with window, x.*win is used for further
          computation, if window is empty, a rectangular window is used.

        * nfft: number of frequency bins, default max(256,
          2.^ceil(log2(length(x)))).

        * Fs: sampling rate, default 1.

        * range: "onesided" computes spectrum from [0..nfft/2+1].
          "twosided" computes spectrum from [0..nfft-1].  These strings
          can appear at any position in the list input arguments after
          window.

        * Pxx: one-, or two-sided power spectrum.

        * w: angular frequency [0..2*pi) (two-sided) or [0..pi]
          one-sided.

        * f: frequency [0..Fs) (two-sided) or [0..Fs/2] one-sided.

 -- Function File:  rectangle_lw (N, B)
     Rectangular lag window.  Subfunction used for spectral density
     estimation.

 -- Function File:  rectangle_sw (N, B)
     Rectangular spectral window.  Subfunction used for spectral density
     estimation.

 -- Function File:  sinetone (FREQ, RATE, SEC, AMPL)
     Return a sinetone of frequency FREQ with length of SEC seconds at
     sampling rate RATE and with amplitude AMPL.  The arguments FREQ
     and AMPL may be vectors of common size.

     Defaults are RATE = 8000, SEC = 1 and AMPL = 64.

 -- Function File:  sinewave (M, N, D)
     Return an M-element vector with I-th element given by `sin (2 * pi
     * (I+D-1) / N)'.

     The default value for D is 0 and the default value for N is M.

 -- Function File:  spectral_adf (C, WIN, B)
     Return the spectral density estimator given a vector of
     autocovariances C, window name WIN, and bandwidth, B.

     The window name, e.g., `"triangle"' or `"rectangle"' is used to
     search for a function called `WIN_sw'.

     If WIN is omitted, the triangle window is used.  If B is omitted,
     `1 / sqrt (length (X))' is used.

 -- Function File:  spectral_xdf (X, WIN, B)
     Return the spectral density estimator given a data vector X,
     window name WIN, and bandwidth, B.

     The window name, e.g., `"triangle"' or `"rectangle"' is used to
     search for a function called `WIN_sw'.

     If WIN is omitted, the triangle window is used.  If B is omitted,
     `1 / sqrt (length (X))' is used.

 -- Function File:  spencer (X)
     Return Spencer's 15 point moving average of each column of X.

 -- Function File: [Y, C] = stft (X, WIN_SIZE, INC, NUM_COEF, WIN_TYPE)
     Compute the short-time Fourier transform of the vector X with
     NUM_COEF coefficients by applying a window of WIN_SIZE data points
     and an increment of INC points.

     Before computing the Fourier transform, one of the following
     windows is applied:

    hanning
          win_type = 1

    hamming
          win_type = 2

    rectangle
          win_type = 3

     The window names can be passed as strings or by the WIN_TYPE
     number.

     If not all arguments are specified, the following defaults are
     used: WIN_SIZE = 80, INC = 24, NUM_COEF = 64, and WIN_TYPE = 1.

     `Y = stft (X, ...)' returns the absolute values of the Fourier
     coefficients according to the NUM_COEF positive frequencies.

     `[Y, C] = stft (`x', ...)' returns the entire STFT-matrix Y and a
     3-element vector C containing the window size, increment, and
     window type, which is needed by the synthesis function.

 -- Function File:  synthesis (Y, C)
     Compute a signal from its short-time Fourier transform Y and a
     3-element vector C specifying window size, increment, and window
     type.

     The values Y and C can be derived by

          [Y, C] = stft (X , ...)

 -- Function File:  triangle_lw (N, B)
     Triangular lag window.  Subfunction used for spectral density
     estimation.

 -- Function File:  triangle_sw (N, B)
     Triangular spectral window.  Subfunction used for spectral density
     estimation.

 -- Function File: [A, V] = yulewalker (C)
     Fit an AR (p)-model with Yule-Walker estimates given a vector C of
     autocovariances `[gamma_0, ..., gamma_p]'.

     Returns the AR coefficients, A, and the variance of white noise, V.


File: octave.info,  Node: Image Processing,  Next: Audio Processing,  Prev: Signal Processing,  Up: Top

31 Image Processing
*******************

Since an image basically is a matrix Octave is a very powerful
environment for processing and analyzing images.  To illustrate how
easy it is to do image processing in Octave, the following example will
load an image, smooth it by a 5-by-5 averaging filter, and compute the
gradient of the smoothed image.

     I = imread ("myimage.jpg");
     S = conv2 (I, ones (5, 5) / 25, "same");
     [Dx, Dy] = gradient (S);

In this example `S' contains the smoothed image, and `Dx' and `Dy'
contains the partial spatial derivatives of the image.

* Menu:

* Loading and Saving Images::
* Displaying Images::
* Representing Images::
* Plotting on top of Images::
* Color Conversion::


File: octave.info,  Node: Loading and Saving Images,  Next: Displaying Images,  Up: Image Processing

31.1 Loading and Saving Images
==============================

The first step in most image processing tasks is to load an image into
Octave.  This is done using the `imread' function, which uses the
`GraphicsMagick' library for reading.  This means a vast number of image
formats is supported.  The `imwrite' function is the corresponding
function for writing images to the disk.

   In summary, most image processing code will follow the structure of
this code

     I = imread ("my_input_image.img");
     J = process_my_image (I);
     imwrite ("my_output_image.img", J);

 -- Function File: [IMG, MAP, ALPHA] = imread (FILENAME)
     Read images from various file formats.

     The size and numeric class of the output depends on the format of
     the image.  A color image is returned as an MxNx3 matrix.
     Gray-level and black-and-white images are of size MxN.  The color
     depth of the image determines the numeric class of the output:
     "uint8" or "uint16" for gray and color, and "logical" for black
     and white.

     *See also:* *note imwrite: doc-imwrite, *note imfinfo: doc-imfinfo.

 -- Function File:  imwrite (IMG, FILENAME)
 -- Function File:  imwrite (IMG, FILENAME, FMT)
 -- Function File:  imwrite (IMG, FILENAME, FMT, P1, V1, ...)
 -- Function File:  imwrite (IMG, MAP, FILENAME, ...)
     Write images in various file formats.

     If FMT is not supplied, the file extension of FILENAME is used to
     determine the format.

     The parameter-value pairs (P1, V1, ...) are optional.  Currently
     the following options are supported for JPEG images:

    `Quality'
          Set the quality of the compression.  The value should be an
          integer between 0 and 100, with larger values indicating
          higher visual quality and lower compression.

     *Supported Formats*
     Extension              Format
     -------------------------------------------------------------------- 
     bmp                    Windows Bitmap
     gif                    Graphics Interchange Format
     jpg and jpeg           Joint Photographic Experts Group
     pbm                    Portable Bitmap
     pcx                    
     pgm                    Portable Graymap
     png                    Portable Network Graphics
     pnm                    Portable Anymap
     ppm                    Portable Pixmap
     ras                    Sun Raster
     tif and tiff           Tagged Image File Format
     xwd                    X11 Dump

     *Unsupported Formats*
     Extension              Format
     -------------------------------------------------------------------- 
     hdf                    Hierarchical Data Format V4
     jp2 and jpx            Joint Photographic Experts Group 2000

     *See also:* *note imread: doc-imread, *note imfinfo: doc-imfinfo.

 -- Built-in Function: VAL = IMAGE_PATH ()
 -- Built-in Function: OLD_VAL = IMAGE_PATH (NEW_VAL)
     Query or set the internal variable that specifies a colon separated
     list of directories in which to search for image files.

   It is possible to get information about an image file on disk,
without actually reading it into Octave.  This is done using the
`imfinfo' function which provides read access to many of the parameters
stored in the header of the image file.

 -- Function File: INFO = imfinfo (FILENAME)
 -- Function File: INFO = imfinfo (URL)
     Read image information from a file.

     `imfinfo' returns a structure containing information about the
     image stored in the file FILENAME.  The output structure contains
     the following fields.

    `Filename'
          The full name of the image file.

    `FileSize'
          Number of bytes of the image on disk

    `FileModDate'
          Date of last modification to the file.

    `Height'
          Image height in pixels.

    `Width'
          Image Width in pixels.

    `BitDepth'
          Number of bits per channel per pixel.

    `Format'
          Image format (e.g., `"jpeg"').

    `LongFormat'
          Long form image format description.

    `XResolution'
          X resolution of the image.

    `YResolution'
          Y resolution of the image.

    `TotalColors'
          Number of unique colors in the image.

    `TileName'
          Tile name.

    `AnimationDelay'
          Time in 1/100ths of a second (0 to 65535) which must expire
          before displaying the next image in an animated sequence.

    `AnimationIterations'
          Number of iterations to loop an animation (e.g., Netscape
          loop extension) for.

    `ByteOrder'
          Endian option for formats that support it.  Is either
          `"little-endian"', `"big-endian"', or `"undefined"'.

    `Gamma'
          Gamma level of the image.  The same color image displayed on
          two different workstations may look different due to
          differences in the display monitor.

    `Matte'
          `true' if the image has transparency.

    `ModulusDepth'
          Image modulus depth (minimum number of bits required to
          support red/green/blue components without loss of accuracy).

    `Quality'
          JPEG/MIFF/PNG compression level.

    `QuantizeColors'
          Preferred number of colors in the image.

    `ResolutionUnits'
          Units of image resolution.  Is either `"pixels per inch"',
          `"pixels per centimeter"', or `"undefined"'.

    `ColorType'
          Image type.  Is either `"grayscale"', `"indexed"',
          `"truecolor"', or `"undefined"'.

    `View'
          FlashPix viewing parameters.

     *See also:* *note imread: doc-imread, *note imwrite: doc-imwrite.


File: octave.info,  Node: Displaying Images,  Next: Representing Images,  Prev: Loading and Saving Images,  Up: Image Processing

31.2 Displaying Images
======================

A natural part of image processing is visualization of an image.  The
most basic function for this is the `imshow' function that shows the
image given in the first input argument.

 -- Function File:  imshow (IM)
 -- Function File:  imshow (IM, LIMITS)
 -- Function File:  imshow (IM, MAP)
 -- Function File:  imshow (RGB, ...)
 -- Function File:  imshow (FILENAME)
 -- Function File:  imshow (..., STRING_PARAM1, VALUE1, ...)
     Display the image IM, where IM can be a 2-dimensional (gray-scale
     image) or a 3-dimensional (RGB image) matrix.

     If LIMITS is a 2-element vector `[LOW, HIGH]', the image is shown
     using a display range between LOW and HIGH.  If an empty matrix is
     passed for LIMITS, the display range is computed as the range
     between the minimal and the maximal value in the image.

     If MAP is a valid color map, the image will be shown as an indexed
     image using the supplied color map.

     If a file name is given instead of an image, the file will be read
     and shown.

     If given, the parameter STRING_PARAM1 has value VALUE1.
     STRING_PARAM1 can be any of the following:
    "displayrange"
          VALUE1 is the display range as described above.

     *See also:* *note image: doc-image, *note imagesc: doc-imagesc,
     *note colormap: doc-colormap, *note gray2ind: doc-gray2ind, *note
     rgb2ind: doc-rgb2ind.

 -- Function File:  image (IMG)
 -- Function File:  image (X, Y, IMG)
     Display a matrix as a color image.  The elements of X are indices
     into the current colormap, and the colormap will be scaled so that
     the extremes of X are mapped to the extremes of the colormap.

     The axis values corresponding to the matrix elements are specified
     in X and Y.  If you're not using gnuplot 4.2 or later, these
     variables are ignored.

     Implementation Note: The origin (0, 0) for images is located in the
     upper left.  For ordinary plots, the origin is located in the lower
     left.  Octave handles this inversion by plotting the data normally,
     and then reversing the direction of the y-axis by setting the
     `ydir' property to `"reverse"'.  This has implications whenever an
     image and an ordinary plot need to be overlaid.  The recommended
     solution is to display the image and then plot the reversed ydata
     using, for example, `flipud (ydata,1)'.

     *See also:* *note imshow: doc-imshow, *note imagesc: doc-imagesc,
     *note colormap: doc-colormap.

 -- Function File:  imagesc (A)
 -- Function File:  imagesc (X, Y, A)
 -- Function File:  imagesc (..., LIMITS)
 -- Function File:  imagesc (H, ...)
 -- Function File: H = imagesc (...)
     Display a scaled version of the matrix A as a color image.  The
     colormap is scaled so that the entries of the matrix occupy the
     entire colormap.  If LIMITS = [LO, HI] are given, then that range
     is set to the 'clim' of the current axes.

     The axis values corresponding to the matrix elements are specified
     in X and Y, either as pairs giving the minimum and maximum values
     for the respective axes, or as values for each row and column of
     the matrix A.

     *See also:* *note image: doc-image, *note imshow: doc-imshow,
     *note caxis: doc-caxis.


File: octave.info,  Node: Representing Images,  Next: Plotting on top of Images,  Prev: Displaying Images,  Up: Image Processing

31.3 Representing Images
========================

In general Octave supports four different kinds of images, gray-scale
images, RGB images, binary images, and indexed images.  A gray-scale
image is represented with an M-by-N matrix in which each element
corresponds to the intensity of a pixel.  An RGB image is represented
with an M-by-N-by-3 array where each 3-vector corresponds to the red,
green, and blue intensities of each pixel.

   The actual meaning of the value of a pixel in a gray-scale or RGB
image depends on the class of the matrix.  If the matrix is of class
`double' pixel intensities are between 0 and 1, if it is of class
`uint8' intensities are between 0 and 255, and if it is of class
`uint16' intensities are between 0 and 65535.

   A binary image is an M-by-N matrix of class `logical'.  A pixel in a
binary image is black if it is `false' and white if it is `true'.

   An indexed image consists of an M-by-N matrix of integers and a
C-by-3 color map.  Each integer corresponds to an index in the color
map, and each row in the color map corresponds to an RGB color.  The
color map must be of class `double' with values between 0 and 1.

 -- Function File: [IMG, MAP] = gray2ind (I, N)
     Convert a gray scale intensity image to an Octave indexed image.
     The indexed image will consist of N different intensity values.
     If not given N will default to 64.

 -- Function File:  ind2gray (X, MAP)
     Convert an Octave indexed image to a gray scale intensity image.
     If MAP is omitted, the current colormap is used to determine the
     intensities.

     *See also:* *note gray2ind: doc-gray2ind, *note rgb2ntsc:
     doc-rgb2ntsc, *note image: doc-image, *note colormap: doc-colormap.

 -- Function File: [X, MAP] = rgb2ind (RGB)
 -- Function File: [X, MAP] = rgb2ind (R, G, B)
     Convert an RGB image to an Octave indexed image.

     *See also:* *note ind2rgb: doc-ind2rgb, *note rgb2ntsc:
     doc-rgb2ntsc.

 -- Function File: RGB = ind2rgb (X, MAP)
 -- Function File: [R, R, R] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.
     If the colormap doesn't contain enough colors, pad it with the
     last color in the map.  If MAP is omitted, the current colormap is
     used for the conversion.

     *See also:* *note rgb2ind: doc-rgb2ind, *note image: doc-image,
     *note imshow: doc-imshow, *note ind2gray: doc-ind2gray, *note
     gray2ind: doc-gray2ind.

 -- Function File:  colormap (MAP)
 -- Function File:  colormap ("default")
     Set the current colormap.

     `colormap (MAP)' sets the current colormap to MAP.  The color map
     should be an N row by 3 column matrix.  The columns contain red,
     green, and blue intensities respectively.  All entries should be
     between 0 and 1 inclusive.  The new colormap is returned.

     `colormap ("default")' restores the default colormap (the `jet'
     map with 64 entries).  The default colormap is returned.

     With no arguments, `colormap' returns the current color map.

     *See also:* *note jet: doc-jet.

 -- Function File: MAP = autumn ()
 -- Function File: MAP = autumn (N)
     Create color colormap.  This colormap ranges from red through
     orange to yellow.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = bone ()
 -- Function File: MAP = bone (N)
     Create color colormap.  This colormap varies from black to white
     with gray-blue shades.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = cool ()
 -- Function File: MAP = cool (N)
     Create color colormap.  The colormap varies from cyan to magenta.
     The argument N must be a scalar.  If unspecified, the length of
     the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = copper ()
 -- Function File: MAP = copper (N)
     Create color colormap.  This colormap varies from black to a light
     copper tone.  The argument N must be a scalar.  If unspecified,
     the length of the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = flag ()
 -- Function File: MAP = flag (N)
     Create color colormap.  This colormap cycles through red, white,
     blue and black with each index change.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or
     64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = gray ()
 -- Function File: MAP = gray (N)
     Create gray colormap.  This colormap varies from black to white
     with shades of gray.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

 -- Function File: MAP = hot ()
 -- Function File: MAP = hot (N)
     Create color colormap.  This colormap ranges from black through
     dark red, red, orange, yellow, to white.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or
     64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File:  hsv (N)
     Create color colormap.  This colormap begins with red, changes
     through yellow, green, cyan, blue, and magenta, before returning
     to red.  It is useful for displaying periodic functions.  It is
     obtained by linearly varying the hue through all possible values
     while keeping constant maximum saturation and value and is
     equivalent to `hsv2rgb ([linspace(0,1,N)', ones(N,2)])'.

     The argument N must be a scalar.  If unspecified, the length of
     the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = jet ()
 -- Function File: MAP = jet (N)
     Create color colormap.  This colormap ranges from dark blue
     through blue, cyan, green, yellow, red, to dark red.  The argument
     N must be a scalar.  If unspecified, the length of the current
     colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = ocean ()
 -- Function File: MAP = ocean (N)
     Create color colormap.  This colormap varies from black to white
     with shades of blue.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

 -- Function File: MAP = pink ()
 -- Function File: MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.  It gives a sepia tone when used on
     grayscale images.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = prism ()
 -- Function File: MAP = prism (N)
     Create color colormap.  This colormap cycles through red, orange,
     yellow, green, blue and violet with each index change.  The
     argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = rainbow ()
 -- Function File: MAP = rainbow (N)
     Create color colormap.  This colormap ranges from red through
     orange, yellow, green, blue, to violet.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or
     64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = spring ()
 -- Function File: MAP = spring (N)
     Create color colormap.  This colormap varies from magenta to
     yellow.  The argument N must be a scalar.  If unspecified, the
     length of the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = summer ()
 -- Function File: MAP = summer (N)
     Create color colormap.  This colormap varies from green to yellow.
     The argument N must be a scalar.  If unspecified, the length of
     the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = white ()
 -- Function File: MAP = white (N)
     Create color colormap.  This colormap is completely white.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* *note colormap: doc-colormap.

 -- Function File: MAP = winter ()
 -- Function File: MAP = winter (N)
     Create color colormap.  This colormap varies from blue to green.
     The argument N must be a scalar.  If unspecified, the length of
     the current colormap, or 64, is used.

     *See also:* *note colormap: doc-colormap.

 -- Function File:  contrast (X, N)
     Return a gray colormap that maximizes the contrast in an image.
     The returned colormap will have N rows.  If N is not defined then
     the size of the current colormap is used instead.

     *See also:* *note colormap: doc-colormap.

   An additional colormap is `gmap40'.  This code map contains only
colors with integer values of the red, green and blue components.  This
is a workaround for a limitation of gnuplot 4.0, that does not allow
the color of line or patch objects to be set, and so `gmap40' is useful
for gnuplot 4.0 users, and in particular in conjunction with the BAR,
BARH or CONTOUR functions.

 -- Function File: MAP = gmap40 ()
 -- Function File: MAP = gmap40 (N)
     Create color colormap.  The colormap consists of red, green, blue,
     yellow, magenta and cyan.  This colormap is specifically designed
     for users of gnuplot 4.0 where these 6 colors are the allowable
     ones for patch objects.  The argument N must be a scalar.  If
     unspecified, a length of 6 is assumed.  Larger values of N result
     in a repetition of the above colors.

     *See also:* *note colormap: doc-colormap.

   The following three functions modify the existing colormap rather
than replace it.

 -- Function File: MAP_OUT = brighten (MAP, BETA)
 -- Function File: MAP_OUT = brighten (H, BETA)
 -- Function File: MAP_OUT = brighten (BETA)
     Darken or brighten the given colormap.  If the MAP argument is
     omitted, the function is applied to the current colormap.  The
     first argument can also be a valid graphics handle H, in which case
     `brighten' is applied to the colormap associated with this handle.

     Should the resulting colormap MAP_OUT not be assigned, it will be
     written to the current colormap.

     The argument BETA should be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the colormap.

     *See also:* *note colormap: doc-colormap.

 -- Function File:  spinmap (T, INC)
     Cycle the colormap for T seconds with an increment of INC.  Both
     parameters are optional.  The default cycle time is 5 seconds and
     the default increment is 2.

     A higher value of INC causes a faster cycle through the colormap.

     *See also:* *note gca: doc-gca, *note colorbar: doc-colorbar.

 -- Function File:  whitebg ()
 -- Function File:  whitebg (COLOR)
 -- Function File:  whitebg ("none")
 -- Function File:  whitebg (FIG)
 -- Function File:  whitebg (FIG, COLOR)
 -- Function File:  whitebg (FIG, "none")
     Invert the colors in the current color scheme.  The root
     properties are also inverted such that all subsequent plot use the
     new color scheme.

     If defined, FIG is the handle to the figure to be inverted.  In
     this case only the specified figure has its color properties
     changed.

     If the optional argument COLOR is present then the background color
     is set to COLOR rather than inverted.  COLOR may be a string
     representing one of the eight known colors or an RGB triplet.  The
     special string argument "none" restores the plot to the default
     colors.

     *See also:* *note reset: doc-reset.


File: octave.info,  Node: Plotting on top of Images,  Next: Color Conversion,  Prev: Representing Images,  Up: Image Processing

31.4 Plotting on top of Images
==============================

If gnuplot is being used to display images it is possible to plot on
top of images.  Since an image is a matrix it is indexed by row and
column values.  The plotting system is, however, based on the
traditional (x, y) system.  To minimize the difference between the two
systems Octave places the origin of the coordinate system in the point
corresponding to the pixel at (1, 1).  So, to plot points given by row
and column values on top of an image, one should simply call `plot'
with the column values as the first argument and the row values as the
second.  As an example the following code generates an image with
random intensities between 0 and 1, and shows the image with red
circles over pixels with an intensity above 0.99.

     I = rand (100, 100);
     [row, col] = find (I > 0.99);
     hold ("on");
     imshow (I);
     plot (col, row, "ro");
     hold ("off");


File: octave.info,  Node: Color Conversion,  Prev: Plotting on top of Images,  Up: Image Processing

31.5 Color Conversion
=====================

Octave supports conversion from the RGB color system to NTSC and HSV
and vice versa.

 -- Function File: HSV_MAP = rgb2hsv (RGB)
     Transform a colormap or image from the RGB space to the HSV space.

     A color in the RGB space consists of the red, green and blue
     intensities.

     In the HSV space each color is represented by their hue, saturation
     and value (brightness).  Value gives the amount of light in the
     color.  Hue describes the dominant wavelength.  Saturation is the
     amount of hue mixed into the color.

     *See also:* *note hsv2rgb: doc-hsv2rgb.

 -- Function File: RGB_MAP = hsv2rgb (HSV_MAP)
     Transform a colormap or image from the HSV space to the RGB space.

     *See also:* *note rgb2hsv: doc-rgb2hsv.

 -- Function File:  rgb2ntsc (RGB)
     Transform a colormap or image from RGB to NTSC.

     *See also:* *note ntsc2rgb: doc-ntsc2rgb.

 -- Function File:  ntsc2rgb (YIQ)
     Transform a colormap or image from NTSC to RGB.

     *See also:* *note rgb2ntsc: doc-rgb2ntsc.


File: octave.info,  Node: Audio Processing,  Next: Object Oriented Programming,  Prev: Image Processing,  Up: Top

32 Audio Processing
*******************

Octave provides a few functions for dealing with audio data.  An audio
`sample' is a single output value from an A/D converter, i.e., a small
integer number (usually 8 or 16 bits), and audio data is just a series
of such samples.  It can be characterized by three parameters: the
sampling rate (measured in samples per second or Hz, e.g., 8000 or
44100), the number of bits per sample (e.g., 8 or 16), and the number of
channels (1 for mono, 2 for stereo, etc.).

   There are many different formats for representing such data.
Currently, only the two most popular, _linear encoding_ and _mu-law
encoding_, are supported by Octave.  There is an excellent FAQ on audio
formats by Guido van Rossum <guido@cwi.nl> which can be found at any
FAQ ftp site, in particular in the directory
`/pub/usenet/news.answers/audio-fmts' of the archive site
`rtfm.mit.edu'.

   Octave simply treats audio data as vectors of samples (non-mono data
are not supported yet).  It is assumed that audio files using linear
encoding have one of the extensions `lin' or `raw', and that files
holding data in mu-law encoding end in `au', `mu', or `snd'.

 -- Function File:  lin2mu (X, N)
     Convert audio data from linear to mu-law.  Mu-law values use 8-bit
     unsigned integers.  Linear values use N-bit signed integers or
     floating point values in the range -1 <= X <= 1 if N is 0.

     If N is not specified it defaults to 0, 8, or 16 depending on the
     range of values in X.

     *See also:* *note mu2lin: doc-mu2lin, *note loadaudio:
     doc-loadaudio, *note saveaudio: doc-saveaudio.

 -- Function File:  mu2lin (X, N)
     Convert audio data from mu-law to linear.  Mu-law values are 8-bit
     unsigned integers.  Linear values use N-bit signed integers or
     floating point values in the range -1<=y<=1 if N is 0.

     If N is not specified it defaults to 0.

     *See also:* *note lin2mu: doc-lin2mu, *note loadaudio:
     doc-loadaudio, *note saveaudio: doc-saveaudio.

 -- Function File:  loadaudio (NAME, EXT, BPS)
     Load audio data from the file `NAME.EXT' into the vector X.

     The extension EXT determines how the data in the audio file is
     interpreted; the extensions `lin' (default) and `raw' correspond
     to linear, the extensions `au', `mu', or `snd' to mu-law encoding.

     The argument BPS can be either 8 (default) or 16, and specifies
     the number of bits per sample used in the audio file.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note saveaudio: doc-saveaudio, *note playaudio: doc-playaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

 -- Function File:  saveaudio (NAME, X, EXT, BPS)
     Save a vector X of audio data to the file `NAME.EXT'.  The
     optional parameters EXT and BPS determine the encoding and the
     number of bits per sample used in the audio file (see
     `loadaudio'); defaults are `lin' and 8, respectively.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note playaudio: doc-playaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

   The following functions for audio I/O require special A/D hardware
and operating system support.  It is assumed that audio data in linear
encoding can be played and recorded by reading from and writing to
`/dev/dsp', and that similarly `/dev/audio' is used for mu-law
encoding.  These file names are system-dependent.  Improvements so that
these functions will work without modification on a wide variety of
hardware are welcome.

 -- Function File:  playaudio (NAME, EXT)
 -- Function File:  playaudio (X)
     Play the audio file `NAME.EXT' or the audio data stored in the
     vector X.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note saveaudio: doc-saveaudio,
     *note setaudio: doc-setaudio, *note record: doc-record.

 -- Function File:  record (SEC, SAMPLING_RATE)
     Record SEC seconds of audio input into the vector X.  The default
     value for SAMPLING_RATE is 8000 samples per second, or 8kHz.  The
     program waits until the user types <RET> and then immediately
     starts to record.

     *See also:* *note lin2mu: doc-lin2mu, *note mu2lin: doc-mu2lin,
     *note loadaudio: doc-loadaudio, *note saveaudio: doc-saveaudio,
     *note playaudio: doc-playaudio, *note setaudio: doc-setaudio.

 -- Function File:  setaudio ()
 -- Function File:  setaudio (W_TYPE)
 -- Function File:  setaudio (W_TYPE, VALUE)
     Execute the shell command `mixer', possibly with optional
     arguments W_TYPE and VALUE.

 -- Function File: Y = wavread (FILENAME)
     Load the RIFF/WAVE sound file FILENAME, and return the samples in
     vector Y.  If the file contains multichannel data, then Y is a
     matrix with the channels represented as columns.

 -- Function File: [Y, FS, BPS] = wavread (FILENAME)
     Additionally return the sample rate (FS) in Hz and the number of
     bits per sample (BPS).

 -- Function File: [...] = wavread (FILENAME, N)
     Read only the first N samples from each channel.

 -- Function File: [...] = wavread (FILENAME, N1 N2)
     Read only samples N1 through N2 from each channel.

 -- Function File: [SAMPLES, CHANNELS] = wavread (FILENAME, "size")
     Return the number of samples (N) and channels (CH) instead of the
     audio data.

     *See also:* *note wavwrite: doc-wavwrite.

 -- Function File:  wavwrite (Y, FILENAME)
 -- Function File:  wavwrite (Y, FS, FILENAME)
 -- Function File:  wavwrite (Y, FS, BPS, FILENAME)
     Write Y to the canonical RIFF/WAVE sound file FILENAME with sample
     rate FS and bits per sample BPS.  The default sample rate is 8000
     Hz with 16-bits per sample.  Each column of the data represents a
     separate channel.

     *See also:* *note wavread: doc-wavread.


File: octave.info,  Node: Object Oriented Programming,  Next: System Utilities,  Prev: Audio Processing,  Up: Top

33 Object Oriented Programming
******************************

Octave includes the capability to include user classes, including the
features of operator and function overloading.  Equally a user class
can be used to encapsulate certain properties of the class so that they
cannot be altered accidentally and can be set up to address the issue
of class precedence in mixed class operations.

   This chapter discussions the means of constructing a user class with
the example of a polynomial class, how to query and set the properties
of this class, together with the means to overload operators and
functions.

* Menu:

* Creating a Class::
* Manipulating Classes::
* Indexing Objects::
* Overloading Objects::
* Inheritance and Aggregation::


File: octave.info,  Node: Creating a Class,  Next: Manipulating Classes,  Up: Object Oriented Programming

33.1 Creating a Class
=====================

We use in the following text a polynomial class to demonstrate the use
of object oriented programming within Octave.  This class was chosen as
it is simple, and so doesn't distract unnecessarily from the discussion
of the programming features of Octave.  However, even still a small
understand of the polynomial class itself is necessary to fully grasp
the techniques described.

   The polynomial class is used to represent polynomials of the form

     a0 + a1 * x + a2 * x^2 + ... + an * x^n

where a0, a1, etc. are real scalars.  Thus the polynomial can be
represented by a vector

     a = [a0, a1, a2, ..., an];

   We therefore now have sufficient information about the requirements
of the class constructor for our polynomial class to write it.  All
object oriented classes in Octave, must be contained with a directory
taking the name of the class, prepended with the @ symbol.  For
example, with our polynomial class, we would place the methods defining
the class in the @polynomial directory.

   The constructor of the class, must have the name of the class itself
and so in our example the constructor with have the name
`@polynomial/polynomial.m'.  Also ideally when the constructor is
called with no arguments to should return a value object.  So for
example our polynomial might look like

     ## -*- texinfo -*-
     ## @deftypefn {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## Creates a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## from a vector of coefficients [a0 a1 a2 ... an].
     ## @end deftypefn

     function p = polynomial (a)
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
     endfunction

   Note that the return value of the constructor must be the output of
the `class' function called with the first argument being a structure
and the second argument being the class name.  An example of the call
to this constructor function is then

     p = polynomial ([1, 0, 1]);

   Note that methods of a class can be documented.  The help for the
constructor itself can be obtained with the constructor name, that is
for the polynomial constructor `help polynomial' will return the help
string.  Also the help can be obtained by restricting the search for
the help to a particular class, for example `help
@polynomial/polynomial'.  This second method is the only means of
getting help for the overloaded methods and functions of the class.

   The same is true for other Octave functions that take a function name
as an argument.  For example `type @polynomial/display' will print the
code of the display method of the polynomial class to the screen, and
`dbstop @polynomial/display' will set a breakpoint at the first
executable line of the display method of the polynomial class.

   To check where a variable is a user class, the `isobject' and `isa'
functions can be used.  For example:

     p = polynomial ([1, 0, 1]);
     isobject (p)
     => 1
     isa (p, "polynomial")
     => 1

 -- Built-in Function:  isobject (X)
     Return true if X is a class object.

     *See also:* *note class: doc-class, *note typeinfo: doc-typeinfo,
     *note isa: doc-isa, *note ismethod: doc-ismethod.

The available methods of a class can be displayed with the `methods'
function.

 -- Built-in Function:  methods (X)
 -- Built-in Function:  methods ("classname")
     Return a cell array containing the names of the methods for the
     object X or the named class.

To inquire whether a particular method is available to a user class, the
`ismethod' function can be used.

 -- Built-in Function:  ismethod (X, METHOD)
     Return true if X is a class object and the string METHOD is a
     method of this class.

     *See also:* *note isobject: doc-isobject.

For example:

     p = polynomial ([1, 0, 1]);
     ismethod (p, "roots")
     => 1


File: octave.info,  Node: Manipulating Classes,  Next: Indexing Objects,  Prev: Creating a Class,  Up: Object Oriented Programming

33.2 Manipulating Classes
=========================

There are a number of basic classes methods that can be defined to allow
the contents of the classes to be queried and set.  The most basic of
these is the `display' method.  The `display' method is used by Octave
when displaying a class on the screen, due to an expression that is not
terminated with a semicolon.  If this method is not defined, then
Octave will printed nothing when displaying the contents of a class.

 -- Function File:  display (A)
     Display the contents of an object.  If A is an object of the class
     "myclass", then `display' is called in a case like

          myclass (...)

     where Octave is required to display the contents of a variable of
     the type "myclass".

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.

An example of a display method for the polynomial class might be

     function display (p)
       a = p.poly;
       first = true;
       fprintf("%s =", inputname(1));
       for i = 1 : length (a);
         if (a(i) != 0)
           if (first)
             first = false;
           elseif (a(i) > 0)
             fprintf (" +");
           endif
           if (a(i) < 0)
             fprintf (" -");
           endif
           if (i == 1)
             fprintf (" %g", abs (a(i)));
           elseif (abs(a(i)) != 1)
             fprintf (" %g *", abs (a(i)));
           endif
           if (i > 1)
             fprintf (" X");
           endif
           if (i > 2)
             fprintf (" ^ %d", i - 1);
           endif
         endif
       endfor
       if (first)
         fprintf(" 0");
       endif
       fprintf("\n");
     endfunction

Note that in the display method, it makes sense to start the method
with the line `fprintf("%s =", inputname(1))' to be consistent with the
rest of Octave and print the variable name to be displayed when
displaying the class.

   To be consistent with the Octave graphic handle classes, a class
should also define the `get' and `set' methods.  The `get' method
should accept one or two arguments, and given one argument of the
appropriate class it should return a structure with all of the
properties of the class.  For example:

     function s = get (p, f)
       if (nargin == 1)
         s.poly = p.poly;
       elseif (nargin == 2)
         if (ischar (f))
           switch (f)
             case "poly"
               s = p.poly;
             otherwise
               error ("get: invalid property %s", f);
           endswitch
         else
           error ("get: expecting the property to be a string");
         endif
       else
         print_usage ();
       endif
     endfunction

Similarly, the `set' method should taken as its first argument an
object to modify, and then take property/value pairs to be modified.

     function s = set (p, varargin)
       s = p;
       if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
         error ("set: expecting property/value pairs");
       endif
       while (length (varargin) > 1)
         prop = varargin{1};
         val = varargin{2};
         varargin(1:2) = [];
         if (ischar (prop) && strcmp (prop, "poly"))
           if (isvector (val) && isreal (val))
             s.poly = val(:).';
           else
             error ("set: expecting the value to be a real vector");
           endif
         else
           error ("set: invalid property of polynomial class");
         endif
       endwhile
     endfunction

Note that as Octave does not implement pass by reference, than the
modified object is the return value of the `set' method and it must be
called like

     p = set (p, "a", [1, 0, 0, 0, 1]);

Also the `set' method makes use of the `subsasgn' method of the class,
and this method must be defined.  The `subsasgn' method is discussed in
the next section.

   Finally, user classes can be considered as a special type of a
structure, and so they can be saved to a file in the same manner as a
structure.  For example:

     p = polynomial ([1, 0, 1]);
     save userclass.mat p
     clear p
     load userclass.mat

All of the file formats supported by `save' and `load' are supported.
In certain circumstances, a user class might either contain a field
that it makes no sense to save or a field that needs to be initialized
before it is saved.  This can be done with the `saveobj' method of the
class

 -- Function File: B = saveobj (A)
     Method of a class to manipulate an object prior to saving it to a
     file.  The function `saveobj' is called when the object A is saved
     using the `save' function.  An example of the use of `saveobj'
     might be to remove fields of the object that don't make sense to
     be saved or it might be used to ensure that certain fields of the
     object are initialized before the object is saved.  For example:

          function b = saveobj (a)
            b = a;
            if (isempty (b.field))
               b.field = initfield(b);
            endif
          endfunction

     *See also:* *note loadobj: doc-loadobj, *note class: doc-class.

`saveobj' is called just prior to saving the class to a file.  Likely,
the `loadobj' method is called just after a class is loaded from a
file, and can be used to ensure that any removed fields are reinserted
into the user object.

 -- Function File: B = loadobj (A)
     Method of a class to manipulate an object after loading it from a
     file.  The function `loadobj' is called when the object A is loaded
     using the `load' function.  An example of the use of `saveobj'
     might be to add fields to an object that don't make sense to be
     saved.  For example:

          function b = loadobj (a)
            b = a;
            b.addmissingfield = addfield (b);
          endfunction

     *See also:* *note saveobj: doc-saveobj, *note class: doc-class.


File: octave.info,  Node: Indexing Objects,  Next: Overloading Objects,  Prev: Manipulating Classes,  Up: Object Oriented Programming

33.3 Indexing Objects
=====================

* Menu:

* Defining Indexing And Indexed Assignment::
* Indexed Assignment Optimization::


File: octave.info,  Node: Defining Indexing And Indexed Assignment,  Next: Indexed Assignment Optimization,  Up: Indexing Objects

33.3.1 Defining Indexing And Indexed Assignment
-----------------------------------------------

Objects can be indexed with parentheses, either like `A (IDX)' or like
`A {IDX}', or even like `A (IDX).FIELD'.  However, it is up to the user
to decide what this indexing actually means.  In the case of our
polynomial class `P (N)' might mean either the coefficient of the N-th
power of the polynomial, or it might be the evaluation of the
polynomial at N.  The meaning of this subscripted referencing is
determined by the `subsref' method.

 -- Built-in Function:  subsref (VAL, IDX)
     Perform the subscripted element selection operation according to
     the subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     `type' and `subs'.  Valid values for `type' are `"()"', `"{}"',
     and `"."'.  The `subs' field may be either `":"' or a cell array
     of index values.

     The following example shows how to extract the two first columns of
     a matrix

          val = magic(3)
               => val = [ 8   1   6
                          3   5   7
                          4   9   2 ]
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsref(val, idx)
               => [ 8   1
                    3   5
                    4   9 ]

     Note that this is the same as writing `val(:,1:2)'.

     *See also:* *note subsasgn: doc-subsasgn, *note substruct:
     doc-substruct.

   For example we might decide that indexing with "()" evaluates the
polynomial and indexing with "{}" returns the N-th coefficient (of N-th
power).  In this case the `subsref' method of our polynomial class
might look like

     function b = subsref (a, s)
       if (isempty (s))
         error ("polynomial: missing index");
       endif
       switch (s(1).type)
         case "()"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             b = polyval (fliplr (a.poly), ind{1});
           endif
         case "{}"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             if (isnumeric (ind{1}))
               b = a.poly(ind{1}+1);
             else
               b = a.poly(ind{1});
             endif
           endif
         case "."
           fld = s.subs;
           if (strcmp (fld, "poly"))
             b = a.poly;
           else
             error ("@polynomial/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("invalid subscript type");
       endswitch
       if (numel (s) > 1)
         b = subsref (b, s(2:end));
       endif
     endfunction

   The equivalent functionality for subscripted assignments uses the
`subsasgn' method.

 -- Built-in Function:  subsasgn (VAL, IDX, RHS)
     Perform the subscripted assignment operation according to the
     subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     `type' and `subs'.  Valid values for `type' are `"()"', `"{}"',
     and `"."'.  The `subs' field may be either `":"' or a cell array
     of index values.

     The following example shows how to set the two first columns of a
     3-by-3 matrix to zero.

          val = magic(3);
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsasgn (val, idx, 0)
               => [ 0   0   6
                    0   0   7
                    0   0   2 ]

     Note that this is the same as writing `val(:,1:2) = 0'.

     *See also:* *note subsref: doc-subsref, *note substruct:
     doc-substruct.

 -- Built-in Function: VAL = optimize_subsasgn_calls ()
 -- Built-in Function: OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
     Query or set the internal flag for subsasgn method call
     optimizations.  If true, Octave will attempt to eliminate the
     redundant copying when calling subsasgn method of a user-defined
     class.

   Note that the `subsref' and `subsasgn' methods always receive the
whole index chain, while they usually handle only the first element.
It is the responsibility of these methods to handle the rest of the
chain (if needed), usually by forwarding it again to `subsref' or
`subsasgn'.

   If you wish to use the `end' keyword in subscripted expressions of
an object, then the user needs to define the `end' method for the
class.  For example, the `end' method for our polynomial class might
look like

     function r = end (obj, index_pos, num_indices)

       if (num_indices != 1)
         error ("polynomial object may only have one index")
       endif

       r = length (obj.poly) - 1;

     endfunction

which is a fairly generic `end' method that has a behavior similar to
the `end' keyword for Octave Array classes.  It can then be used as
follows:

     p = polynomial([1,2,3,4]);
     p(end-1)
     => 3

   Objects can also be used as the index in a subscripted expression
themselves and this is controlled with the `subsindex' function.

 -- Function File: IDX = subsindex (A)
     Convert an object to an index vector.  When A is a class object
     defined with a class constructor, then `subsindex' is the
     overloading method that allows the conversion of this class object
     to a valid indexing vector.  It is important to note that
     `subsindex' must return a zero-based real integer vector of the
     class "double".  For example, if the class constructor

          function b = myclass (a)
           b = class (struct ("a", a), "myclass");
          endfunction

     then the `subsindex' function

          function idx = subsindex (a)
           idx = double (a.a) - 1.0;
          endfunction

     can then be used as follows

          a = myclass (1:4);
          b = 1:10;
          b(a)
          => 1  2  3  4

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.

   Finally, objects can equally be used like ranges, using the `colon'
method

 -- Function File: R = colon (A, B)
 -- Function File: R = colon (A, B, C)
     Method of a class to construct a range with the `:' operator.  For
     example:

          a = myclass (...)
          b = myclass (...)
          c = a : b

     *See also:* *note class: doc-class, *note subsref: doc-subsref,
     *note subsasgn: doc-subsasgn.


File: octave.info,  Node: Indexed Assignment Optimization,  Prev: Defining Indexing And Indexed Assignment,  Up: Indexing Objects

33.3.2 Indexed Assignment Optimization
--------------------------------------

Octave's ubiquitous lazily-copied pass-by-value semantics implies a
problem for performance of user-defined subsasgn methods.  Imagine a
call to subsasgn:

       ss = substruct ("()",{1});
       x = subsasgn (x, ss, 1);

and the corresponding method looking like this:

       function x = subsasgn (x, ss, val)
         ...
         x.myfield(ss.subs{1}) = val;
       endfunction

   The problem is that on entry to the subsasgn method, `x' is still
referenced from the caller's scope, which means that the method will
first need to unshare (copy) `x' and `x.myfield' before performing the
assignment.  Upon completing the call, unless an error occurs, the
result is immediately assigned to `x' in the caller's scope, so that
the previous value of `x.myfield' is forgotten.  Hence, the Octave
language implies a copy of N elements (N being the size of
`x.myfield'), where modifying just a single element would actually
suffice, i.e., degrades a constant-time operation to linear-time one.
This may be a real problem for user classes that intrinsically store
large arrays.

   To partially solve the problem, Octave uses a special optimization
for user-defined subsasgn methods coded as m-files.  When the method
gets called as a result of the built-in assignment syntax (not direct
subsasgn call as shown above), i.e.

       x(1) = 1;

   AND if the subsasgn method is declared with identical input and
output argument, like in the example above, then Octave will ignore the
copy of `x' inside the caller's scope; therefore, any changes made to
`x' during the method execution will directly affect the caller's copy
as well.  This allows, for instance, defining a polynomial class where
modifying a single element takes constant time.

   It is important to understand the implications that this
optimization brings.  Since no extra copy of `x' in the caller's scope
will exist, it is _solely_ the callee's responsibility to not leave `x'
in an invalid state if an error occurs throughout the execution.  Also,
if the method partially changes `x' and then errors out, the changes
_will_ affect `x' in the caller's scope.  Deleting or completely
replacing `x' inside subsasgn will not do anything, however, only
indexed assignments matter.

   Since this optimization may change the way code works (especially if
badly written), a built-in variable `optimize_subsasgn_calls' is
provided to control it.  It is on by default.  Another option to avoid
the effect is to declare subsasgn methods with different output and
input arguments, like this:

       function y = subsasgn (x, ss, val)
         ...
       endfunction


File: octave.info,  Node: Overloading Objects,  Next: Inheritance and Aggregation,  Prev: Indexing Objects,  Up: Object Oriented Programming

33.4 Overloading Objects
========================

* Menu:

* Function Overloading::
* Operator Overloading::
* Precedence of Objects::


File: octave.info,  Node: Function Overloading,  Next: Operator Overloading,  Up: Overloading Objects

33.4.1 Function Overloading
---------------------------

Any Octave function can be overloaded, and allows an object specific
version of this function to be called as needed.  A pertinent example
for our polynomial class might be to overload the `polyval' function
like

     function [y, dy] = polyval (p, varargin)
       if (nargout == 2)
         [y, dy] = polyval (fliplr(p.poly), varargin{:});
       else
         y = polyval (fliplr(p.poly), varargin{:});
       endif
     endfunction

   This function just hands off the work to the normal Octave `polyval'
function.  Another interesting example for an overloaded function for
our polynomial class is the `plot' function.

     function h = plot(p, varargin)
       n = 128;
       rmax = max (abs (roots (p.poly)));
       x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
       if (nargout > 0)
         h = plot(x, p(x), varargin{:});
       else
         plot(x, p(x), varargin{:});
       endif
     endfunction

which allows polynomials to be plotted in the domain near the region of
the roots of the polynomial.

   Functions that are of particular interest to be overloaded are the
class conversion functions such as `double'.  Overloading these
functions allows the `cast' function to work with the user class and
can aid in the use of methods of other classes with the user class.  An
example `double' function for our polynomial class might look like.

     function b = double (a)
       b = a.poly;
     endfunction


File: octave.info,  Node: Operator Overloading,  Next: Precedence of Objects,  Prev: Function Overloading,  Up: Overloading Objects

33.4.2 Operator Overloading
---------------------------

        Operation      Method         Description                   
---------------------------------------------------------------------------- 
        a + b          plus (a, b)    Binary addition               
        a - b          minus (a, b)   Binary subtraction operator   
        + a            uplus (a)      Unary addition operator       
        - a            uminus (a)     Unary subtraction operator    
        a .* b         times (a, b)   Element-wise multiplication   
                                      operator                      
        a * b          mtimes (a, b)  Matrix multiplication         
                                      operator                      
        a ./ b         rdivide (a,    Element-wise right division   
                       b)             operator                      
        a / b          mrdivide (a,   Matrix right division         
                       b)             operator                      
        a .\ b         ldivide (a,    Element-wise left division    
                       b)             operator                      
        a \ b          mldivide (a,   Matrix left division          
                       b)             operator                      
        a .^ b         ldivide (a,    Element-wise power operator   
                       b)                                           
        a ^ b          mldivide (a,   Matrix power operator         
                       b)                                           
        a < b          lt (a, b)      Less than operator            
        a <= b         le (a, b)      Less than or equal to         
                                      operator                      
        a > b          gt (a, b)      Greater than operator         
        a >= b         ge (a, b)      Greater than or equal to      
                                      operator                      
        a == b         eq (a, b)      Equal to operator             
        a != b         ne (a, b)      Not equal to operator         
        a \& b         and (a, b)     Logical and operator          
        a | b          or (a, b)      Logical or operator           
        ! b            not (a)        Logical not operator          
        a'             ctranspose     Complex conjugate transpose   
                       (a)            operator                      
        a.'            transpose (a)  Transpose operator            
        a : b          colon (a, b)   Two element range operator    
        a : b : c      colon (a, b,   Three element range operator  
                       c)                                           
        [a, b]         horzcat (a,    Horizontal concatenation      
                       b)             operator                      
        [a; b]         vertcat (a,    Vertical concatenation        
                       b)             operator                      
        a(s_1, ...,    subsref (a,    Subscripted reference         
        s_n)           s)                                           
        a(s_1, ...,    subsasgn (a,   Subscripted assignment        
        s_n) = b       s, b)                                        
        b (a)          subsindex (a)  Convert to zero-based index   
        "display"      display (a)    Commandline display function  

Table 33.1: Available overloaded operators and their corresponding
class method

   An example `mtimes' method for our polynomial class might look like

     function y = mtimes (a, b)
       y = polynomial (conv (double(a),double(b)));
     endfunction


File: octave.info,  Node: Precedence of Objects,  Prev: Operator Overloading,  Up: Overloading Objects

33.4.3 Precedence of Objects
----------------------------

Many functions and operators take two or more arguments and so the case
can easily arise that these functions are called with objects of
different classes.  It is therefore necessary to determine the
precedence of which method of which class to call when there are mixed
objects given to a function or operator.  To do this the `superiorto'
and `inferiorto' functions can be used

 -- Built-in Function:  superiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a higher precedence than CLASS_NAME.  More
     that one such class can be specified in a single call.  This
     function may only be called from a class constructor.

 -- Built-in Function:  inferiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a lower precedence than CLASS_NAME.  More
     that one such class can be specified in a single call.  This
     function may only be called from a class constructor.

   For example with our polynomial class consider the case

     2 * polynomial ([1, 0, 1]);

That mixes an object of the class "double" with an object of the class
"polynomial".  In this case we like to ensure that the return type of
the above is of the type "polynomial" and so we use the `superiorto'
function in the class constructor.  In particular our polynomial class
constructor would be modified to be

     ## -*- texinfo -*-
     ## @deftypefn {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## Creates a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## from a vector of coefficients [a0 a1 a2 ... an].
     ## @end deftypefn

     function p = polynomial (a)
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
       superiorto ("double");
     endfunction

   Note that user classes always have higher precedence than built-in
Octave types.  So in fact marking our polynomial class higher than the
"double" class is in fact not necessary.


File: octave.info,  Node: Inheritance and Aggregation,  Prev: Overloading Objects,  Up: Object Oriented Programming

33.5 Inheritance and Aggregation
================================

Using classes to build new classes is supported by octave through the
use of both inheritance and aggregation.

   Class inheritance is provided by octave using the `class' function
in the class constructor.  As in the case of the polynomial class, the
octave programmer will create a struct that contains the data fields
required by the class, and then call the class function to indicate
that an object is to be created from the struct.  Creating a child of
an existing object is done by creating an object of the parent class
and providing that object as the third argument of the class function.

   This is easily demonstrated by example.  Suppose the programmer needs
an FIR filter, i.e., a filter with a numerator polynomial but a unity
denominator polynomial.  In traditional octave programming, this would
be performed as follows.

     octave:1> x = [some data vector];
     octave:2> n = [some coefficient vector];
     octave:3> y = filter (n, 1, x);

   The equivalent class could be implemented in a class directory
@FIRfilter that is on the octave path.  The constructor is a file
FIRfilter.m in the class directory.

     ## -*- texinfo -*-
     ## @deftypefn {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Creates an FIR filter with polynomial @var{p} as
     ## coefficient vector.
     ##
     ## @end deftypefn

     function f = FIRfilter (p)

       f.polynomial = [];
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (nargin == 1)
         if (!isa (p, "polynomial"))
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter", p);
     endfunction

   As before, the leading comments provide command-line documentation
for the class constructor.  This constructor is very similar to the
polynomial class constructor, except that we pass a polynomial object
as the third argument to the class function, telling octave that the
FIRfilter class will be derived from the polynomial class.  Our FIR
filter does not have any data fields, but we must provide a struct to
the `class' function.  The `class' function will add an element named
polynomial to the object struct, so we simply add a dummy element named
polynomial as the first line of the constructor.  This dummy element
will be overwritten by the class function.

   Note further that all our examples provide for the case in which no
arguments are supplied.  This is important since octave will call the
constructor with no arguments when loading objects from save files to
determine the inheritance structure.

   A class may be a child of more than one class (see the documentation
for the `class' function), and inheritance may be nested.  There is no
limitation to the number of parents or the level of nesting other than
memory or other physical issues.

   As before, we need a `display' method.  A simple example might be

     function display (f)

       display(f.polynomial);

     endfunction

   Note that we have used the polynomial field of the struct to display
the filter coefficients.

   Once we have the class constructor and display method, we may create
an object by calling the class constructor.  We may also check the
class type and examine the underlying structure.

     octave:1> f=FIRfilter(polynomial([1 1 1]/3))
     f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     octave:2> class(f)
     ans = FIRfilter
     octave:3> isa(f,"FIRfilter")
     ans =  1
     octave:4> isa(f,"polynomial")
     ans =  1
     octave:5> struct(f)
     ans =
     {
     polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     }

   We only need to define a method to actually process data with our
filter and our class is usable.  It is also useful to provide a means
of changing the data stored in the class.  Since the fields in the
underlying struct are private by default, we could provide a mechanism
to access the fields.  The `subsref' method may be used for both.

     function out = subsref (f, x)
       switch x.type
         case "()"
           n = f.polynomial;
           out = filter(n.poly, 1, x.subs{1});
         case "."
           fld = x.subs;
           if (strcmp (fld, "polynomial"))
             out = f.polynomial;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("@FIRfilter/subsref: invalid subscript type for FIR filter");
       endswitch
     endfunction

   The "()" case allows us to filter data using the polynomial provided
to the constructor.

     octave:2> f=FIRfilter(polynomial([1 1 1]/3));
     octave:3> x=ones(5,1);
     octave:4> y=f(x)
     y =

        0.33333
        0.66667
        1.00000
        1.00000
        1.00000

   The "." case allows us to view the contents of the polynomial field.

     octave:1> f=FIRfilter(polynomial([1 1 1]/3));
     octave:2> f.polynomial
     ans = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2

   In order to change the contents of the object, we need to define a
`subsasgn' method.  For example, we may make the polynomial field
publicly writable.

     function out = subsasgn (f, index, val)
       switch (index.type)
         case "."
           fld = index.subs;
           if (strcmp (fld, "polynomial"))
             out = f;
             out.polynomial = val;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("FIRfilter/subsagn: Invalid index type")
       endswitch
     endfunction

   So that

     octave:6> f=FIRfilter();
     octave:7> f.polynomial = polynomial([1 2 3]);
     f.polynomial = 1 + 2 * X + 3 * X ^ 2

   Defining the FIRfilter class as a child of the polynomial class
implies that and FIRfilter object may be used any place that a
polynomial may be used.  This is not a normal use of a filter, so that
aggregation may be a more sensible design approach.  In this case, the
polynomial is simply a field in the class structure.  A class
constructor for this case might be

     ## -*- texinfo -*-
     ## @deftypefn {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Creates an FIR filter with polynomial @var{p} as
     ## coefficient vector.
     ##
     ## @end deftypefn

     function f = FIRfilter (p)

       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       elseif (nargin == 1)
         if (isa (p, "polynomial"))
           f.polynomial = p;
         else
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter");
     endfunction

   For our example, the remaining class methods remain unchanged.


File: octave.info,  Node: System Utilities,  Next: Packages,  Prev: Object Oriented Programming,  Up: Top

34 System Utilities
*******************

This chapter describes the functions that are available to allow you to
get information about what is happening outside of Octave, while it is
still running, and use this information in your program.  For example,
you can get information about environment variables, the current time,
and even start other programs from the Octave prompt.

* Menu:

* Timing Utilities::
* Filesystem Utilities::
* File Archiving Utilities::
* Networking Utilities::
* Controlling Subprocesses::
* Process ID Information::
* Environment Variables::
* Current Working Directory::
* Password Database Functions::
* Group Database Functions::
* System Information::
* Hashing Functions::


File: octave.info,  Node: Timing Utilities,  Next: Filesystem Utilities,  Up: System Utilities

34.1 Timing Utilities
=====================

Octave's core set of functions for manipulating time values are
patterned after the corresponding functions from the standard C library.
Several of these functions use a data structure for time that includes
the following elements:

`usec'
     Microseconds after the second (0-999999).

`sec'
     Seconds after the minute (0-61).  This number can be 61 to account
     for leap seconds.

`min'
     Minutes after the hour (0-59).

`hour'
     Hours since midnight (0-23).

`mday'
     Day of the month (1-31).

`mon'
     Months since January (0-11).

`year'
     Years since 1900.

`wday'
     Days since Sunday (0-6).

`yday'
     Days since January 1 (0-365).

`isdst'
     Daylight Savings Time flag.

`zone'
     Time zone.

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

 -- Loadable Function: SECONDS = time ()
     Return the current time as the number of seconds since the epoch.
     The epoch is referenced to 00:00:00 CUT (Coordinated Universal
     Time) 1 Jan 1970.  For example, on Monday February 17, 1997 at
     07:15:06 CUT, the value returned by `time' was 856163706.

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note gmtime:
     doc-gmtime, *note mktime: doc-mktime, *note now: doc-now, *note
     date: doc-date, *note clock: doc-clock, *note datenum:
     doc-datenum, *note datestr: doc-datestr, *note datevec:
     doc-datevec, *note calendar: doc-calendar, *note weekday:
     doc-weekday.

 -- Function File: t = now ()
     Return the current local time as the number of days since Jan 1,
     0000.  By this reckoning, Jan 1, 1970 is day number 719529.

     The integral part, `floor (now)' corresponds to 00:00:00 today.

     The fractional part, `rem (now, 1)' corresponds to the current
     time on Jan 1, 0000.

     The returned value is also called a "serial date number" (see
     `datenum').

     *See also:* *note clock: doc-clock, *note date: doc-date, *note
     datenum: doc-datenum.

 -- Function File:  ctime (T)
     Convert a value returned from `time' (or any other non-negative
     integer), to the local time and return a string of the same form as
     `asctime'.  The function `ctime (time)' is equivalent to `asctime
     (localtime (time))'.  For example:

          ctime (time ())
               => "Mon Feb 17 01:15:06 1997\n"

 -- Loadable Function: TM_STRUCT = gmtime (T)
     Given a value returned from `time', or any non-negative integer,
     return a time structure corresponding to CUT (Coordinated
     Universal Time).  For example:

          gmtime (time ())
               => {
                     usec = 0
                     sec = 6
                     min = 15
                     hour = 7
                     mday = 17
                     mon = 1
                     year = 97
                     wday = 1
                     yday = 47
                     isdst = 0
                     zone = CST
                   }

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note mktime:
     doc-mktime, *note time: doc-time, *note now: doc-now, *note date:
     doc-date, *note clock: doc-clock, *note datenum: doc-datenum,
     *note datestr: doc-datestr, *note datevec: doc-datevec, *note
     calendar: doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: TM_STRUCT = localtime (T)
     Given a value returned from `time', or any non-negative integer,
     return a time structure corresponding to the local time zone.

          localtime (time ())
               => {
                     usec = 0
                     sec = 6
                     min = 15
                     hour = 1
                     mday = 17
                     mon = 1
                     year = 97
                     wday = 1
                     yday = 47
                     isdst = 0
                     zone = CST
                   }

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: SECONDS = mktime (TM_STRUCT)
     Convert a time structure corresponding to the local time to the
     number of seconds since the epoch.  For example:

          mktime (localtime (time ()))
               => 856163706

     *See also:* *note strftime: doc-strftime, *note strptime:
     doc-strptime, *note localtime: doc-localtime, *note gmtime:
     doc-gmtime, *note time: doc-time, *note now: doc-now, *note date:
     doc-date, *note clock: doc-clock, *note datenum: doc-datenum,
     *note datestr: doc-datestr, *note datevec: doc-datevec, *note
     calendar: doc-calendar, *note weekday: doc-weekday.

 -- Function File:  asctime (TM_STRUCT)
     Convert a time structure to a string using the following five-field
     format: Thu Mar 28 08:40:14 1996.  For example:

          asctime (localtime (time ()))
               => "Mon Feb 17 01:15:06 1997\n"

     This is equivalent to `ctime (time ())'.

 -- Loadable Function:  strftime (FMT, TM_STRUCT)
     Format the time structure TM_STRUCT in a flexible way using the
     format string FMT that contains `%' substitutions similar to those
     in `printf'.  Except where noted, substituted fields have a fixed
     size; numeric fields are padded if necessary.  Padding is with
     zeros by default; for fields that display a single number, padding
     can be changed or inhibited by following the `%' with one of the
     modifiers described below.  Unknown field specifiers are copied as
     normal characters.  All other characters are copied to the output
     without change.  For example:

          strftime ("%r (%Z) %A %e %B %Y", localtime (time ()))
               => "01:15:06 AM (CST) Monday 17 February 1997"

     Octave's `strftime' function supports a superset of the ANSI C
     field specifiers.

     Literal character fields:

    `%'
          % character.

    `n'
          Newline character.

    `t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

    `- (dash)'
          Do not pad the field.

    `_ (underscore)'
          Pad the field with spaces.

     Time fields:

    `%H'
          Hour (00-23).

    `%I'
          Hour (01-12).

    `%k'
          Hour (0-23).

    `%l'
          Hour (1-12).

    `%M'
          Minute (00-59).

    `%p'
          Locale's AM or PM.

    `%r'
          Time, 12-hour (hh:mm:ss [AP]M).

    `%R'
          Time, 24-hour (hh:mm).

    `%s'
          Time in seconds since 00:00:00, Jan 1, 1970 (a nonstandard
          extension).

    `%S'
          Second (00-61).

    `%T'
          Time, 24-hour (hh:mm:ss).

    `%X'
          Locale's time representation (%H:%M:%S).

    `%Z'
          Time zone (EDT), or nothing if no time zone is determinable.

     Date fields:

    `%a'
          Locale's abbreviated weekday name (Sun-Sat).

    `%A'
          Locale's full weekday name, variable length (Sunday-Saturday).

    `%b'
          Locale's abbreviated month name (Jan-Dec).

    `%B'
          Locale's full month name, variable length (January-December).

    `%c'
          Locale's date and time (Sat Nov 04 12:02:33 EST 1989).

    `%C'
          Century (00-99).

    `%d'
          Day of month (01-31).

    `%e'
          Day of month ( 1-31).

    `%D'
          Date (mm/dd/yy).

    `%h'
          Same as %b.

    `%j'
          Day of year (001-366).

    `%m'
          Month (01-12).

    `%U'
          Week number of year with Sunday as first day of week (00-53).

    `%w'
          Day of week (0-6).

    `%W'
          Week number of year with Monday as first day of week (00-53).

    `%x'
          Locale's date representation (mm/dd/yy).

    `%y'
          Last two digits of year (00-99).

    `%Y'
          Year (1970-).

     *See also:* *note strptime: doc-strptime, *note localtime:
     doc-localtime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

 -- Loadable Function: [TM_STRUCT, NCHARS] = strptime (STR, FMT)
     Convert the string STR to the time structure TM_STRUCT under the
     control of the format string FMT.

     If FMT fails to match, NCHARS is 0; otherwise, it is set to the
     position of last matched character plus 1. Always check for this
     unless you're absolutely sure the date string will be parsed
     correctly.

     *See also:* *note strftime: doc-strftime, *note localtime:
     doc-localtime, *note gmtime: doc-gmtime, *note mktime: doc-mktime,
     *note time: doc-time, *note now: doc-now, *note date: doc-date,
     *note clock: doc-clock, *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note datevec: doc-datevec, *note calendar:
     doc-calendar, *note weekday: doc-weekday.

   Most of the remaining functions described in this section are not
patterned after the standard C library.  Some are available for
compatibility with MATLAB and others are provided because they are
useful.

 -- Function File:  clock ()
     Return a vector containing the current year, month (1-12), day
     (1-31), hour (0-23), minute (0-59) and second (0-61).  For example:

          clock ()
               => [ 1993, 8, 20, 4, 56, 1 ]

     The function clock is more accurate on systems that have the
     `gettimeofday' function.

 -- Function File:  date ()
     Return the date as a character string in the form DD-MMM-YY.  For
     example:

          date ()
               => "20-Aug-93"

 -- Function File:  etime (T2, T1)
     Return the difference in seconds between two time values returned
     from `clock' (T2 - T1).  For example:

          t0 = clock ();
           many computations later...
          elapsed_time = etime (clock (), t0);

     will set the variable `elapsed_time' to the number of seconds since
     the variable `t0' was set.

     *See also:* *note tic: doc-tic, *note toc: doc-toc, *note clock:
     doc-clock, *note cputime: doc-cputime.

 -- Built-in Function: [TOTAL, USER, SYSTEM] = cputime ();
     Return the CPU time used by your Octave session.  The first output
     is the total time spent executing your process and is equal to the
     sum of second and third outputs, which are the number of CPU
     seconds spent executing in user mode and the number of CPU seconds
     spent executing in system mode, respectively.  If your system does
     not have a way to report CPU time usage, `cputime' returns 0 for
     each of its output values.  Note that because Octave used some CPU
     time to start, it is reasonable to check to see if `cputime' works
     by checking to see if the total CPU time used is nonzero.

 -- Function File:  is_leap_year ()
 -- Function File:  is_leap_year (YEAR)
     Return true if the given year is a leap year and false otherwise.
     If no year is provided, `is_leap_year' will use the current year.
     For example:

          is_leap_year (2000)
               => 1

 -- Built-in Function:  tic ()
 -- Built-in Function:  toc ()
     Set or check a wall-clock timer.  Calling `tic' without an output
     argument sets the timer.  Subsequent calls to `toc' return the
     number of seconds since the timer was set.  For example,

          tic ();
          # many computations later...
          elapsed_time = toc ();

     will set the variable `elapsed_time' to the number of seconds since
     the most recent call to the function `tic'.

     If called with one output argument then this function returns a
     scalar of type `uint64' and the wall-clock timer is not started.

          t = tic; sleep (5); (double (tic ()) - double (t)) * 1e-6
               => 5

     Nested timing with `tic' and `toc' is not supported.  Therefore
     `toc' will always return the elapsed time from the most recent
     call to `tic'.

     If you are more interested in the CPU time that your process used,
     you should use the `cputime' function instead.  The `tic' and
     `toc' functions report the actual wall clock time that elapsed
     between the calls.  This may include time spent processing other
     jobs or doing nothing at all.  For example:

          tic (); sleep (5); toc ()
               => 5
          t = cputime (); sleep (5); cputime () - t
               => 0

     (This example also illustrates that the CPU timer may have a fairly
     coarse resolution.)

 -- Built-in Function:  pause (SECONDS)
     Suspend the execution of the program.  If invoked without any
     arguments, Octave waits until you type a character.  With a
     numeric argument, it pauses for the given number of seconds.  For
     example, the following statement prints a message and then waits 5
     seconds before clearing the screen.

          fprintf (stderr, "wait please...\n");
          pause (5);
          clc;

 -- Built-in Function:  sleep (SECONDS)
     Suspend the execution of the program for the given number of
     seconds.

 -- Built-in Function:  usleep (MICROSECONDS)
     Suspend the execution of the program for the given number of
     microseconds.  On systems where it is not possible to sleep for
     periods of time less than one second, `usleep' will pause the
     execution for `round (MICROSECONDS / 1e6)' seconds.

 -- Function File:  datenum (YEAR, MONTH, DAY)
 -- Function File:  datenum (YEAR, MONTH, DAY, HOUR)
 -- Function File:  datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- Function File:  datenum (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND)
 -- Function File:  datenum ("date")
 -- Function File:  datenum ("date", P)
     Return the specified local time as a day number, with Jan 1, 0000
     being day 1.  By this reckoning, Jan 1, 1970 is day number 719529.
     The fractional portion, P, corresponds to the portion of the
     specified day.

     Notes:

        * Years can be negative and/or fractional.

        * Months below 1 are considered to be January.

        * Days of the month start at 1.

        * Days beyond the end of the month go into subsequent months.

        * Days before the beginning of the month go to the previous
          month.

        * Days can be fractional.

     *Warning:* this function does not attempt to handle Julian
     calendars so dates before Octave 15, 1582 are wrong by as much as
     eleven days.  Also be aware that only Roman Catholic countries
     adopted the calendar in 1582.  It took until 1924 for it to be
     adopted everywhere.  See the Wikipedia entry on the Gregorian
     calendar for more details.

     *Warning:* leap seconds are ignored.  A table of leap seconds is
     available on the Wikipedia entry for leap seconds.

     *See also:* *note date: doc-date, *note clock: doc-clock, *note
     now: doc-now, *note datestr: doc-datestr, *note datevec:
     doc-datevec, *note calendar: doc-calendar, *note weekday:
     doc-weekday.

 -- Function File: STR = datestr (DATE)
 -- Function File: STR = datestr (DATE, F)
 -- Function File: STR = datestr (DATE, F, P)
     Format the given date/time according to the format `f' and return
     the result in STR.  DATE is a serial date number (see `datenum')
     or a date vector (see `datevec').  The value of DATE may also be a
     string or cell array of strings.

     F can be an integer which corresponds to one of the codes in the
     table below, or a date format string.

     P is the year at the start of the century in which two-digit years
     are to be interpreted in.  If not specified, it defaults to the
     current year minus 50.

     For example, the date 730736.65149 (2000-09-07 15:38:09.0934)
     would be formatted as follows:

     Code    Format                         Example
     --------------------------------------------------------------- 
     0       dd-mmm-yyyy HH:MM:SS           07-Sep-2000 15:38:09
     1       dd-mmm-yyyy                    07-Sep-2000
     2       mm/dd/yy                       09/07/00
     3       mmm                            Sep
     4       m                              S
     5       mm                             09
     6       mm/dd                          09/07
     7       dd                             07
     8       ddd                            Thu
     9       d                              T
     10      yyyy                           2000
     11      yy                             00
     12      mmmyy                          Sep00
     13      HH:MM:SS                       15:38:09
     14      HH:MM:SS PM                    03:38:09 PM
     15      HH:MM                          15:38
     16      HH:MM PM                       03:38 PM
     17      QQ-YY                          Q3-00
     18      QQ                             Q3
     19      dd/mm                          13/03
     20      dd/mm/yy                       13/03/95
     21      mmm.dd.yyyy HH:MM:SS           Mar.03.1962 13:53:06
     22      mmm.dd.yyyy                    Mar.03.1962
     23      mm/dd/yyyy                     03/13/1962
     24      dd/mm/yyyy                     12/03/1962
     25      yy/mm/dd                       95/03/13
     26      yyyy/mm/dd                     1995/03/13
     27      QQ-YYYY                        Q4-2132
     28      mmmyyyy                        Mar2047
     29      yyyymmdd                       20470313
     30      yyyymmddTHHMMSS                20470313T132603
     31      yyyy-mm-dd HH:MM:SS            1047-03-13 13:26:03

     If F is a format string, the following symbols are recognized:

     Symbol  Meaning                                         Example
     ---------------------------------------------------------------------- 
     yyyy    Full year                                       2005
     yy      Two-digit year                                  2005
     mmmm    Full month name                                 December
     mmm     Abbreviated month name                          Dec
     mm      Numeric month number (padded with zeros)        01, 08, 12
     m       First letter of month name (capitalized)        D
     dddd    Full weekday name                               Sunday
     ddd     Abbreviated weekday name                        Sun
     dd      Numeric day of month (padded with zeros)        11
     d       First letter of weekday name (capitalized)      S
     HH      Hour of day, padded with zeros if PM is set     09:00
             and not padded with zeros otherwise             9:00 AM
     MM      Minute of hour (padded with zeros)              10:05
     SS      Second of minute (padded with zeros)            10:05:03
     PM      Use 12-hour time format                         11:30 PM

     If F is not specified or is `-1', then use 0, 1 or 16, depending
     on whether the date portion or the time portion of DATE is empty.

     If P is nor specified, it defaults to the current year minus 50.

     If a matrix or cell array of dates is given, a vector of date
     strings is returned.

     *See also:* *note datenum: doc-datenum, *note datevec:
     doc-datevec, *note date: doc-date, *note clock: doc-clock, *note
     now: doc-now, *note datetick: doc-datetick.

 -- Function File: V = datevec (DATE)
 -- Function File: V = datevec (DATE, F)
 -- Function File: V = datevec (DATE, P)
 -- Function File: V = datevec (DATE, F, P)
 -- Function File: [Y, M, D, H, MI, S] = datevec (...)
     Convert a serial date number (see `datenum') or date string (see
     `datestr') into a date vector.

     A date vector is a row vector with six members, representing the
     year, month, day, hour, minute, and seconds respectively.

     F is the format string used to interpret date strings (see
     `datestr').

     P is the year at the start of the century in which two-digit years
     are to be interpreted in.  If not specified, it defaults to the
     current year minus 50.

     *See also:* *note datenum: doc-datenum, *note datestr:
     doc-datestr, *note date: doc-date, *note clock: doc-clock, *note
     now: doc-now.

 -- Function File: D = addtodate (D, Q, F)
     Add Q amount of time (with units F) to the datenum, D.

     F must be one of "year", "month", "day", "hour", "minute", or
     "second".

     *See also:* *note datenum: doc-datenum, *note datevec: doc-datevec.

 -- Function File:  calendar (...)
 -- Function File: C = calendar ()
 -- Function File: C = calendar (D)
 -- Function File: C = calendar (Y, M)
     If called with no arguments, return the current monthly calendar in
     a 6x7 matrix.

     If D is specified, return the calendar for the month containing
     the day D, which must be a serial date number or a date string.

     If Y and M are specified, return the calendar for year Y and month
     M.

     If no output arguments are specified, print the calendar on the
     screen instead of returning a matrix.

     *See also:* *note datenum: doc-datenum.

 -- Function File: [N, S] = weekday (D)
 -- Function File: [N, S] = weekday (D, FORMAT)
     Return the day of week as a number in N and a string in S, for
     example `[1, "Sun"]', `[2, "Mon"]', ..., or `[7, "Sat"]'.

     D is a serial date number or a date string.

     If the string FORMAT is given and is `"long"', S will contain the
     full name of the weekday; otherwise (or if FORMAT is `"short"'), S
     will contain the abbreviated name of the weekday.

     *See also:* *note datenum: doc-datenum, *note datevec:
     doc-datevec, *note eomday: doc-eomday.

 -- Function File: E = eomday (Y, M)
     Return the last day of the month M for the year Y.

     *See also:* *note datenum: doc-datenum, *note datevec:
     doc-datevec, *note weekday: doc-weekday.

 -- Function File:  datetick ()
 -- Function File:  datetick (FORM)
 -- Function File:  datetick (AXIS, FORM)
 -- Function File:  datetick (..., "keeplimits")
 -- Function File:  datetick (..., "keepticks")
 -- Function File:  datetick (...ax, ...)
     Add date formatted tick labels to an axis.  The axis the apply the
     ticks to is determined by AXIS that can take the values "x", "y"
     or "z".  The default value is "x".  The formatting of the labels is
     determined by the variable FORM, that can either be a string in
     the format needed by `dateform', or a positive integer that can be
     accepted by `datestr'.

     *See also:* *note datenum: doc-datenum, *note datestr: doc-datestr.


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

34.2 Filesystem Utilities
=========================

Octave includes many utility functions for copying, moving, renaming,
and deleting files; for creating, reading, and deleting directories;
for retrieving status information on files; and for manipulating file
and path names.

 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2, 'f')
     Move the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.  If the force flag 'f' is given then any existing
     files will be overwritten without prompting.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note rename: doc-rename, *note copyfile: doc-copyfile.

 -- Built-in Function: [ERR, MSG] = rename (OLD, NEW)
     Change the name of file OLD to NEW.

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

     *See also:* *note ls: doc-ls, *note dir: doc-dir.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, 'f')
     Copy the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.  If the force flag 'f' is given then existing
     destination files will be overwritten without prompting.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note movefile: doc-movefile.

 -- Built-in Function: [ERR, MSG] = unlink (FILE)
     Delete the file named FILE.

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

 -- Built-in Function: [ERR, MSG] = link (OLD, NEW)
     Create a new link (also known as a hard link) to an existing file.

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

     *See also:* *note symlink: doc-symlink.

 -- Built-in Function: [ERR, MSG] = symlink (OLD, NEW)
     Create a symbolic link NEW which contains the string OLD.

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

     *See also:* *note link: doc-link, *note readlink: doc-readlink.

 -- Built-in Function: [RESULT, ERR, MSG] = readlink (SYMLINK)
     Read the value of the symbolic link SYMLINK.

     If successful, RESULT contains the contents of the symbolic link
     SYMLINK, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     *See also:* *note link: doc-link, *note symlink: doc-symlink.

 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (PARENT, DIR)
     Create a directory named DIR in the directory PARENT.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note rmdir: doc-rmdir.

 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR, "s")
     Remove the directory named DIR.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     If the optional second parameter is supplied with value `"s"',
     recursively remove all subdirectories as well.

     *See also:* *note mkdir: doc-mkdir, *note confirm_recursive_rmdir:
     doc-confirm_recursive_rmdir.

 -- Built-in Function: VAL = confirm_recursive_rmdir ()
 -- Built-in Function: OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will ask for confirmation before recursively removing a directory
     tree.

 -- Built-in Function: [ERR, MSG] = mkfifo (NAME, MODE)
     Create a FIFO special file named NAME with file mode MODE

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

 -- Built-in Function:  umask (MASK)
     Set the permission mask for file creation.  The parameter MASK is
     an integer, interpreted as an octal number.  If successful,
     returns the previous value of the mask (as an integer to be
     interpreted as an octal number); otherwise an error message is
     printed.

 -- Built-in Function: [INFO, ERR, MSG] = stat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = stat (FID)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FID)
     Return a structure INFO containing the following information about
     FILE or file identifier FID.

    `dev'
          ID of device containing a directory entry for this file.

    `ino'
          File number of the file.

    `mode'
          File mode, as an integer.  Use the functions `S_ISREG',
          `S_ISDIR', `S_ISCHR', `S_ISBLK', `S_ISFIFO', `S_ISLNK', or
          `S_ISSOCK' to extract information from this value.

    `modestr'
          File mode, as a string of ten letters or dashes as would be
          returned by `ls -l'.

    `nlink'
          Number of links.

    `uid'
          User ID of file's owner.

    `gid'
          Group ID of file's group.

    `rdev'
          ID of device for block or character special files.

    `size'
          Size in bytes.

    `atime'
          Time of last access in the same form as time values returned
          from `time'.  *Note Timing Utilities::.

    `mtime'
          Time of last modification in the same form as time values
          returned from `time'.  *Note Timing Utilities::.

    `ctime'
          Time of last file status change in the same form as time
          values returned from `time'.  *Note Timing Utilities::.

    `blksize'
          Size of blocks in the file.

    `blocks'
          Number of blocks allocated for file.

     If the call is successful ERR is 0 and MSG is an empty string.  If
     the file does not exist, or some other error occurs, S is an empty
     matrix, ERR is -1, and MSG contains the corresponding system error
     message.

     If FILE is a symbolic link, `stat' will return information about
     the actual file that is referenced by the link.  Use `lstat' if
     you want information about the symbolic link itself.

     For example:

          [s, err, msg] = stat ("/vmlinuz")
                => s =
                  {
                    atime = 855399756
                    rdev = 0
                    ctime = 847219094
                    uid = 0
                    size = 389218
                    blksize = 4096
                    mtime = 847219094
                    gid = 6
                    nlink = 1
                    blocks = 768
                    mode = -rw-r--r--
                    modestr = -rw-r--r--
                    ino = 9316
                    dev = 2049
                  }
               => err = 0
               => msg =

 -- Built-in Function:  S_ISBLK (MODE)
     Return true if MODE corresponds to a block device.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISCHR (MODE)
     Return true if MODE corresponds to a character device.  The value
     of MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISDIR (MODE)
     Return true if MODE corresponds to a directory.  The value of MODE
     is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISFIFO (MODE)
     Return true if MODE corresponds to a fifo.  The value of MODE is
     assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISLNK (MODE)
     Return true if MODE corresponds to a symbolic link.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISREG (MODE)
     Return true if MODE corresponds to a regular file.  The value of
     MODE is assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Built-in Function:  S_ISSOCK (MODE)
     Return true if MODE corresponds to a socket.  The value of MODE is
     assumed to be returned from a call to `stat'.

     *See also:* *note stat: doc-stat, *note lstat: doc-lstat.

 -- Function File: [STATUS, MSG, MSGID] = fileattrib (FILE)
     Return information about FILE.

     If successful, STATUS is 1, with RESULT containing a structure
     with the following fields:

    `Name'
          Full name of FILE.

    `archive'
          True if FILE is an archive (Windows).

    `system'
          True if FILE is a system file (Windows).

    `hidden'
          True if FILE is a hidden file (Windows).

    `directory'
          True if FILE is a directory.

    `UserRead'
    `GroupRead'
    `OtherRead'
          True if the user (group; other users) has read permission for
          FILE.

    `UserWrite'
    `GroupWrite'
    `OtherWrite'
          True if the user (group; other users) has write permission for
          FILE.

    `UserExecute'
    `GroupExecute'
    `OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.
     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

     With no input arguments, return information about the current
     directory.

     If FILE contains globbing characters, return information about all
     the matching files.

     *See also:* *note glob: doc-glob.

 -- Function File:  isdir (F)
     Return true if F is a directory.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note is_rooted_relative_filename: doc-is_rooted_relative_filename.

 -- Built-in Function: [FILES, ERR, MSG] = readdir (DIR)
     Return names of the files in the directory DIR as a cell array of
     strings.  If an error occurs, return an empty cell array in FILES.

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

     *See also:* *note ls: doc-ls, *note dir: doc-dir, *note glob:
     doc-glob.

 -- Built-in Function:  glob (PATTERN)
     Given an array of pattern strings (as a char array or a cell
     array) in PATTERN, return a cell array of file names that match
     any of them, or an empty cell array if no patterns match.  The
     pattern strings are interpreted as filename globbing patterns (as
     they are used by Unix shells).  Within a pattern
    `*'
          matches any string, including the null string,

    `?'
          matches any single character, and

    `[...]'
          matches any of the enclosed characters.

     Tilde expansion is performed on each of the patterns before
     looking for matching file names.  For example:

          ls
               =>
                  file1  file2  file3  myfile1 myfile1b
          glob ("*file1")
               =>
                  {
                    [1,1] = file1
                    [2,1] = myfile1
                  }
          glob ("myfile?")
               =>
                  {
                    [1,1] = myfile1
                  }
          glob ("file[12]")
               =>
                  {
                    [1,1] = file1
                    [2,1] = file2
                  }

     *See also:* *note ls: doc-ls, *note dir: doc-dir, *note readdir:
     doc-readdir.

 -- Built-in Function:  fnmatch (PATTERN, STRING)
     Return 1 or zero for each element of STRING that matches any of
     the elements of the string array PATTERN, using the rules of
     filename pattern matching.  For example:

          fnmatch ("a*b", {"ab"; "axyzb"; "xyzab"})
               => [ 1; 1; 0 ]

 -- Built-in Function:  file_in_path (PATH, FILE)
 -- Built-in Function:  file_in_path (PATH, FILE, "all")
     Return the absolute name of FILE if it can be found in PATH.  The
     value of PATH should be a colon-separated list of directories in
     the format described for `path'.  If no file is found, return an
     empty character string.  For example:

          file_in_path (EXEC_PATH, "sh")
               => "/bin/sh"

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

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

     *See also:* *note file_in_loadpath: doc-file_in_loadpath.

 -- Built-in Function:  filesep ()
 -- Built-in Function:  filesep ('all')
     Return the system-dependent character used to separate directory
     names.

     If 'all' is given, the function returns all valid file separators
     in the form of a string.  The list of file separators is
     system-dependent.  It is `/' (forward slash) under UNIX or
     Mac OS X, `/' and `\' (forward and backward slashes) under Windows.

     *See also:* *note pathsep: doc-pathsep.

 -- Built-in Function: VAL = filemarker ()
 -- Built-in Function:  filemarker (NEW_VAL)
     Query or set the character used to separate filename from the the
     subfunction names contained within the file.  This can be used in
     a generic manner to interact with subfunctions.  For example,

          help (["myfunc", filemarker, "mysubfunc"])

     returns the help string associated with the sub-function
     `mysubfunc' of the function `myfunc'.  Another use of `filemarker'
     is when debugging it allows easier placement of breakpoints within
     sub-functions.  For example,

          dbstop (["myfunc", filemarker, "mysubfunc"])

     will set a breakpoint at the first line of the subfunction
     `mysubfunc'.

 -- Function File: [DIR, NAME, EXT, VER] = fileparts (FILENAME)
     Return the directory, name, extension, and version components of
     FILENAME.

     *See also:* *note fullfile: doc-fullfile.

 -- Function File: FILENAME = fullfile (DIR1, DIR2, ..., FILE)
     Return a complete filename constructed from the given components.

     *See also:* *note fileparts: doc-fileparts.

 -- Built-in Function:  tilde_expand (STRING)
     Perform tilde expansion on STRING.  If STRING begins with a tilde
     character, (`~'), all of the characters preceding the first slash
     (or all characters, if there is no slash) are treated as a
     possible user name, and the tilde and the following characters up
     to the slash are replaced by the home directory of the named user.
     If the tilde is followed immediately by a slash, the tilde is
     replaced by the home directory of the user running Octave.  For
     example:

          tilde_expand ("~joeuser/bin")
               => "/home/joeuser/bin"
          tilde_expand ("~/bin")
               => "/home/jwe/bin"

 -- Built-in Function: [CNAME, STATUS, MSG] canonicalize_file_name
          (NAME)
     Return the canonical name of file NAME.

 -- Built-in Function:  make_absolute_filename (FILE)
     Return the full name of FILE, relative to the current directory.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note is_rooted_relative_filename:
     doc-is_rooted_relative_filename, *note isdir: doc-isdir.

 -- Built-in Function:  is_absolute_filename (FILE)
     Return true if FILE is an absolute filename.

     *See also:* *note is_rooted_relative_filename:
     doc-is_rooted_relative_filename, *note make_absolute_filename:
     doc-make_absolute_filename, *note isdir: doc-isdir.

 -- Built-in Function:  is_rooted_relative_filename (FILE)
     Return true if FILE is a rooted-relative filename.

     *See also:* *note is_absolute_filename: doc-is_absolute_filename,
     *note make_absolute_filename: doc-make_absolute_filename, *note
     isdir: doc-isdir.

 -- Built-in Function:  P_tmpdir ()
     Return the default name of the directory for temporary files on
     this system.  The name of this directory is system dependent.

 -- Function File: DIR = tempdir ()
     Return the name of the system's directory for temporary files.

 -- Function File:  tempname ()
 -- Function File:  tempname (DIR)
 -- Function File:  tempname (DIR, PREFIX)
     This function is an alias for `tmpnam'.

     *See also:* *note tmpnam: doc-tmpnam.


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

34.3 File Archiving Utilities
=============================

 -- Function File:  bunzip2 (BZFILE)
 -- Function File:  bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note bzip2: doc-bzip2, *note unpack: doc-unpack,
     *note gunzip: doc-gunzip, *note unzip: doc-unzip, *note untar:
     doc-untar.

 -- Function File: ENTRIES = gzip (FILES)
 -- Function File: ENTRIES = gzip (FILES, OUTDIR)
     Compress the list of files and/or directories specified in FILES.
     Each file is compressed separately and a new file with a '.gz'
     extension is created.  The original files are not modified.
     Existing compressed files are silently overwritten.  If OUTDIR is
     defined the compressed files are placed in this directory.

     *See also:* *note gunzip: doc-gunzip, *note bzip2: doc-bzip2,
     *note zip: doc-zip, *note tar: doc-tar.

 -- Function File:  gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.  If GZFILE is
     a directory, all gzfiles in the directory will be recursively
     gunzipped.

     *See also:* *note gzip: doc-gzip, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note unzip: doc-unzip, *note untar:
     doc-untar.

 -- Function File: ENTRIES = tar (TARFILE, FILES)
 -- Function File: ENTRIES = tar (TARFILE, FILES, ROOT)
     Pack FILES FILES into the TAR archive TARFILE.  The list of files
     must be a string or a cell array of strings.

     The optional argument ROOT changes the relative path of FILES from
     the current directory.

     If an output argument is requested the entries in the archive are
     returned in a cell array.

     *See also:* *note untar: doc-untar, *note bzip2: doc-bzip2, *note
     gzip: doc-gzip, *note zip: doc-zip.

 -- Function File:  untar (TARFILE)
 -- Function File:  untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note tar: doc-tar, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note gunzip: doc-gunzip, *note unzip:
     doc-unzip.

 -- Function File: ENTRIES = zip (ZIPFILE, FILES)
 -- Function File: ENTRIES = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and/or directories specified in FILES
     into the archive ZIPFILE in the same directory.  If ROOTDIR is
     defined the FILES are located relative to ROOTDIR rather than the
     current directory.

     *See also:* *note unzip: doc-unzip, *note bzip2: doc-bzip2, *note
     gzip: doc-gzip, *note tar: doc-tar.

 -- Function File:  unzip (ZIPFILE)
 -- Function File:  unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note zip: doc-zip, *note unpack: doc-unpack, *note
     bunzip2: doc-bunzip2, *note gunzip: doc-gunzip, *note untar:
     doc-untar.

 -- Function File: FILES = unpack (FILE)
 -- Function File: FILES = unpack (FILE, DIR)
 -- Function File: FILES = unpack (FILE, DIR, FILETYPE)
     Unpack the archive FILE based on its extension to the directory
     DIR.  If FILE is a list of strings, then each file is unpacked
     individually.  If DIR is not specified, it defaults to the current
     directory.  If a directory is in the file list, then the FILETYPE
     must also be specified.

     The optional return value is a list of FILES unpacked.

     *See also:* *note bzip2: doc-bzip2, *note gzip: doc-gzip, *note
     zip: doc-zip, *note tar: doc-tar.

 -- Function File: ENTRIES = bzip2 (FILES)
 -- Function File: ENTRIES = bzip2 (FILES, OUTDIR)
     Compress the list of files specified in FILES.  Each file is
     compressed separately and a new file with a '.bz2' extension is
     created.  The original files are not modified.  Existing
     compressed files are silently overwritten.  If OUTDIR is defined
     the compressed files are placed in this directory.

     *See also:* *note bunzip2: doc-bunzip2, *note gzip: doc-gzip,
     *note zip: doc-zip, *note tar: doc-tar.


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

34.4 Networking Utilities
=========================

* Menu:

* FTP Objects::
* URL Manipulation::

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


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

34.4.1 FTP Objects
------------------

 -- Function File: F = ftp (HOST)
 -- Function File: F = ftp (HOST, USERNAME, PASSWORD)
     Connect to the FTP server HOST with USERNAME and PASSWORD.  If
     USERNAME and PASSWORD are not specified, user "anonymous" with no
     password is used.  The returned FTP object F represents the
     established FTP connection.

 -- Function File:  mget (F, FILE)
 -- Function File:  mget (F, DIR)
 -- Function File:  mget (..., TARGET)
     Download a remote file FILE or directory DIR to the local
     directory on the FTP connection F.  F is an FTP object returned by
     the `ftp' function.

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

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

 -- Function File:  mput (F, FILE)
     Upload the local file FILE into the current remote directory on
     the FTP connection F.  F is an FTP object returned by the ftp
     function.

     The argument FILE is passed by the "glob" function and any files
     that match the wildcards in FILE will be uploaded.

 -- Function File:  ascii (F)
     Put the FTP connection F into ascii mode.  F is an FTP object
     returned by the `ftp' function.

 -- Function File:  binary (F)
     Put the FTP connection F into binary mode.  F is an FTP object
     returned by the `ftp' function.


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

34.4.2 URL Manipulation
-----------------------

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

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

     The variable SUCCESS is 1 if the download was successful,
     otherwise it is 0 in which case MESSAGE contains an error message.
     If no output argument is specified and an error occurs, then the
     error is signaled through Octave's error handling mechanism.

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

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

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

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

     *See also:* *note urlwrite: doc-urlwrite.

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

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

     The full path of the downloaded file is returned in F.  The
     variable SUCCESS is 1 if the download was successful, otherwise it
     is 0 in which case MESSAGE contains an error message.  If no
     output argument is specified and an error occurs, then the error
     is signaled through Octave's error handling mechanism.

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

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

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

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

     *See also:* *note urlread: doc-urlread.


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

34.5 Controlling Subprocesses
=============================

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

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

 -- Built-in Function: [STATUS, OUTPUT] system (STRING, RETURN_OUTPUT,
          TYPE)
 -- Built-in Function: [STATUS, OUTPUT] shell_cmd (STRING,
          RETURN_OUTPUT, TYPE)
     Execute a shell command specified by STRING.  If the optional
     argument TYPE is `"async"', the process is started in the
     background and the process id of the child process is returned
     immediately.  Otherwise, the process is started, and Octave waits
     until it exits.  If the TYPE argument is omitted, a value of
     `"sync"' is assumed.

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

          disp (system (cmd, 1));

     or

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

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

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

     will set the variable `output' to the string `foo', and the
     variable `status' to the integer `2'.

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

 -- Function File: [STATUS, TEXT] = unix (COMMAND)
 -- Function File: [STATUS, TEXT] = unix (COMMAND, "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* *note isunix: doc-isunix, *note ispc: doc-ispc, *note
     system: doc-system.

 -- Function File: [STATUS, TEXT] = dos (COMMAND)
 -- Function File: [STATUS, TEXT] = dos (COMMAND, "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* *note unix: doc-unix, *note isunix: doc-isunix, *note
     ispc: doc-ispc, *note system: doc-system.

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

     *See also:* *note system: doc-system.

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.  The name of the command to run
     is given by COMMAND.  The file identifier corresponding to the
     input or output stream of the process is returned in FID.  The
     argument MODE may be

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

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

     For example:

          fid = popen ("ls -ltr / | tail -3", "r");
          while (ischar (s = fgets (fid)))
            fputs (stdout, s);
          endwhile
               -| drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
               -| drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
               -| drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

 -- Built-in Function:  pclose (FID)
     Close a file identifier that was opened by `popen'.  You may also
     use `fclose' for the same purpose.

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.  The name of the
     process is given by COMMAND, and ARGS is an array of strings
     containing options for the command.  The file identifiers for the
     input and output streams of the subprocess are returned in IN and
     OUT.  If execution of the command is successful, PID contains the
     process ID of the subprocess.  Otherwise, PID is -1.

     For example:

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

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

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
     Query or set the internal variable that specifies a colon separated
     list of directories to append to the shell PATH when executing
     external programs.  The initial value of is taken from the
     environment variable `OCTAVE_EXEC_PATH', but that value can be
     overridden by the command line argument `--exec-path PATH'.

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

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

     Fork can return one of the following values:

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

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

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

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.  Calling `exec' without
     first calling `fork' will terminate your current Octave process and
     replace it with the program named by FILE.  For example,

          exec ("ls" "-l")

     will run `ls' and return you to your shell prompt.

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

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

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

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

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

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

    -1
          Wait for any child process.

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

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

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

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

    `WNOHANG'
          Do not hang if status is not immediately available.

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

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

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

     *See also:* *note WCONTINUE: doc-WCONTINUE, *note WCOREDUMP:
     doc-WCOREDUMP, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFCONTINUED: doc-WIFCONTINUED, *note WIFSIGNALED:
     doc-WIFSIGNALED, *note WIFSTOPPED: doc-WIFSTOPPED, *note WNOHANG:
     doc-WNOHANG, *note WSTOPSIG: doc-WSTOPSIG, *note WTERMSIG:
     doc-WTERMSIG, *note WUNTRACED: doc-WUNTRACED.

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

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WUNTRACED: doc-WUNTRACED.

 -- Built-in Function:  WCOREDUMP (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     produced a core dump.  This function should only be employed if
     `WIFSIGNALED' returned true.  The macro used to implement this
     function is not specified in POSIX.1-2001 and is not available on
     some Unix implementations (e.g., AIX, SunOS).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WEXITSTATUS (STATUS)
     Given STATUS from a call to `waitpid', return the exit status of
     the child.  This function should only be employed if `WIFEXITED'
     returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

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

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WSTOPSIG: doc-WSTOPSIG.

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

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

 -- Built-in Function:  WIFSTOPPED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was stopped by delivery of a signal; this is only possible
     if the call was done using `WUNTRACED' or when the child is being
     traced (see ptrace(2)).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

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

     *See also:* *note waitpid: doc-waitpid, *note WEXITSTATUS:
     doc-WEXITSTATUS, *note WIFSIGNALED: doc-WIFSIGNALED, *note
     WTERMSIG: doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

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

     *See also:* *note waitpid: doc-waitpid, *note WUNTRACED:
     doc-WUNTRACED, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function:  WSTOPSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal which caused the child to stop.  This function should only
     be employed if `WIFSTOPPED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WTERMSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal that caused the child process to terminate.  This function
     should only be employed if `WIFSIGNALED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WCOREDUMP: doc-WCOREDUMP,
     *note WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG,
     *note WIFCONTINUED: doc-WIFCONTINUED.

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

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function: [ERR, MSG] = fcntl (FID, REQUEST, ARG)
     Change the properties of the open file FID.  The following values
     may be passed as REQUEST:

    `F_DUPFD'
          Return a duplicate file descriptor.

    `F_GETFD'
          Return the file descriptor flags for FID.

    `F_SETFD'
          Set the file descriptor flags for FID.

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

         `O_RDONLY'
               Open for reading only.

         `O_WRONLY'
               Open for writing only.

         `O_RDWR'
               Open for reading and writing.

         `O_APPEND'
               Append on each write.

         `O_CREAT'
               Create the file if it does not exist.

         `O_NONBLOCK'
               Non-blocking mode.

         `O_SYNC'
               Wait for writes to complete.

         `O_ASYNC'
               Asynchronous I/O.

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

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

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

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

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

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

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

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

     Return 0 if successful, otherwise return -1.

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


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

34.6 Process, Group, and User IDs
=================================

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

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

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

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

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

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

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


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

34.7 Environment Variables
==========================

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

          getenv ("PATH")

     returns a string containing the value of your path.

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


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

34.8 Current Working Directory
==============================

 -- Command:  cd dir
 -- Command:  chdir dir
     Change the current working directory to DIR.  If DIR is omitted,
     the current directory is changed to the user's home directory.
     For example,

          cd ~/octave

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

     *See also:* *note mkdir: doc-mkdir, *note rmdir: doc-rmdir, *note
     dir: doc-dir.

 -- Command:  ls options
     List directory contents.  For example:

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

     The `dir' and `ls' commands are implemented by calling your
     system's directory listing command, so the available options may
     vary from system to system.

     *See also:* *note dir: doc-dir, *note stat: doc-stat, *note
     readdir: doc-readdir, *note glob: doc-glob, *note filesep:
     doc-filesep, *note ls_command: doc-ls_command.

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

     *See also:* *note ls: doc-ls.

 -- Function File:  dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.  If a return value
     is requested, return a structure array with the fields

          name
          bytes
          date
          isdir
          statinfo

     in which `statinfo' is the structure returned from `stat'.

     If DIRECTORY is not a directory, return information about the
     named FILENAME.  DIRECTORY may be a list of directories specified
     either by name or with wildcard characters (like * and ?)  which
     will be expanded with glob.

     Note that for symbolic links, `dir' returns information about the
     file that a symbolic link points to instead of the link itself.
     However, if the link points to a nonexistent file, `dir' returns
     information about the link.

     *See also:* *note ls: doc-ls, *note stat: doc-stat, *note lstat:
     doc-lstat, *note readdir: doc-readdir, *note glob: doc-glob, *note
     filesep: doc-filesep.

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

     *See also:* *note dir: doc-dir, *note ls: doc-ls.


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

34.9 Password Database Functions
================================

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

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`uid'
     The numeric user id.

`gid'
     The numeric group id.

`gecos'
     The GECOS field.

`dir'
     The home directory.

`shell'
     The initial shell.

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

 -- Loadable Function: PW_STRUCT = getpwent ()
     Return a structure containing an entry from the password database,
     opening it if necessary.  Once the end of the data has been
     reached, `getpwent' returns 0.

 -- Loadable Function: PW_STRUCT = getpwuid (UID).
     Return a structure containing the first entry from the password
     database with the user ID UID.  If the user ID does not exist in
     the database, `getpwuid' returns 0.

 -- Loadable Function: PW_STRUCT = getpwnam (NAME)
     Return a structure containing the first entry from the password
     database with the user name NAME.  If the user name does not exist
     in the database, `getpwname' returns 0.

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

 -- Loadable Function:  endpwent ()
     Close the password database.


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

34.10 Group Database Functions
==============================

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

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`gid'
     The numeric group id.

`mem'
     The members of the group.

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

 -- Loadable Function: GRP_STRUCT = getgrent ()
     Return an entry from the group database, opening it if necessary.
     Once the end of data has been reached, `getgrent' returns 0.

 -- Loadable Function: GRP_STRUCT = getgrgid (GID).
     Return the first entry from the group database with the group ID
     GID.  If the group ID does not exist in the database, `getgrgid'
     returns 0.

 -- Loadable Function: GRP_STRUCT = getgrnam (NAME)
     Return the first entry from the group database with the group name
     NAME.  If the group name does not exist in the database,
     `getgrnam' returns 0.

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

 -- Loadable Function:  endgrent ()
     Close the group database.


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

34.11 System Information
========================

 -- Function File: [C, MAXSIZE, ENDIAN] = computer ()
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the kind of computer Octave is running on.  If invoked with an
     output argument, the value is returned instead of printed.  For
     example:

          computer ()
               -| i586-pc-linux-gnu

          x = computer ()
               => x = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.

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

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

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

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

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

     If called with the optional argument QUERY, modify how processors
     are counted as follows:
    `all'
          total number of processors.

    `current'
          processors available to the current process.

    `overridable'
          likewise, but overridable through the `OMP_NUM_THREADS'
          environment variable.

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

     *See also:* *note isunix: doc-isunix, *note ismac: doc-ismac.

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

     *See also:* *note ismac: doc-ismac, *note ispc: doc-ispc.

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

     *See also:* *note isunix: doc-isunix, *note ispc: doc-ispc.

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

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

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

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

     This is an alias for the function `OCTAVE_HOME' provided for
     compatibility.

     *See also:* *note OCTAVE_HOME: doc-OCTAVE_HOME.

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

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

     This is an alias for the function `OCTAVE_VERSION' provided for
     compatibility

     *See also:* *note OCTAVE_VERSION: doc-OCTAVE_VERSION..

 -- Function File:  ver ()
     Display a header containing the current Octave version number,
     license string and operating system, followed by the installed
     package names, versions, and installation directories.

 -- Function File: v = ver ()
     Return a vector of structures, respecting Octave and each
     installed package.  The structure includes the following fields.

    `Name'
          Package name.

    `Version'
          Version of the package.

    `Revision'
          Revision of the package.

    `Date'
          Date respecting the version/revision.

 -- Function File: v = ver ("Octave")
     Return version information for Octave only.

 -- Function File: v = ver (PACKAGE)
     Return version information for PACKAGE.

     *See also:* *note version: doc-version, *note octave_config_info:
     doc-octave_config_info.

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

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

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

     The operator can be any logical operator from the set

        * "==" equal

        * "<" less than

        * "<=" less than or equal to

        * ">" greater than

        * ">=" greater than or equal to

        * "!=" not equal

        * "~=" not equal

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

 -- Function File:  license
     Display the license of Octave.

 -- Function File:  license ("inuse")
     Display a list of packages currently being used.

 -- Function File: RETVAL = license ("inuse")
     Return a structure containing the fields `feature' and `user'.

 -- Function File: RETVAL = license ("test", FEATURE)
     Return 1 if a license exists for the product identified by the
     string FEATURE and 0 otherwise.  The argument FEATURE is case
     insensitive and only the first 27 characters are checked.

 -- Function File:  license ("test", FEATURE, TOGGLE)
     Enable or disable license testing for FEATURE, depending on
     TOGGLE, which may be one of:

    "enable"
          Future tests for the specified license of FEATURE are
          conducted as usual.

    "disable"
          Future tests for the specified license of FEATURE return 0.

 -- Function File: RETVAL = license ("checkout", FEATURE)
     Check out a license for FEATURE, returning 1 on success and 0 on
     failure.

     This function is provided for compatibility with MATLAB.

     *See also:* *note ver: doc-ver, *note version: doc-version.

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

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


 -- Loadable Function:  getrusage ()
     Return a structure containing a number of statistics about the
     current Octave process.  Not all fields are available on all
     systems.  If it is not possible to get CPU time statistics, the
     CPU time slots are set to zero.  Other missing data are replaced
     by NaN.  The list of possible fields is:

    `idrss'
          Unshared data size.

    `inblock'
          Number of block input operations.

    `isrss'
          Unshared stack size.

    `ixrss'
          Shared memory size.

    `majflt'
          Number of major page faults.

    `maxrss'
          Maximum data size.

    `minflt'
          Number of minor page faults.

    `msgrcv'
          Number of messages received.

    `msgsnd'
          Number of messages sent.

    `nivcsw'
          Number of involuntary context switches.

    `nsignals'
          Number of signals received.

    `nswap'
          Number of swaps.

    `nvcsw'
          Number of voluntary context switches.

    `oublock'
          Number of block output operations.

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

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


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

34.12 Hashing Functions
=======================

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

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

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

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

 -- Loadable Function:  md5sum (FILE)
 -- Loadable Function:  md5sum (STR, OPT)
     Calculate the MD5 sum of the file FILE.  If the second parameter
     OPT exists and is true, then calculate the MD5 sum of the string
     STR.


File: octave.info,  Node: Packages,  Next: Dynamically Linked Functions,  Prev: System Utilities,  Up: Top

35 Packages
***********

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

* Menu:

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


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

35.1 Installing and Removing Packages
=====================================

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

     pkg install image-1.0.0.tar.gz

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

   To see which packages are installed type

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

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

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

     pkg uninstall image

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

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

     pkg install -nodeps my_package_with_dependencies.tar.gz

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

 -- Command:  pkg COMMAND PKG_NAME
 -- Command:  pkg COMMAND OPTION PKG_NAME
     This command interacts with the package manager.  Different
     actions will be taken depending on the value of COMMAND.

    `install'
          Install named packages.  For example,

               pkg install image-1.0.0.tar.gz

          installs the package found in the file `image-1.0.0.tar.gz'.

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

         `-nodeps'
               The package manager will disable the dependency
               checking.  That way it is possible to install a package
               even if it depends on another package that's not
               installed on the system.  *Use this option with care.*

         `-noauto'
               The package manager will not automatically load the
               installed package when starting Octave, even if the
               package requests that it is.

         `-auto'
               The package manager will automatically load the
               installed package when starting Octave, even if the
               package requests that it isn't.

         `-local'
               A local installation is forced, even if the user has
               system privileges.

         `-global'
               A global installation is forced, even if the user
               doesn't normally have system privileges

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

         `-verbose'
               The package manager will print the output of all of the
               commands that are performed.

    `uninstall'
          Uninstall named packages.  For example,

               pkg uninstall image

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

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

               pkg load image

          adds the `image' package to the path.  It is possible to load
          all installed packages at once with the command

               pkg load all

    `unload'
          Removes named packages from the path.  After unloading a
          package it is no longer possible to use the functions
          provided by the package.  This command behaves like the
          `load' command.

    `list'
          Show a list of the currently installed packages.  By
          requesting one or two output argument it is possible to get a
          list of the currently installed packages.  For example,

               installed_packages = pkg list;

          returns a cell array containing a structure for each
          installed package.  The command

               [USER_PACKAGES, SYSTEM_PACKAGES] = pkg list

          splits the list of installed packages into those who are
          installed by the current user, and those installed by the
          system administrator.

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

    `describe'
          Show a short description of the named installed packages,
          with the option '-verbose' also list functions provided by
          the package, e.g.:

                pkg describe -verbose all

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

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

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

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

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

    `prefix'
          Set the installation prefix directory.  For example,

               pkg prefix ~/my_octave_packages

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

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

               p = pkg prefix

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

               pkg prefix ~/my_octave_packages ~/my_arch_dep_pkgs

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

               pkg local_list ~/.octave_packages

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

               pkg local_list

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

               pkg global_list /usr/share/octave/octave_packages

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

               pkg global_list

    `rebuild'
          Rebuilds the package database from the installed directories.
          This can be used in cases where for some reason the package
          database is corrupted.  It can also take the `-auto' and
          `-noauto' options to allow the autoloading state of a package
          to be changed.  For example,

               pkg rebuild -noauto image

          will remove the autoloading status of the image package.

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

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

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


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

35.2 Using Packages
===================

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

     pkg unload package_name

where `package_name' is the name of the package to be removed from the
path.

   In much the same way a package can be added to the Octave path by
typing

     pkg load package_name


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

35.3 Administrating Packages
============================

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

     pkg prefix new_installation_directory

The current installation directory can be retrieved by typing

     current_installation_directory = pkg prefix

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

     pkg local_list /path/to/new_file

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


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

35.4 Creating Packages
======================

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


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

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

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

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

          ln -s foo.oct bar.oct

     with an autoload directive like

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

     *Note PKG_ADD and PKG_DEL Directives::, for details on `PKG_ADD'
     directives.

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

`package/pre_install.m'
     This is an optional script that is run prior to the installation
     of a package.

`package/post_install.m'
     This is an optional script that is run after the installation of a
     package.

`package/on_uninstall.m'
     This is an optional script that is run prior to the removal of a
     package.

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


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

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

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

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

* Menu:

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


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

35.4.1 The DESCRIPTION File
---------------------------

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


   * Lines starting with `#' are comments.

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

   * Everything else is of the form `NameOfOption: ValueOfOption'.

The following is a simple example of a `DESCRIPTION' file

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

   The package manager currently recognizes the following keywords


`Name'
     Name of the package.

`Version'
     Version of the package.

`Date'
     Date of last update.

`Author'
     Original author of the package.

`Maintainer'
     Maintainer of the package.

`Title'
     A one line description of the package.

`Description'
     A one paragraph description of the package.

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

`Problems'
     Optional list of known problems.

`Url'
     Optional list of homepages related to the package.

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

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

          Depends: package (>= 1.0.0)

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

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

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

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


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

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

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


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

35.4.2 The INDEX File
---------------------

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


   * Lines beginning with `#' are comments.

   * The first non-comment line should look like this

          toolbox >> Toolbox name

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

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

The format can be summarized with the following example.

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

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

     fn = workaround description

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

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

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

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

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

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

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

     $id = expansion

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

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

id is any string of letters, numbers and `_'.


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

35.4.3 PKG_ADD and PKG_DEL Directives
-------------------------------------

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

   In `m'-files a `PKG_ADD' directive looks like this

     ## PKG_ADD: some_octave_command

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

     // PKG_ADD: some_octave_command

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


File: octave.info,  Node: Dynamically Linked Functions,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A Dynamically Linked Functions
***************************************

Octave has the possibility of including compiled code as dynamically
linked extensions and then using these extensions as if they were part
of Octave itself.  Octave can call C++ code through its native oct-file
interface or C code through its mex interface.  It can also indirectly
call functions written in any other language through a simple wrapper.
The reasons to write code in a compiled language might be either to
link to an existing piece of code and allow it to be used within
Octave, or to allow improved performance for key pieces of code.

   Before going further, you should first determine if you really need
to use dynamically linked functions at all.  Before proceeding with
writing any dynamically linked function to improve performance you
should address ask yourself

   * Can I get the same functionality using the Octave scripting
     language only?

   * Is it thoroughly optimized Octave code?  Vectorization of Octave
     code, doesn't just make it concise, it generally significantly
     improves its performance.  Above all, 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 it make as much use as possible of existing built-in library
     routines?  These are highly optimized and many do not carry the
     overhead of being interpreted.

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

   Also, as oct- and mex-files are dynamically linked to Octave, they
introduce the possibility of Octave crashing due to errors in the user
code.  For example a segmentation violation in the user's code will
cause Octave to abort.

* Menu:

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


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: Dynamically Linked Functions

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

* Menu:

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


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

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

The basic command to build oct-files is `mkoctfile' and it can be call
from within octave or from the command line.

 -- Command:  mkoctfile [-options] file ...
     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.

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

    `-I DIR'
          Add the include directory DIR to compile commands.

    `-D DEF'
          Add the definition DEF to the compiler call.

    `-l LIB'
          Add the library LIB to the link command.

    `-L DIR'
          Add the library directory DIR to the link command.

    `-M'
    `--depend'
          Generate dependency files (.d) for C and C++ source files.

    `-R DIR'
          Add the run-time path to the link command.

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

    `-W...'
          Pass flags though the compiler like "-Wa,OPTION".

    `-c'
          Compile but do not link.

    `-g'
          Enable debugging options for compilers.

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

    `-p VAR'
    `--print VAR'
          Print the configuration variable VAR.  Recognized variables
          are:

                  ALL_CFLAGS                FFTW_LIBS
                  ALL_CXXFLAGS              FLIBS
                  ALL_FFLAGS                FPICFLAG
                  ALL_LDFLAGS               INCFLAGS
                  BLAS_LIBS                 LDFLAGS
                  CC                        LD_CXX
                  CFLAGS                    LD_STATIC_FLAG
                  CPICFLAG                  LFLAGS
                  CPPFLAGS                  LIBCRUFT
                  CXX                       LIBOCTAVE
                  CXXFLAGS                  LIBOCTINTERP
                  CXXPICFLAG                LIBREADLINE
                  DEPEND_EXTRA_SED_PATTERN  LIBS
                  DEPEND_FLAGS              OCTAVE_LIBS
                  DL_LD                     RDYNAMIC_FLAG
                  DL_LDFLAGS                RLD_FLAG
                  F2C                       SED
                  F2CFLAGS                  XTRA_CFLAGS
                  F77                       XTRA_CXXFLAGS
                  FFLAGS

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

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

    `-s'
    `--strip'
          Strip the output file.

    `-v'
    `--verbose'
          Echo commands as they are executed.

    `file'
          The file to compile or link.  Recognized file types are

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


   Consider the short C++ example:

     #include <octave/oct.h>

     DEFUN_DLD (helloworld, args, nargout,
       "Hello World Help String")
     {
       int nargin = args.length ();
       octave_stdout << "Hello World has " << nargin
             << " input arguments and "
             << nargout << " output arguments.\n";
       return octave_value_list ();
     }

   This example although short introduces the basics of writing a C++
function that can be dynamically linked to Octave.  The easiest way to
make available most of the definitions that might be necessary for a C++
oct-file in Octave is to use the `#include <octave/oct.h>' header.
Note that `octave/oct.h' is a C++ header and cannot be directly
`#include''ed in a C source file, nor any other language.  What follows
is mostly C++, with a discussion of other languages in section *note
Calling External Code from Oct-Files::.

   The macro that defines the entry point into the dynamically loaded
function is `DEFUN_DLD'.  This macro takes four arguments, these being

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

  2. The list of arguments to the function of type `octave_value_list',

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

  4. The string that will be seen as 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.  Firstly, it must be a valid Octave function name and so
must be a sequence of letters, digits and underscores, not starting
with a digit.  Secondly, 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 it should be
compiled to an oct-file using the command

     mkoctfile helloworld.cc

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

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

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


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

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

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

`Matrix'
     A double precision matrix class defined in dMatrix.h,

`ComplexMatrix'
     A complex matrix class defined in CMatrix.h, and

`BoolMatrix'
     A boolean matrix class defined in boolMatrix.h.

   These are the basic two-dimensional matrix types of octave.  In
additional there are a number of multi-dimensional array types, these
being

`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 means of constructing matrices of
multi-dimensional arrays.  Considering the `Matrix' type as an example

   * We can create an empty matrix or array with the empty constructor.
     For example

          Matrix a;

     This can be used on all matrix and array types

   * Define the dimensions of the matrix or array with a dim_vector.
     For example

          dim_vector dv (2);
          dv(0) = 2; dv(1) = 2;
          Matrix a (dv);

     This can be used on all matrix and array types

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

          Matrix a (2, 2)

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

   These types all share a number of basic methods and operators, a
selection of which include

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

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

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

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

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

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

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

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

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

     #include <octave/oct.h>

     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       int nargin = args.length ();
       if (nargin != 2)
         print_usage ();
       else
         {
           NDArray A = args(0).array_value ();
           NDArray B = args(1).array_value ();
           if (! error_state)
             return octave_value (A + B);
         }
       return octave_value_list ();
     }

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

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

     addtwomatrices (ones (2, 2), ones (2, 2))
           =>  2  2
               2  2

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

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


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

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

In Octave a character string is just a special `Array' class.  Consider
the example:

     #include <octave/oct.h>

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

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

           if (! error_state)
             {
               if (args(0).is_sq_string ())
                 retval(1) = octave_value (ch, true);
               else
                 retval(1) = octave_value (ch, true, '\'');

               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, true);
             }
         }
       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 an example is

         if (args(0).is_sq_string ())
           octave_stdout <<
             "First argument is a singularly quoted string\n";
         else if (args(0).is_dq_string ())
           octave_stdout <<
             "First argument is a doubly 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 c;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch, true, '\'');

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


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

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

Octave's cell type is equally accessible within oct-files.  A cell
array is just an array of `octave_value's, and so each element of the
cell array can then be treated just like any other `octave_value'.  A
simple example is

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

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

       if (nargin != 1)
         print_usage ();
       else
         {
           Cell c = args (0).cell_value ();
           if (! error_state)
             for (octave_idx_type i = 0; i < c.nelem (); i++)
               retval(i) = c.elem (i);
         }

       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
this example extracts the `octave_value's one by one from the cell
array and returns be as individual return arguments.  For example
consider

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

        1   2

     b3 = test


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

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

A structure in Octave is 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.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (args.length () == 2)
         {
           octave_scalar_map arg0 = args(0).scalar_map_value ();

           if (! error_state)
             {
               std::string arg1 = args(1).string_value ();

               if (! error_state)
                 {
                   octave_value tmp = arg0.contents (arg1);

                   if (tmp.is_defined ())
                     {
                       octave_scalar_map st;

                       st.assign ("selected", tmp);

                       retval = octave_value (st);
                     }
                   else
                     error ("sruct does not contain field named '%s'\n",
                            arg1.c_str ());
                 }
               else
                 error ("expecting character string as second argument");
             }
           else
             error ("expecting struct as first argument");
         }
       else
         print_usage ();

       return retval;
     }

   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     => selected = test

   The commented code above demonstrates how to iterate over all of the
fields of the structure, where as the following code demonstrates
finding a particular field in a more concise manner.

   As can be seen the `contents' method of the `Octave_map' class
returns a `Cell' which allows structure arrays to be represented.
Therefore, to obtain the underlying `octave_value' we write

     octave_value tmp = arg0.contents (p1) (0);

where the trailing (0) is the () operator on the `Cell' object.  We can
equally iterate of the elements of the Cell array to address the
elements of the structure array.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

`SparseMatrix'
     A double precision sparse matrix class

`SparseComplexMatrix'
     A complex sparse matrix class

`SparseBoolMatrix'
     A boolean sparse matrix class

   All of these classes inherit from the `Sparse<T>' template class,
and so all have similar capabilities and usage.  The `Sparse<T>' class
was based on Octave `Array<T>' class, and so users familiar with
Octave's `Array' classes will be comfortable with the use of the sparse
classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing `Array' classes.  However,
there are a few differences due the different nature of sparse objects,
and these will be described.  Firstly, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse
classes do not allow them at this time.  So all operations of the
sparse classes must be 2-dimensional.  This means that in fact
`SparseMatrix' is similar to Octave's `Matrix' class rather than its
`NDArray' class.

* Menu:

* Array and Sparse Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 The Differences between the Array and Sparse Classes
............................................................

The number of elements in a sparse matrix is considered to be the number
of non-zero elements rather than the product of the dimensions.
Therefore

     SparseMatrix sm;
     ...
     int nel = sm.nelem ();

returns the number of non-zero elements.  If the user really requires
the number of elements in the matrix, including the non-zero elements,
they should use `numel' rather than `nelem'.  Note that for very large
matrices, where the product of the two dimensions is larger than the
representation of an unsigned int, then `numel' can overflow.  An
example is `speye(1e6)' which will create a matrix with a million rows
and columns, but only a million non-zero elements.  Therefore the
number of rows by the number of columns in this case is more than two
hundred times the maximum value that can be represented by an unsigned
int.  The use of `numel' should therefore be avoided useless it is known
it won't overflow.

   Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function.  The reason is that if a
sparse object is non-const, then Octave will assume that a request for
a zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore a piece of code like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j)
                   << std::endl;

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

   An easy way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix.  So this is not a costly operation.  For example,
the above would become

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j)
                   << std::endl;

   Finally, as the sparse types aren't just represented as a contiguous
block of memory, the `fortran_vec' method of the `Array<T>' is not
available.  It is however replaced by three separate methods `ridx',
`cidx' and `data', that access the raw compressed column format that
the Octave sparse matrices are stored in.  Additionally, these methods
can be used in a manner similar to `elem', to allow the matrix to be
accessed or filled.  However, in that case it is up to the user to
respect the sparse matrix compressed column format discussed previous.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Differences,  Up: Sparse Matrices in Oct-Files

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

You have several alternatives for creating a sparse matrix.  You can
first create the data as three vectors representing the row and column
indexes and the data, and from those create the matrix.  Or
alternatively, you can create a sparse matrix with the appropriate
amount of space and then fill in the values.  Both techniques have their
advantages and disadvantages.

   Here is an example of how to create a small sparse matrix with the
first technique

     int nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 0; ridx(1) = 0; ridx(2) = 1; ridx(3) = 2;
     cidx(0) = 0; cidx(1) = 1; cidx(2) = 3; cidx(3) = 3;
     data(0) = 1; data(1) = 2; data(2) = 3; data(3) = 4;

     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *note Storage of Sparse
Matrices::.  Note that the compressed matrix format is not used at the
time of the creation of the matrix itself, however it is used
internally.

   As previously mentioned, the values of the sparse matrix are stored
in increasing column-major ordering.  Although the data passed by the
user does not need to respect this requirement, the pre-sorting the
data significantly speeds up the creation of the sparse matrix.

   The disadvantage of this technique of creating a sparse matrix is
that there is a brief time where two copies of the data exists.
Therefore for extremely memory constrained problems this might not be
the right technique to create the sparse matrix.

   The alternative is to first create the sparse matrix with the desired
number of non-zero elements and then later fill those elements in.  The
easiest way to do this is

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

   That creates the same matrix as previously.  Again, although it is
not strictly necessary, it is significantly faster if the sparse matrix
is created in this manner that the elements are added in column-major
ordering.  The reason for this is that if the elements are inserted at
the end of the current list of known elements then no element in the
matrix needs to be moved to allow the new element to be inserted.  Only
the column indexes need to be updated.

   There are a few further points to note about this technique of
creating a sparse matrix.  Firstly, it is possible to create a sparse
matrix with fewer elements than are actually inserted in the matrix.
Therefore

     int nz = 4, 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.  The reason is that
as each new element is added to the sparse matrix the space allocated
to it is increased by reallocating the memory.  This is an expensive
operation, that will significantly slow this means of creating a sparse
matrix.  Furthermore, it is possible to create a sparse matrix with too
much storage, so having NZ above equaling 6 is also valid.  The
disadvantage is that the matrix occupies more memory than strictly
needed.

   It is not always easy to know the number of non-zero elements prior
to filling a matrix.  For this reason the additional storage for the
sparse matrix can be removed after its creation with the
"maybe_compress" function.  Furthermore, the maybe_compress can
deallocate the unused storage, but it can equally 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 resorting the elements.  Therefore, if possible it is better is
the user doesn't add the zeros in the first place.  An example of the
use of "maybe_compress" is

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

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this technique might
be

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a-priori
                            // the final no of nz.

which is probably the most efficient means of creating the sparse
matrix.

   Finally, it might sometimes arise that the amount of storage
initially created is insufficient to completely store the sparse
matrix.  Therefore, the method `change_capacity' exists to reallocate
the sparse memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_mutate ();  // If don't know a-priori
                          // the final no of nz.

   Note that both increasing and decreasing the number of non-zero
elements in a sparse matrix is expensive, as it involves memory
reallocation.  Also as parts of the matrix, though not its entirety,
exist as the old and new copy at the same time, additional memory is
needed.  Therefore if possible this should be avoided.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

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

Most of the same operators and functions on sparse matrices that are
available from the Octave are equally available with oct-files.  The
basic means of extracting a sparse matrix from an `octave_value' and
returning them as an `octave_value', can be seen in the following
example.

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm =
         args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an octave-value is handled by the sparse
`octave_value' constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can easily be accessed with oct-files using the
support functions `get_global_value' and `set_global_value'.
`get_global_value' takes two arguments, the first is a string
representing the variable name to obtain.  The second argument is a
boolean argument specifying what to do in the case that no global
variable of the desired name is found.  An example of the use of these
two functions is

     #include <octave/oct.h>

     DEFUN_DLD (globaldemo, args, , "Global demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage ();
       else
         {
           std::string s = args(0).string_value ();
           if (! error_state)
             {
               octave_value tmp = get_global_value (s, true);
               if (tmp.is_defined ())
                 retval = tmp;
               else
                 retval = "Global variable not found";

               set_global_value ("a", 42.0);
             }
         }
       return retval;
     }

   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     => 10
     globaldemo ("c")
     => "Global variable not found"
     num2str (a)
     => 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another octave function from
within an oct-file, and there are many examples of such within octave
itself.  For example the `quad' function is an oct-file that calculates
the definite integral by quadrature over a user supplied function.

   There are also many ways in which a function might be passed.  It
might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. Inline Function

  4. String

   The example below demonstrates an example that accepts all four
means of passing a function to an oct-file.

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

     DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
     {
       int nargin = args.length();
       octave_value_list retval;

       if (nargin < 2)
         print_usage ();
       else
         {
           octave_value_list newargs;
           for (octave_idx_type i = nargin - 1; i > 0; i--)
             newargs (i - 1) = args(i);
           if (args(0).is_function_handle ()
               || args(0).is_inline_function ())
             {
               octave_function *fcn = args(0).function_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else if (args(0).is_string ())
             {
               std::string fcn = args (0).string_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else
             error ("funcdemo: expected string,",
                    " inline or function handle");
         }
       return retval;
     }

   The first argument to this demonstration is the user supplied
function and the following arguments are all passed to the user
function.

     funcdemo (@sin,1)
     => 0.84147
     funcdemo (@(x) sin(x), 1)
     => 0.84147
     funcdemo (inline ("sin(x)"), 1)
     => 0.84147
     funcdemo ("sin",1)
     => 0.84147
     funcdemo (@atan2, 1, 1)
     => 0.78540

   When the user function is passed as a string, the treatment of the
function is different.  In some cases it is necessary to always have the
user supplied function as an `octave_function' object.  In that case
the string argument can be used to create a temporary function like

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fname = "function y = ";
     fname.append (fcn_name);
     fname.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fname, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  The number of
input arguments to the user function is fixed, and in the above is a
single argument, and secondly to avoid leaving the temporary function
in the Octave symbol table it should be cleared after use.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
the declarations of the external C functions might 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 manner in
which to ensure that the C++ compiler treats these declarations as C
code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code however can pose some difficulties.  This is
due to differences in the manner in compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies a number of macros
that allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the `XSTOPX' function to
replace the Fortran `STOP' function.  `XSTOPX' uses the Octave
exception handler to treat failing cases in the Fortran code
explicitly.  Note that Octave supplies its own replacement BLAS
`XERBLA' function, which uses `XSTOPX'.

   If the underlying code calls `XSTOPX', then the `F77_XFCN' macro
should be used to call the underlying Fortran function.  The Fortran
exception state can then be checked with the global variable
`f77_exception_encountered'.  If `XSTOPX' will not be called, then the
`F77_FCN' macro should be used instead to call the Fortran code.

   There is no harm in using `F77_XFCN' in all cases, except that for
Fortran code that is short running and executes a large number of times,
there is potentially an overhead in doing so.  However, if `F77_FCN' is
used with code that calls `XSTOP', Octave can generate a segmentation
fault.

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

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

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortsub, FORTSUB)
             (const int&, double*, F77_CHAR_ARG_DECL
              F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortdemo , args , , "Fortran Demo.")
     {
       octave_value_list retval;
       int nargin = args.length();
       if (nargin != 1)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           if (! error_state)
             {
               double *av = a.fortran_vec ();
               octave_idx_type na = a.nelem ();
               OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

               F77_XFCN (fortsub, FORTSUB, (na, av, ctmp
                         F77_CHAR_ARG_LEN (128)));

               retval(1) = std::string (ctmp);
               retval(0) = a;
             }
         }
       return retval;
     }

and the Fortran function is

           subroutine fortsub (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 ('fortsub: 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 ('fortsub: 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.  An example of the behavior of this function is

     [b, s] = fortdemo (1:3)
     =>
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortdemo(0:3)
     error: fortsub:divide by zero
     error: exception encountered in Fortran subroutine fortsub_
     error: fortdemo: error in Fortran


File: octave.info,  Node: Allocating Local Memory in Oct-Files,  Next: Input Parameter Checking in Oct-Files,  Prev: Calling External Code from Oct-Files,  Up: Oct-Files

A.1.10 Allocating Local Memory in Oct-Files
-------------------------------------------

Allocating memory within an oct-file might seem easy as the C++
new/delete operators can be used.  However, in that case 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'.


File: octave.info,  Node: Input Parameter Checking in Oct-Files,  Next: Exception and Error Handling in Oct-Files,  Prev: Allocating Local Memory in Oct-Files,  Up: Oct-Files

A.1.11 Input Parameter Checking in Oct-Files
--------------------------------------------

As oct-files are compiled functions they have the possibility of causing
Octave to abort abnormally.  It is therefore important that each and
every function has the minimum of parameter checking needed 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 non
existent argument.  However, it some case 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.  Therefore, oct-files
often need additional input parameter checking.

   There are several functions within Octave that might be useful for
the purposes of parameter checking.  These include the methods of the
octave_value class like `is_real_matrix', etc., but equally include
more specialized functions.  Some of the more common ones are
demonstrated in the following example.

     #include <octave/oct.h>

     DEFUN_DLD (paramdemo, args, nargout,
                "Parameter Check Demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage();
       else if (nargout != 0)
         error ("paramdemo: function has no output arguments");
       else
         {
           NDArray m = args(0).array_value();
           double min_val = -10.0;
           double max_val = 10.0;
           octave_stdout << "Properties of input array:\n";
           if (m.any_element_is_negative ())
             octave_stdout << "  includes negative values\n";
           if (m.any_element_is_inf_or_nan())
             octave_stdout << "  includes Inf or NaN values\n";
           if (m.any_element_not_one_or_zero())
             octave_stdout <<
               "  includes other values than 1 and 0\n";
           if (m.all_elements_are_int_or_inf_or_nan())
             octave_stdout <<
               "  includes only int, Inf or NaN values\n";
           if (m.all_integers (min_val, max_val))
             octave_stdout <<
               "  includes only integers in [-10,10]\n";
         }
       return retval;
     }

An example of its use is:

     paramdemo ([1, 2, NaN, Inf])
     => Properties of input array:
           includes Inf or NaN values
           includes other values than 1 and 0
           includes only int, Inf or NaN values


File: octave.info,  Node: Exception and Error Handling in Oct-Files,  Next: Documentation and Test of Oct-Files,  Prev: Input Parameter Checking in Oct-Files,  Up: Oct-Files

A.1.12 Exception and Error Handling in Oct-Files
------------------------------------------------

Another important feature of Octave is its ability to react to the user
typing `Control-C' even during calculations.  This ability is based on
the C++ exception handler, where memory allocated by the C++ new/delete
methods are automatically released when the exception is treated.  When
writing an oct-file, to allow Octave to treat the user typing
`Control-C', the `OCTAVE_QUIT' macro is supplied.  For example:

     for (octave_idx_type i = 0; i < a.nelem (); i++)
       {
         OCTAVE_QUIT;
         b.elem(i) = 2. * a.elem(i);
       }

   The presence of the `OCTAVE_QUIT' macro in the inner loop allows
Octave to treat the user request with the `Control-C'.  Without this
macro, the user must either wait for the function to return before the
interrupt is processed, or press `Control-C' three times to force
Octave to exit.

   The `OCTAVE_QUIT' macro does impose a very small speed penalty, and
so for loops that are known to be small it might not make sense to
include `OCTAVE_QUIT'.

   When creating an oct-file that uses an external libraries, the
function might spend a significant portion of its time in the external
library.  It is not generally possible to use the `OCTAVE_QUIT' macro
in this case.  The alternative in this case is

     BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
     ...  some code that calls a "foreign" function ...
     END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;

   The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated.  Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
fortran_vec method or the `OCTAVE_LOCAL_BUFFER' macro.

   The Octave unwind_protect mechanism (*note The `unwind_protect'
Statement::) can also be used in oct-files.  In conjunction with the
exception handling of Octave, it is important to enforce that certain
code is run to allow variables, etc. to be restored even if an
exception occurs.  An example of the use of this mechanism is

     #include <octave/oct.h>
     #include <octave/unwind-prot.h>

     void
     err_hand (const char *fmt, ...)
     {
       // Do nothing!!
     }

     DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
     {
       int nargin = args.length();
       octave_value retval;
       if (nargin < 2)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           NDArray b = args(1).array_value ();

           if (! error_state)
             {
               unwind_protect::begin_frame ("Funwinddemo");
               unwind_protect_ptr (current_liboctave_warning_handler);
               set_liboctave_warning_handler(err_hand);
               retval = octave_value (quotient (a, b));
               unwind_protect::run_frame ("Funwinddemo");
             }
         }
       return retval;
     }

   As can be seen in the example:

     unwinddemo (1, 0)
     => Inf
     1 / 0
     => warning: division by zero
        Inf

   The division by zero (and in fact all warnings) is disabled in the
`unwinddemo' function.


File: octave.info,  Node: Documentation and Test of Oct-Files,  Prev: Exception and Error Handling in Oct-Files,  Up: Oct-Files

A.1.13 Documentation and Test of Oct-Files
------------------------------------------

The documentation of an oct-file is the fourth string parameter of the
`DEFUN_DLD' macro.  This string can be formatted in the same manner as
the help strings for user functions (*note Documentation Tips::),
however there are some issue that are particular to the formatting of
help strings within oct-files.

   The major issue is that the help string will typically be longer
than a single line of text, and so the formatting of long help strings
need to be taken into account.  There are several manners in which to
treat this issue, but the most common is illustrated in the following
example,

     DEFUN_DLD (do_what_i_want, args, nargout,
       "-*- texinfo -*-\n\
     @deftypefn {Function File} {} do_what_i_say (@var{n})\n\
     A function that does what the user actually wants rather\n\
     than what they requested.\n\
     @end deftypefn")
     {
     ...
     }

where, as can be seen, end line of text within the help string is
terminated by `\n\' which is an embedded new-line in the string
together with a C++ string continuation character.  Note that the final
`\' must be the last character on the line.

   Octave also includes the ability to embed the test and demonstration
code for a function within the code itself (*note Test and Demo
Functions::).  This can be used from within oct-files (or in fact any
file) with certain provisos.  Firstly, the test and demo functions of
Octave look for a `%!' as the first characters on a new-line to
identify test and demonstration code.  This is equally a requirement for
oct-files.  Furthermore the test and demonstration code must be included
in a comment block of the compiled code to avoid it being interpreted by
the compiler.  Finally, the Octave test and demonstration code must have
access to the source code of the oct-file and not just the compiled code
as the tests are stripped from the compiled code.  An example in an
oct-file might be

     /*

     %!error (sin())
     %!error (sin(1,1))
     %!assert (sin([1,2]),[sin(1),sin(2)])

     */


File: octave.info,  Node: Mex-Files,  Next: Standalone Programs,  Prev: Oct-Files,  Up: Dynamically Linked Functions

A.2 Mex-Files
=============

Octave includes an interface to allow legacy mex-files to be compiled
and used with Octave.  This interface can also be used to share code
between Octave and MATLAB users.  However, as mex-files expose the
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
mex-files access the variables passed to mex functions, there are a
significant number of additional copies of memory when calling or
returning from a mex function.  For this reason, new code should be
written using the oct-file interface discussed above if possible.

* Menu:

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::


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

A.2.1 Getting Started with Mex-Files
------------------------------------

The basic command to build a mex-file is either `mkoctfile --mex' or
`mex'.  The first can either be used from within Octave or from the
command line.  However, to avoid issues with MATLAB's own `mex'
command, the use of the command `mex' is limited to within Octave.

 -- Function File:  mex [options] file ...
     Compile source code written in C, C++, or Fortran, to a MEX file.
     This is equivalent to `mkoctfile --mex [options] file'.

     *See also:* *note mkoctfile: doc-mkoctfile.

 -- Function File:  mexext ()
     Return the filename extension used for MEX files.

   One important difference with the use of `mex' between MATLAB and
Octave is that the header file "matrix.h" is implicitly included through
the inclusion of "mex.h".  This is to avoid a conflict with the Octave
file "Matrix.h" with operating systems and compilers that don't
distinguish between filenames in upper and lower case

   Consider the short example:

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
                  const mxArray *prhs[])
     {
       mxArray *v = mxCreateDoubleMatrix (1, 1, mxREAL);
       double *data = mxGetPr (v);
       *data = 1.23456789;
       plhs[0] = v;
     }

   This simple example demonstrates the basics of writing a mex-file.
The entry point into the mex-file is defined by `mexFunction'.  Note
that the function name is not explicitly included in the `mexFunction'
and so there can only be a single `mexFunction' entry point per-file.
Also the name of the function is determined by the name of the mex-file
itself.  Therefore if the above function is in the file
`firstmexdemo.c', it can be compiled with

     mkoctfile --mex firstmexdemo.c

which creates a file `firstmexdemo.mex'.  The function can then be run
from Octave as

     firstmexdemo()
     => 1.2346

   It should be noted that the mex-file contains no help string for the
functions it contains.  To document mex-files, there should exist an
m-file in the same directory as the mex-file itself.  Taking the above
as an example, we would therefore have a file `firstmexdemo.m' that
might contain the text

     %FIRSTMEXDEMO 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 we cannot have multiple entry points into a single mex-file,
we can use the `mexFunctionName' function to determine what name the
mex-file was called with.  This can be used to alter the behavior of
the mex-file based on the function name.  For example if

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
                  const mxArray *prhs[])
     {
       const char *nm;
       nm = mexFunctionName ();
       mexPrintf ("You called function: %s\n", nm);
       if (strcmp (nm, "myfunc") == 0)
         mexPrintf ("This is the principal function\n", nm);
       return;
     }

is in file `myfunc.c', and it is compiled with

     mkoctfile --mex myfunc.c
     ln -s myfunc.mex myfunc2.mex

   Then as can be seen by

     myfunc()
     => You called function: myfunc
         This is the principal function
     myfunc2()
     => You called function: myfunc2

the behavior of the mex-file can be altered depending on the functions
name.

   Allow the user should only include `mex.h' in their code, Octave
declares additional functions, typedefs, etc., available to the user to
write mex-files in the headers `mexproto.h' and `mxarray.h'.


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

A.2.2 Working with Matrices and Arrays in Mex-Files
---------------------------------------------------

The basic mex type of all variables is `mxArray'.  All variables, such
as matrices, cell arrays or structures are all stored in this basic
type, and this type serves basically the same purpose as the
octave_value class in oct-files.  That is it acts as a container for the
more specialized types.

   The `mxArray' structure contains at a minimum, the variable it
represents name, its dimensions, its type and whether the variable is
real or complex.  It can however contain a number of additional fields
depending on the type of the `mxArray'.  There are a number of
functions to create `mxArray' structures, including
`mxCreateCellArray', `mxCreateSparse' and the generic
`mxCreateNumericArray'.

   The basic functions to access the data contained in an array is
`mxGetPr'.  As the mex interface assumes that the real and imaginary
parts of a complex array are stored separately, there is an equivalent
function `mxGetPi' that get the imaginary part.  Both of these
functions are for use only with double precision matrices.  There also
exists the generic function `mxGetData' and `mxGetImagData' that
perform the same operation on all matrix types.  For example:

     mxArray *m;
     mwSize *dims;
     UINT32_T *pr;

     dims = (mwSize *) mxMalloc (2 * sizeof(mwSize));
     dims[0] = 2;
     dims[1] = 2;
     m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
     pr =  = (UINT32_T *) mxGetData (m);

   There are also the functions `mxSetPr', etc., that perform the
inverse, and set the data of an Array to use the block of memory pointed
to by the argument of `mxSetPr'.

   Note the type `mwSize' used above, and `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 dimension and
maximum number or elements, while `mwIndex' is used to define indexing
into arrays.

   An example that demonstration how to work with arbitrary real or
complex double precision arrays is given by the file `mypow2.c' as given
below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
                  const mxArray* prhs[])
     {
       mwIndex i;
       mwSize n;
       double *vri, *vro;

       if (nrhs != 1 || ! mxIsNumeric (prhs[0]))
         mexErrMsgTxt ("expects matrix");

       n = mxGetNumberOfElements (prhs[0]);
       plhs[0] = (mxArray *) mxCreateNumericArray
         (mxGetNumberOfDimensions (prhs[0]),
          mxGetDimensions (prhs[0]), mxGetClassID (prhs[0]),
          mxIsComplex (prhs[0]));
       vri = mxGetPr (prhs[0]);
       vro = mxGetPr (plhs[0]);

       if (mxIsComplex (prhs[0]))
         {
           double *vii, *vio;
           vii = mxGetPi (prhs[0]);
           vio = mxGetPi (plhs[0]);

           for (i = 0; i < n; i++)
             {
               vro [i] = vri [i] * vri [i] - vii [i] * vii [i];
               vio [i] = 2 * vri [i] * vii [i];
             }
         }
       else
         {
           for (i = 0; i < n; i++)
             vro [i] = vri [i] * vri [i];
         }
     }

with an example of its use

     b = randn(4,1) + 1i * randn(4,1);
     all(b.^2 == mypow2(b))
     => 1

   The example above uses the functions `mxGetDimensions',
`mxGetNumberOfElements', and `mxGetNumberOfDimensions' to work with the
dimensions of multi-dimensional arrays.  The functions `mxGetM', and
`mxGetN' are also available to find the number of rows and columns in a
matrix.


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

A.2.3 Character Strings in Mex-Files
------------------------------------

As mex-files do not make the distinction between single and double
quoted strings within Octave, there is perhaps less complexity in the
use of strings and character matrices in mex-files.  An example of their
use, that parallels the demo in `stringdemo.cc', is given in the file
`mystring.c', as seen below.

     #include <string.h>
     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
                  const mxArray *prhs[])
     {
       mwIndex i, j;
       mwSize m, n;
       mxChar *pi, *po;

       if (nrhs != 1 || ! mxIsChar (prhs[0]) ||
           mxGetNumberOfDimensions (prhs[0]) > 2)
         mexErrMsgTxt ("expecting 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"])
     => s1 = Second String
             First String

   Other functions in the mex interface for handling character strings
are `mxCreateString', `mxArrayToString', and
`mxCreateCharMatrixFromStrings'.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an
arbitrary distinction as the data in the mxArray for the matrix is
consecutive in any case.


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

A.2.4 Cell Arrays with Mex-Files
--------------------------------

We can perform exactly the same operations in Cell arrays in mex-files
as we can in oct-files.  An example that reduplicates the functional of
the `celldemo.cc' oct-file in a mex-file is given by `mycell.c' as 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 ("expects cell");

       n = mxGetNumberOfElements (prhs[0]);
       n = (n > nlhs ? nlhs : n);

       for (i = 0; i < n; i++)
         plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
     }

which as can be seen below has exactly the same behavior as the oct-file
version.

     [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' is `mcSetCell' and is
defined as

     void mxSetCell (mxArray *ptr, int idx, mxArray *val);

   Finally, to create a cell array or matrix, the appropriate functions
are

     mxArray *mxCreateCellArray (int ndims, const int *dims);
     mxArray *mxCreateCellMatrix (int m, int n);


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

A.2.5 Structures with Mex-Files
-------------------------------

The basic function to create a structure in a mex-file is
`mxCreateStructMatrix', which creates a structure array with a two
dimensional matrix, or `mxCreateStructArray'.

     mxArray *mxCreateStructArray (int ndims, int *dims,
                                   int num_keys,
                                   const char **keys);
     mxArray *mxCreateStructMatrix (int rows, int cols,
                                    int num_keys,
                                    const char **keys);

   Accessing the fields of the structure can then be performed with the
`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 mex-file can be
found in the file `mystruct.c', as seen 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 ("expects 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, 0, 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 =
         {
           this =

           (,
             [1] = this1
             [2] = this2
             [3] = this3
             [4] = this4
           ,)

           that =

           (,
             [1] = that1
             [2] = that2
             [3] = that3
             [4] = that4
           ,)

         }

