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

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

Copyright © 1996-2024 The Octave Project Developers

   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

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

 -- : ZI = interp2 (X, Y, Z, XI, YI)
 -- : ZI = interp2 (Z, XI, YI)
 -- : ZI = interp2 (Z, N)
 -- : ZI = interp2 (Z)
 -- : ZI = interp2 (..., METHOD)
 -- : ZI = interp2 (..., METHOD, EXTRAP)

     Two-dimensional interpolation.

     Interpolate numeric reference data X, Y, Z to determine ZI at the
     coordinates XI, YI.  The reference data X, Y can be matrices, as
     returned by ‘meshgrid’, in which case the sizes of X, Y, and Z must
     be equal.  If X, Y are vectors describing a grid then
     ‘length (X) == columns (Z)’ and ‘length (Y) == rows (Z)’.  In
     either case the input data must be strictly monotonic.

     If called without X, Y, and just a single reference data matrix Z,
     the 2-D region ‘X = 1:columns (Z), Y = 1:rows (Z)’ is assumed.
     This saves memory if the grid is regular and the distance between
     points is not important.

     If called with a single reference data matrix Z and a refinement
     value N, then perform interpolation over a grid where each original
     interval has been recursively subdivided N times.  This results in
     ‘2^N-1’ additional points for every interval in the original grid.
     If N is omitted a value of 1 is used.  As an example, the interval
     [0,1] with ‘N==2’ results in a refined interval with points at [0,
     1/4, 1/2, 3/4, 1].

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "pchip"
          Piecewise cubic Hermite interpolating
          polynomial--shape-preserving interpolation with smooth first
          derivative.

     "cubic"
          Cubic interpolation using a convolution kernel function--third
          order method with smooth first derivative.

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

     EXTRAP is a scalar number.  It replaces values beyond the endpoints
     with EXTRAP.  Note that if EXTRAP is used, METHOD must be specified
     as well.  If EXTRAP is omitted and the METHOD is "spline", then the
     extrapolated values of the "spline" are used.  Otherwise the
     default EXTRAP value for any other METHOD is "NA".

     See also: *note interp1: XREFinterp1, *note interp3: XREFinterp3,
     *note interpn: XREFinterpn, *note meshgrid: XREFmeshgrid.

 -- : VI = interp3 (X, Y, Z, V, XI, YI, ZI)
 -- : VI = interp3 (V, XI, YI, ZI)
 -- : VI = interp3 (V, N)
 -- : VI = interp3 (V)
 -- : VI = interp3 (..., METHOD)
 -- : VI = interp3 (..., METHOD, EXTRAPVAL)

     Three-dimensional interpolation.

     Interpolate numeric reference data X, Y, Z, V to determine VI at
     the coordinates XI, YI, ZI.  The reference data X, Y, Z can be
     matrices, as returned by ‘meshgrid’, in which case the sizes of X,
     Y, Z, and V must be equal.  If X, Y, Z are vectors describing a
     cubic grid then ‘length (X) == columns (V)’, ‘length (Y) == rows
     (V)’, and ‘length (Z) == size (V, 3)’.  In either case the input
     data must be strictly monotonic.

     If called without X, Y, Z, and just a single reference data matrix
     V, the 3-D region ‘X = 1:columns (V), Y = 1:rows (V), Z = 1:size
     (V, 3)’ is assumed.  This saves memory if the grid is regular and
     the distance between points is not important.

     If called with a single reference data matrix V and a refinement
     value N, then perform interpolation over a 3-D grid where each
     original interval has been recursively subdivided N times.  This
     results in ‘2^N-1’ additional points for every interval in the
     original grid.  If N is omitted a value of 1 is used.  As an
     example, the interval [0,1] with ‘N==2’ results in a refined
     interval with points at [0, 1/4, 1/2, 3/4, 1].

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "cubic"
          Piecewise cubic Hermite interpolating
          polynomial--shape-preserving interpolation with smooth first
          derivative (not implemented yet).

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

     EXTRAPVAL is a scalar number.  It replaces values beyond the
     endpoints with EXTRAPVAL.  Note that if EXTRAPVAL is used, METHOD
     must be specified as well.  If EXTRAPVAL is omitted and the METHOD
     is "spline", then the extrapolated values of the "spline" are used.
     Otherwise the default EXTRAPVAL value for any other METHOD is "NA".

     See also: *note interp1: XREFinterp1, *note interp2: XREFinterp2,
     *note interpn: XREFinterpn, *note meshgrid: XREFmeshgrid.

 -- : VI = interpn (X1, X2, ..., V, Y1, Y2, ...)
 -- : VI = interpn (V, Y1, Y2, ...)
 -- : VI = interpn (V, M)
 -- : VI = interpn (V)
 -- : VI = interpn (..., METHOD)
 -- : VI = interpn (..., METHOD, EXTRAPVAL)

     Perform N-dimensional interpolation, where N is at least two.

     Each element of the N-dimensional numeric 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, Y2, ..., YN represent the points at which the
     array VI is interpolated.  They can be vectors of the same length
     and orientation in which case they are interpreted as coordinates
     of scattered points.  If they are vectors of differing orientation
     or length, they are used to form a grid in "ndgrid" format.  They
     can also be N-dimensional arrays of equal size.

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

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "linear" (default)
          Linear interpolation from nearest neighbors.

     "pchip"
          Piecewise cubic Hermite interpolating
          polynomial--shape-preserving interpolation with smooth first
          derivative (not implemented yet).

     "cubic"
          Cubic interpolation (same as "pchip" [not implemented yet]).

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

     The default method is "linear".

     EXTRAPVAL is a scalar number.  It replaces values beyond the
     endpoints with EXTRAPVAL.  Note that if EXTRAPVAL is used, METHOD
     must be specified as well.  If EXTRAPVAL is omitted and the METHOD
     is "spline", then the extrapolated values of the "spline" are used.
     Otherwise the default EXTRAPVAL value for any other METHOD is ‘NA’.

     See also: *note interp1: XREFinterp1, *note interp2: XREFinterp2,
     *note interp3: XREFinterp3, *note spline: XREFspline, *note ndgrid:
     XREFndgrid.

   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.


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

30 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::
* Vector Rotation Matrices::

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

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

 -- : TRI = delaunay (X, Y)
 -- : TETR = delaunay (X, Y, Z)
 -- : TRI = delaunay (X)
 -- : TRI = delaunay (..., OPTIONS)
     Compute the Delaunay triangulation for a 2-D or 3-D set of points.

     For 2-D sets, the return value TRI is a set of triangles which
     satisfies the Delaunay circum-circle criterion, i.e., no data point
     from [X, Y] is within the circum-circle of the defining triangle.
     The set of triangles TRI is a matrix of size [n, 3].  Each row
     defines a triangle and the three columns are the three vertices of
     the triangle.  The value of ‘TRI(i,j)’ is an index into X and Y for
     the location of the j-th vertex of the i-th triangle.

     For 3-D sets, the return value TETR is a set of tetrahedrons which
     satisfies the Delaunay circum-circle criterion, i.e., no data point
     from [X, Y, Z] is within the circum-circle of the defining
     tetrahedron.  The set of tetrahedrons is a matrix of size [n, 4].
     Each row defines a tetrahedron and the four columns are the four
     vertices of the tetrahedron.  The value of ‘TETR(i,j)’ is an index
     into X, Y, Z for the location of the j-th vertex of the i-th
     tetrahedron.

     The input X may also be a matrix with two or three columns where
     the first column contains x-data, the second y-data, and the
     optional third column contains z-data.

     An optional final argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options are ‘{"Qt", "Qbb", "Qc"}’.  If Qhull fails for 2-D input
     the triangulation is attempted again with the options ‘{"Qt",
     "Qbb", "Qc", "Qz"}’ which may result in reduced accuracy.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

          x = rand (1, 10);
          y = rand (1, 10);
          tri = delaunay (x, y);
          triplot (tri, x, y);
          hold on;
          plot (x, y, "r*");
          axis ([0,1,0,1]);

     See also: *note delaunayn: XREFdelaunayn, *note convhull:
     XREFconvhull, *note voronoi: XREFvoronoi, *note triplot:
     XREFtriplot, *note trimesh: XREFtrimesh, *note tetramesh:
     XREFtetramesh, *note trisurf: XREFtrisurf.

   For 3-D inputs ‘delaunay’ 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.

 -- : T = delaunayn (PTS)
 -- : T = delaunayn (PTS, OPTIONS)
     Compute the Delaunay triangulation for an N-dimensional set of
     points.

     The Delaunay triangulation is a tessellation of the convex hull of
     a set of points such that no N-sphere defined by the N-triangles
     contains any other points from the set.

     The input matrix PTS of size [n, dim] contains n points in a space
     of dimension dim.  The return matrix T has size [m, dim+1].  Each
     row of T contains a set of indices back into the original set of
     points PTS which describes a simplex of dimension dim.  For
     example, a 2-D simplex is a triangle and 3-D simplex is a
     tetrahedron.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options depend on the dimension of the input:

        • 2-D and 3-D: OPTIONS = ‘{"Qt", "Qbb", "Qc"}’

        • 4-D and higher: OPTIONS = ‘{"Qt", "Qbb", "Qc", "Qx"}’

     If Qhull fails for 2-D input the triangulation is attempted again
     with the options ‘{"Qt", "Qbb", "Qc", "Qz"}’ which may result in
     reduced accuracy.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     See also: *note delaunay: XREFdelaunay, *note convhulln:
     XREFconvhulln, *note voronoin: XREFvoronoin, *note trimesh:
     XREFtrimesh, *note tetramesh: XREFtetramesh.

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

     rand ("state", 1);
     x = rand (1, 10);
     y = rand (1, 10);
     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

30.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.  ‘tetramesh’
will plot the triangulation of a 3-dimensional set of points.

 -- : triplot (TRI, X, Y)
 -- : triplot (TRI, X, Y, LINESPEC)
 -- : H = triplot (...)
     Plot a 2-D triangular mesh.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.

     The linestyle to use for the plot can be defined with the argument
     LINESPEC of the same format as the ‘plot’ command.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note plot: XREFplot, *note trimesh: XREFtrimesh, *note
     trisurf: XREFtrisurf, *note delaunay: XREFdelaunay.

 -- : trimesh (TRI, X, Y, Z, C)
 -- : trimesh (TRI, X, Y, Z)
 -- : trimesh (TRI, X, Y)
 -- : trimesh (..., PROP, VAL, ...)
 -- : H = trimesh (...)
     Plot a 3-D triangular wireframe mesh.

     In contrast to ‘mesh’, which plots a mesh using rectangles,
     ‘trimesh’ plots the mesh using triangles.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.  Z determines the height above the
     plane of each vertex.  If no Z input is given then the triangles
     are plotted as a 2-D figure.

     The color of the trimesh is computed by linearly scaling the Z
     values to fit the range of the current colormap.  Use ‘caxis’
     and/or change the colormap to control the appearance.

     Optionally, the color of the mesh can be specified independently of
     Z by supplying C, which is a vector for colormap data, or a matrix
     with three columns for RGB data.  The number of colors specified in
     C must either equal the number of vertices in Z or the number of
     triangles in TRI.

     Any property/value pairs are passed directly to the underlying
     patch object.  The full list of properties is documented at *note
     Patch Properties::.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note mesh: XREFmesh, *note tetramesh: XREFtetramesh,
     *note triplot: XREFtriplot, *note trisurf: XREFtrisurf, *note
     delaunay: XREFdelaunay, *note patch: XREFpatch, *note hidden:
     XREFhidden.

 -- : trisurf (TRI, X, Y, Z, C)
 -- : trisurf (TRI, X, Y, Z)
 -- : trisurf (..., PROP, VAL, ...)
 -- : H = trisurf (...)
     Plot a 3-D triangular surface.

     In contrast to ‘surf’, which plots a surface mesh using rectangles,
     ‘trisurf’ plots the mesh using triangles.

     TRI is typically the output of a Delaunay triangulation over the
     grid of X, Y.  Every row of TRI represents one triangle and
     contains three indices into [X, Y] which are the vertices of the
     triangles in the x-y plane.  Z determines the height above the
     plane of each vertex.

     The color of the trisurf is computed by linearly scaling the Z
     values to fit the range of the current colormap.  Use ‘caxis’
     and/or change the colormap to control the appearance.

     Optionally, the color of the mesh can be specified independently of
     Z by supplying C, which is a vector for colormap data, or a matrix
     with three columns for RGB data.  The number of colors specified in
     C must either equal the number of vertices in Z or the number of
     triangles in TRI.  When specifying the color at each vertex the
     triangle will be colored according to the color of the first vertex
     only (see patch documentation and the "FaceColor" property when set
     to "flat").

     Any property/value pairs are passed directly to the underlying
     patch object.  The full list of properties is documented at *note
     Patch Properties::.

     The optional return value H is a graphics handle to the created
     patch object.

     See also: *note surf: XREFsurf, *note triplot: XREFtriplot, *note
     trimesh: XREFtrimesh, *note delaunay: XREFdelaunay, *note patch:
     XREFpatch, *note shading: XREFshading.

 -- : tetramesh (T, X)
 -- : tetramesh (T, X, C)
 -- : tetramesh (..., PROPERTY, VAL, ...)
 -- : H = tetramesh (...)
     Display the tetrahedrons defined in the m-by-4 matrix T as 3-D
     patches.

     T is typically the output of a Delaunay triangulation of a 3-D set
     of points.  Every row of T contains four indices into the n-by-3
     matrix X of the vertices of a tetrahedron.  Every row in X
     represents one point in 3-D space.

     The vector C specifies the color of each tetrahedron as an index
     into the current colormap.  The default value is 1:m where m is the
     number of tetrahedrons; the indices are scaled to map to the full
     range of the colormap.  If there are more tetrahedrons than colors
     in the colormap then the values in C are cyclically repeated.

     Calling ‘tetramesh (..., "property", "value", ...)’ passes all
     property/value pairs directly to the patch function as additional
     arguments.  The full list of properties is documented at *note
     Patch Properties::.

     The optional return value H is a vector of patch handles where each
     handle represents one tetrahedron in the order given by T.  A
     typical use case for H is to turn the respective patch "visible"
     property "on" or "off".

     Type ‘demo tetramesh’ to see examples on using ‘tetramesh’.

     See also: *note trimesh: XREFtrimesh, *note delaunay: XREFdelaunay,
     *note delaunayn: XREFdelaunayn, *note patch: XREFpatch.

   The difference between ‘triplot’, and ‘trimesh’ or ‘trisurf’, 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

30.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 = BETA * T

where BETA contains N + 1 values that together as a vector represent the
Barycentric coordinates of the point P.  To ensure a unique solution for
the values of BETA an additional criteria of

     sum (BETA) == 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.

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

     Programming Note: The algorithm is O(M*N) for locating M points in
     N triangles.  Performance is typically much faster if the points to
     be located are in a single continuous path; a point is first
     checked against the region its predecessor was found in, speeding
     up lookups for points along a continuous path.

     See also: *note delaunay: XREFdelaunay, *note delaunayn:
     XREFdelaunayn.

 -- : IDX = tsearchn (X, T, XI)
 -- : [IDX, P] = tsearchn (X, T, XI)
     Find the simplexes enclosing the given points.

     ‘tsearchn’ is typically used with ‘delaunayn’: ‘T = delaunayn (X)’
     returns a set of simplexes ‘t’, then ‘tsearchn’ returns the row
     index of T containing each point of XI.  For points outside the
     convex hull, IDX is NaN.

     If requested, ‘tsearchn’ also returns the barycentric coordinates P
     of the enclosing simplexes.

     See also: *note delaunay: XREFdelaunay, *note delaunayn:
     XREFdelaunayn, *note tsearch: XREFtsearch.

   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, 4];

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 vertices of the N-simplex
within which the desired point is found.

 -- : IDX = dsearch (X, Y, TRI, XI, YI)
 -- : IDX = dsearch (X, Y, TRI, XI, YI, S)
     Return the index IDX of 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: XREFdsearchn, *note tsearch: XREFtsearch.

 -- : IDX = dsearchn (X, TRI, XI)
 -- : IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- : IDX = dsearchn (X, XI)
 -- : [IDX, D] = dsearchn (...)
     Return the index IDX of 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)’.

     The optional output D contains a column vector of distances between
     the query points XI and the nearest simplex points X.

     See also: *note dsearch: XREFdsearch, *note tsearch: XREFtsearch.

   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

30.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 vertices of the Voronoi tessellation are the centers of the
circum-circles of the simplices of the Delaunay tessellation.

 -- : voronoi (X, Y)
 -- : voronoi (X, Y, OPTIONS)
 -- : voronoi (..., "linespec")
 -- : voronoi (HAX, ...)
 -- : H = voronoi (...)
 -- : [VX, VY] = voronoi (...)
     Plot the Voronoi diagram of points ‘(X, Y)’.

     The Voronoi facets with points at infinity are not drawn.

     The OPTIONS argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.

     If "linespec" is given it is used to set the color and line style
     of the plot.

     If an axes graphics handle HAX is supplied then the Voronoi diagram
     is drawn on the specified axes rather than in a new figure.

     If a single output argument is requested then the Voronoi diagram
     will be plotted and a graphics handle H to the plot is returned.

     [VX, VY] = voronoi (...) returns the Voronoi vertices instead of
     plotting the diagram.

          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: XREFvoronoin, *note delaunay:
     XREFdelaunay, *note convhull: XREFconvhull.

 -- : [C, F] = voronoin (PTS)
 -- : [C, F] = voronoin (PTS, OPTIONS)
     Compute N-dimensional Voronoi facets.

     The input matrix PTS of size [n, dim] contains n points in a space
     of dimension dim.

     C contains the points of the Voronoi facets.  The list F contains,
     for each facet, the indices of the Voronoi points.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.

     The default options depend on the dimension of the input:

        • 2-D and 3-D: OPTIONS = ‘{"Qbb"}’

        • 4-D and higher: OPTIONS = ‘{"Qbb", "Qx"}’

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     See also: *note voronoi: XREFvoronoi, *note convhulln:
     XREFconvhulln, *note delaunayn: XREFdelaunayn.

   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.

 -- : A = polyarea (X, Y)
 -- : A = polyarea (X, Y, DIM)

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

 -- : AREA = rectint (A, B)
     Compute area or volume of intersection of rectangles or N-D boxes.

     Compute the area of intersection of rectangles in A and rectangles
     in B.  N-dimensional boxes are supported in which case the volume,
     or hypervolume is computed according to the number of dimensions.

     2-dimensional rectangles are defined as ‘[xpos ypos width height]’
     where xpos and ypos are the position of the bottom left corner.
     Higher dimensions are supported where the coordinates for the
     minimum value of each dimension follow the length of the box in
     that dimension, e.g., ‘[xpos ypos zpos kpos ... width height depth
     k_length ...]’.

     Each row of A and B define a rectangle, and if both define multiple
     rectangles, 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: XREFpolyarea.

 -- : IN = inpolygon (X, Y, XV, YV)
 -- : [IN, ON] = inpolygon (X, Y, XV, YV)

     For a polygon defined by vertex points ‘(XV, YV)’, return true if
     the points ‘(X, Y)’ are inside (or on the boundary) of the polygon;
     Otherwise, return false.

     The input variables X and Y, must have the same dimension.

     The optional output ON returns true if the points are exactly on
     the polygon edge, and false otherwise.

     See also: *note delaunay: XREFdelaunay.

   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

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

 -- : H = convhull (X, Y)
 -- : H = convhull (X, Y, Z)
 -- : H = convhull (X)
 -- : H = convhull (..., OPTIONS)
 -- : [H, V] = convhull (...)
     Compute the convex hull of a 2-D or 3-D set of points.

     The hull H is a linear index vector into the original set of points
     that specifies which points form the enclosing hull.  For 2-D
     inputs only, the output is ordered in a counterclockwise manner
     around the hull.

     The input X may also be a matrix with two or three columns where
     the first column contains x-data, the second y-data, and the
     optional third column contains z-data.

     An optional final argument, which must be a string or cell array of
     strings, contains options passed to the underlying qhull command.
     See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     option is ‘{"Qt"}’.

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     If the second output V is requested the volume of the enclosing
     convex hull is calculated.

     See also: *note convhulln: XREFconvhulln, *note delaunay:
     XREFdelaunay, *note voronoi: XREFvoronoi.

 -- : H = convhulln (PTS)
 -- : H = convhulln (PTS, OPTIONS)
 -- : [H, V] = convhulln (...)
     Compute the convex hull of the set of points PTS.

     PTS is a matrix of size [n, dim] containing n points in a space of
     dimension dim.

     The hull H is an index vector into the set of points and specifies
     which points form the enclosing hull.

     An optional second argument, which must be a string or cell array
     of strings, contains options passed to the underlying qhull
     command.  See the documentation for the Qhull library for details
     <http://www.qhull.org/html/qh-quick.htm#options>.  The default
     options depend on the dimension of the input:

        • 2D, 3D, 4D: OPTIONS = ‘{"Qt"}’

        • 5D and higher: OPTIONS = ‘{"Qt", "Qx"}’

     If OPTIONS is not present or ‘[]’ then the default arguments are
     used.  Otherwise, OPTIONS replaces the default argument list.  To
     append user options to the defaults it is necessary to repeat the
     default arguments in OPTIONS.  Use a null string to pass no
     arguments.

     If the second output V is requested the volume of the enclosing
     convex hull is calculated.

     See also: *note convhull: XREFconvhull, *note delaunayn:
     XREFdelaunayn, *note voronoin: XREFvoronoin.

   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,  Next: Vector Rotation Matrices,  Prev: Convex Hull,  Up: Geometry

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

 -- : ZI = griddata (X, Y, Z, XI, YI)
 -- : ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- : [XI, YI, ZI] = griddata (...)
 -- : VI = griddata (X, Y, Z, V, XI, YI, ZI)
 -- : VI = griddata (X, Y, Z, V, XI, YI, ZI, METHOD)
 -- : VI = griddata (X, Y, Z, V, XI, YI, ZI, METHOD, OPTIONS)

     Interpolate irregular 2-D and 3-D source data at specified points.

     For 2-D interpolation, the inputs X and Y define the points where
     the function ‘Z = f (X, Y)’ is evaluated.  The inputs X, Y, Z are
     either vectors of the same length, or the unequal vectors X, Y are
     expanded to a 2-D grid with ‘meshgrid’ and Z is a 2-D matrix
     matching the resulting size of the X-Y grid.

     The interpolation points are (XI, YI).  If, and only if, XI is a
     row vector and YI is a column vector, then ‘meshgrid’ will be used
     to create a mesh of interpolation points.

     For 3-D interpolation, the inputs X, Y, and Z define the points
     where the function ‘V = f (X, Y, Z)’ is evaluated.  The inputs X,
     Y, Z are either vectors of the same length, or if they are of
     unequal length, then they are expanded to a 3-D grid with
     ‘meshgrid’.  The size of the input V must match the size of the
     original data, either as a vector or a matrix.

     The optional input interpolation METHOD can be "nearest", "linear",
     or for 2-D data "v4".  When the method is "nearest", the output VI
     will be the closest point in the original data (X, Y, Z) to the
     query point (XI, YI, ZI).  When the method is "linear", the output
     VI will be a linear interpolation between the two closest points in
     the original source data in each dimension.  For 2-D cases only,
     the "v4" method is also available which implements a biharmonic
     spline interpolation.  If METHOD is omitted or empty, it defaults
     to "linear".

     For 3-D interpolation, the optional argument OPTIONS is passed
     directly to Qhull when computing the Delaunay triangulation used
     for interpolation.  For more information on the defaults and how to
     pass different values, *note ‘delaunayn’: XREFdelaunayn.

     Programming Notes: If the input is complex the real and imaginary
     parts are interpolated separately.  Interpolation is normally based
     on a Delaunay triangulation.  Any query values outside the convex
     hull of the input points will return ‘NaN’.  However, the "v4"
     method does not use the triangulation and will return values
     outside the original data (extrapolation).

     See also: *note griddata3: XREFgriddata3, *note griddatan:
     XREFgriddatan, *note delaunay: XREFdelaunay.

 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI)
 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI, METHOD)
 -- : VI = griddata3 (X, Y, Z, V, XI, YI, ZI, METHOD, OPTIONS)

     Interpolate irregular 3-D source data at specified points.

     The inputs X, Y, and Z define the points where the function ‘V = f
     (X, Y, Z)’ is evaluated.  The inputs X, Y, Z are either vectors of
     the same length, or if they are of unequal length, then they are
     expanded to a 3-D grid with ‘meshgrid’.  The size of the input V
     must match the size of the original data, either as a vector or a
     matrix.

     The interpolation points are specified by XI, YI, ZI.

     The optional input interpolation METHOD can be "nearest" or
     "linear".  When the method is "nearest", the output VI will be the
     closest point in the original data (X, Y, Z) to the query point
     (XI, YI, ZI).  When the method is "linear", the output VI will be a
     linear interpolation between the two closest points in the original
     source data in each dimension.  If METHOD is omitted or empty, it
     defaults to "linear".

     The optional argument OPTIONS is passed directly to Qhull when
     computing the Delaunay triangulation used for interpolation.  See
     ‘delaunayn’ for information on the defaults and how to pass
     different values.

     Programming Notes: If the input is complex the real and imaginary
     parts are interpolated separately.  Interpolation is based on a
     Delaunay triangulation and any query values outside the convex hull
     of the input points will return ‘NaN’.

     See also: *note griddata: XREFgriddata, *note griddatan:
     XREFgriddatan, *note delaunayn: XREFdelaunayn.

 -- : YI = griddatan (X, Y, XI)
 -- : YI = griddatan (X, Y, XI, METHOD)
 -- : YI = griddatan (X, Y, XI, METHOD, OPTIONS)

     Interpolate irregular source data X, Y at points specified by XI.

     The input X is an MxN matrix representing M points in an
     N-dimensional space.  The input Y is a single-valued column vector
     (Mx1) representing a function evaluated at the points X, i.e., ‘Y =
     fcn (X)’.  The input XI is a list of points for which the function
     output YI should be approximated through interpolation.  XI must
     have the same number of columns (N) as X so that the dimensionality
     matches.

     The optional input interpolation METHOD can be "nearest" or
     "linear".  When the method is "nearest", the output YI will be the
     closest point in the original data X to the query point XI.  When
     the method is "linear", the output YI will be a linear
     interpolation between the two closest points in the original source
     data.  If METHOD is omitted or empty, it defaults to "linear".

     The optional argument OPTIONS is passed directly to Qhull when
     computing the Delaunay triangulation used for interpolation.  See
     ‘delaunayn’ for information on the defaults and how to pass
     different values.

     Example

          ## Evaluate sombrero() function at irregular data points
          x = 16*gallery ("uniformdata", [200,1], 1) - 8;
          y = 16*gallery ("uniformdata", [200,1], 11) - 8;
          z = sin (sqrt (x.^2 + y.^2)) ./ sqrt (x.^2 + y.^2);
          ## Create a regular grid and interpolate data
          [xi, yi] = ndgrid (linspace (-8, 8, 50));
          zi = griddatan ([x, y], z, [xi(:), yi(:)]);
          zi = reshape (zi, size (xi));
          ## Plot results
          clf ();
          plot3 (x, y, z, "or");
          hold on
          surf (xi, yi, zi);
          legend ("Original Data", "Interpolated Data");

     Programming Notes: If the input is complex the real and imaginary
     parts are interpolated separately.  Interpolation is based on a
     Delaunay triangulation and any query values outside the convex hull
     of the input points will return ‘NaN’.  For 2-D and 3-D data
     additional interpolation methods are available by using the
     ‘griddata’ function.

     See also: *note griddata: XREFgriddata, *note griddata3:
     XREFgriddata3, *note delaunayn: XREFdelaunayn.

   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));
     zz = griddata (x, y, z, xx, yy);
     mesh (xx, yy, zz);

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


File: octave.info,  Node: Vector Rotation Matrices,  Prev: Interpolation on Scattered Data,  Up: Geometry

30.5 Vector Rotation Matrices
=============================

Also included in Octave's geometry functions are primitive functions to
enable vector rotations in 3-dimensional space.  Separate functions are
provided for rotation about each of the principle axes, X, Y, and Z.
According to Euler's rotation theorem, any arbitrary rotation, R, of any
vector, P, can be expressed as a product of the three principle
rotations:

     p' = Rp = Rz*Ry*Rx*p

 -- : T = rotx (ANGLE)

     ‘rotx’ returns the 3x3 transformation matrix corresponding to an
     active rotation of a vector about the x-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the y-z plane from the
     positive x side.

     The form of the transformation matrix is:

               | 1      0           0      |
           T = | 0  cos(ANGLE) -sin(ANGLE) |
               | 0  sin(ANGLE)  cos(ANGLE) |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation ‘V =
     T*U’.  For example, a vector, U, pointing along the positive
     y-axis, rotated 90-degrees about the x-axis, will result in a
     vector pointing along the positive z-axis:

          >> u = [0 1 0]'
          u =
             0
             1
             0

          >> T = rotx (90)
          T =
             1.00000   0.00000   0.00000
             0.00000   0.00000  -1.00000
             0.00000   1.00000   0.00000

          >> v = T*u
          v =
             0.00000
             0.00000
             1.00000

     See also: *note roty: XREFroty, *note rotz: XREFrotz.

 -- : T = roty (ANGLE)

     ‘roty’ returns the 3x3 transformation matrix corresponding to an
     active rotation of a vector about the y-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the z-x plane from the
     positive y side.

     The form of the transformation matrix is:

               |  cos(ANGLE)  0  sin(ANGLE) |
           T = |      0       1      0      |
               | -sin(ANGLE)  0  cos(ANGLE) |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation ‘V =
     T*U’.  For example, a vector, U, pointing along the positive
     z-axis, rotated 90-degrees about the y-axis, will result in a
     vector pointing along the positive x-axis:

            >> u = [0 0 1]'
             u =
                0
                0
                1

             >> T = roty (90)
             T =
                0.00000   0.00000   1.00000
                0.00000   1.00000   0.00000
               -1.00000   0.00000   0.00000

             >> v = T*u
             v =
                1.00000
                0.00000
                0.00000

     See also: *note rotx: XREFrotx, *note rotz: XREFrotz.

 -- : T = rotz (ANGLE)

     ‘rotz’ returns the 3x3 transformation matrix corresponding to an
     active rotation of a vector about the z-axis by the specified
     ANGLE, given in degrees, where a positive angle corresponds to a
     counterclockwise rotation when viewing the x-y plane from the
     positive z side.

     The form of the transformation matrix is:

               | cos(ANGLE) -sin(ANGLE) 0 |
           T = | sin(ANGLE)  cos(ANGLE) 0 |
               |     0           0      1 |

     This rotation matrix is intended to be used as a left-multiplying
     matrix when acting on a column vector, using the notation ‘V =
     T*U’.  For example, a vector, U, pointing along the positive
     x-axis, rotated 90-degrees about the z-axis, will result in a
     vector pointing along the positive y-axis:

            >> u = [1 0 0]'
             u =
                1
                0
                0

             >> T = rotz (90)
             T =
                0.00000  -1.00000   0.00000
                1.00000   0.00000   0.00000
                0.00000   0.00000   1.00000

             >> v = T*u
             v =
                0.00000
                1.00000
                0.00000

     See also: *note rotx: XREFrotx, *note roty: XREFroty.


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

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

 -- : Y = fft (X)
 -- : Y = fft (X, N)
 -- : Y = fft (X, N, DIM)
     Compute the discrete Fourier transform of X 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: XREFifft, *note fft2: XREFfft2, *note fftn:
     XREFfftn, *note fftw: XREFfftw.

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

     The inverse FFT is calculated along the first non-singleton
     dimension of the array.  Thus if Y is a matrix, ‘ifft (Y)’ computes
     the inverse FFT for each column of Y.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of Y 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 Y is
     resized and padded with zeros.  Otherwise, if N is smaller than the
     dimension along which the inverse FFT is calculated, then Y 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: XREFfft, *note ifft2: XREFifft2, *note ifftn:
     XREFifftn, *note fftw: XREFfftw.

 -- : B = fft2 (A)
 -- : B = 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: *note ifft2: XREFifft2, *note fft: XREFfft, *note fftn:
     XREFfftn, *note fftw: XREFfftw.

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

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

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

     See also: *note fft2: XREFfft2, *note ifft: XREFifft, *note ifftn:
     XREFifftn, *note fftw: XREFfftw.

 -- : B = fftn (A)
 -- : B = 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: XREFifftn, *note fft: XREFfft, *note fft2:
     XREFfft2, *note fftw: XREFfftw.

 -- : A = ifftn (B)
 -- : A = ifftn (B, SIZE)
     Compute the inverse N-dimensional discrete Fourier transform of B
     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 B, then the dimension
     of B is truncated prior to performing the inverse FFT.  Otherwise,
     if an element of SIZE is larger than the corresponding dimension
     then B is resized and padded with zeros.

     See also: *note fftn: XREFfftn, *note ifft: XREFifft, *note ifft2:
     XREFifft2, *note fftw: XREFfftw.

   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.

 -- : METHOD = fftw ("planner")
 -- : fftw ("planner", METHOD)
 -- : WISDOM = fftw ("dwisdom")
 -- : fftw ("dwisdom", WISDOM)
 -- : NTHREADS = fftw ("threads")
 -- : fftw ("threads", NTHREADS)

     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 re-imported as follows

          fftw ("dwisdom", WISDOM)

     If WISDOM is an empty string, 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.

     The number of threads used for computing the plans and executing
     the transforms can be set with

          fftw ("threads", NTHREADS)

     Note that Octave must be compiled with multi-threaded FFTW support
     for this feature.  By default, the number of (logical) processors
     available to the current process or 3 is used (whichever is
     smaller).

     See also: *note fft: XREFfft, *note ifft: XREFifft, *note fft2:
     XREFfft2, *note ifft2: XREFifft2, *note fftn: XREFfftn, *note
     ifftn: XREFifftn.

 -- : C = fftconv (X, Y)
 -- : C = 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: XREFdeconv, *note conv: XREFconv, *note
     conv2: XREFconv2.

 -- : Y = fftfilt (B, X)
 -- : Y = fftfilt (B, X, N)
     Filter X with the FIR filter B using the FFT.

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

     Given the optional third argument, N, ‘fftfilt’ uses the
     overlap-add method to filter X with B using an N-point FFT.  The
     FFT size must be an even power of 2 and must be greater than or
     equal to the length of B.  If the specified N does not meet these
     criteria, it is automatically adjusted to the nearest value that
     does.

     See also: *note filter: XREFfilter, *note filter2: XREFfilter2.

 -- : Y = filter (B, A, X)
 -- : [Y, SF] = filter (B, A, X, SI)
 -- : [Y, SF] = filter (B, A, X, [], DIM)
 -- : [Y, SF] = filter (B, A, X, SI, DIM)
     Apply a 1-D digital filter to the data X.

     ‘filter’ returns 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.  The result is calculated
     over the first non-singleton dimension of X or over DIM if
     supplied.

     An equivalent form of the 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: XREFfilter2, *note fftfilt: XREFfftfilt,
     *note freqz: XREFfreqz.

 -- : Y = filter2 (B, X)
 -- : 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: XREFconv2.

 -- : [H, W] = freqz (B, A, N, "whole")
 -- : [H, W] = freqz (B)
 -- : [H, W] = freqz (B, A)
 -- : [H, W] = freqz (B, A, N)
 -- : H = freqz (B, A, W)
 -- : [H, W] = freqz (..., FS)
 -- : freqz (...)

     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 A is omitted, the denominator is assumed to be 1 (this
     corresponds to a simple FIR filter).

     If N is omitted, a value of 512 is assumed.  For fastest
     computation, N should factor into a small number of small primes.

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

     ‘freqz (B, A, W)’

     Evaluate the response at the specific frequencies in the vector W.
     The values for W are measured in radians.

     ‘[...] = 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.

     ‘freqz (...)’

     Plot the magnitude and phase response of H rather than returning
     them.

     See also: *note freqz_plot: XREFfreqz_plot.

 -- : freqz_plot (W, H)
 -- : freqz_plot (W, H, FREQ_NORM)
     Plot the magnitude and phase response of H.

     If the optional FREQ_NORM argument is true, the frequency vector W
     is in units of normalized radians.  If FREQ_NORM is false, or not
     given, then W is measured in Hertz.

     See also: *note freqz: XREFfreqz.

 -- : Y = sinc (X)
     Compute the sinc function.

     Return sin (pi*x) / (pi*x).

 -- : B = unwrap (X)
 -- : B = unwrap (X, TOL)
 -- : B = unwrap (X, TOL, DIM)
     Unwrap radian phases by adding or subtracting 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.

     ‘unwrap’ ignores all non-finite input values (Inf, NaN, NA).

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

 -- : Y = arch_rnd (A, B, T)
     Simulate an ARCH sequence of length T with AR coefficients B and CH
     coefficients A.

     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

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

 -- : X = arma_rnd (A, B, V, T, N)
     Return a simulation of the ARMA model.

     The ARMA model is defined by

          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.

 -- : X = 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.

     In other words, 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.

 -- : C = 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’.

 -- : C = blackman (M)
 -- : C = blackman (M, "periodic")
 -- : C = blackman (M, "symmetric")
     Return the filter coefficients of a Blackman window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

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

 -- : Y = 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 P 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: XREFpolyfit.

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

 -- : [NEWPHI, NEWV] = 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.

 -- : Y = fftshift (X)
 -- : Y = fftshift (X, DIM)
     Perform a shift of the vector X, for use with the ‘fft’ and ‘ifft’
     functions, in order to 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 by dt, then ‘fftshift (fft (X))’ corresponds to frequencies

          f = [ -(ceil((N-1)/2):-1:1), 0, (1:floor((N-1)/2)) ] * df

     where df = 1 / (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.

     See also: *note ifftshift: XREFifftshift.

 -- : X = ifftshift (Y)
 -- : X = ifftshift (Y, DIM)
     Undo the action of the ‘fftshift’ function.

     For even length X, ‘fftshift’ is its own inverse, but odd lengths
     differ slightly.

     See also: *note fftshift: XREFfftshift.

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

 -- : C = hamming (M)
 -- : C = hamming (M, "periodic")
 -- : C = hamming (M, "symmetric")
     Return the filter coefficients of a Hamming window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

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

 -- : C = hanning (M)
 -- : C = hanning (M, "periodic")
 -- : C = hanning (M, "symmetric")
     Return the filter coefficients of a Hanning window of length M.

     If the optional argument "periodic" is given, the periodic form of
     the window is returned.  This is equivalent to the window of length
     M+1 with the last coefficient removed.  The optional argument
     "symmetric" is equivalent to not specifying a second argument.

     For a definition of the Hanning window see, e.g., A.V. Oppenheim &
     R. W. Schafer, ‘Discrete-Time Signal Processing’.

 -- : H = 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 column.

 -- : PP = pchip (X, Y)
 -- : YI = pchip (X, Y, XI)
     Return the Piecewise Cubic Hermite Interpolating Polynomial (pchip)
     of points X and Y.

     If called with two arguments, return the piecewise polynomial PP
     that may be used with ‘ppval’ to evaluate the polynomial at
     specific points.

     When called with a third input argument, ‘pchip’ evaluates the
     pchip polynomial at the points XI.  The third calling form is
     equivalent to ‘ppval (pchip (X, Y), XI)’.

     The variable X must be a strictly monotonic vector (either
     increasing or decreasing) of length N.

     Y can be either a vector or array.  If Y is a vector then it must
     be the same length N as X.  If Y is an array then the size of Y
     must have the form ‘[S1, S2, ..., SK, N]’ The array is reshaped
     internally to a matrix where the leading dimension is given by ‘S1
     * S2 * ... * SK’ and each row of this matrix is then treated
     separately.  Note that this is exactly opposite to ‘interp1’ but is
     done for MATLAB compatibility.

     See also: *note spline: XREFspline, *note ppval: XREFppval, *note
     mkpp: XREFmkpp, *note unmkpp: XREFunmkpp.

 -- : [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 (..., "RANGE")
 -- : periodogram (...)
     Return the periodogram (Power Spectral Density) of X.

     The possible inputs are:

     X

          data vector.  If X is real-valued a one-sided spectrum is
          estimated.  If X is complex-valued, or "RANGE" specifies
          "twosided", the full spectrum is estimated.

     WIN
          window weight data.  If window is empty or unspecified a
          default rectangular window is used.  Otherwise, the window is
          applied to the signal (‘X .* WIN’) before computing the
          periodogram.  The window data must be a vector of the same
          length as X.

     NFFT
          number of frequency bins.  The default is 256 or the next
          higher power of 2 greater than the length of X (‘max (256,
          2.^nextpow2 (length (x)))’).  If NFFT is greater than the
          length of the input then X will be zero-padded to the length
          of NFFT.

     FS
          sampling rate.  The default is 1.

     RANGE
          range of spectrum.  "onesided" computes spectrum from
          [0:nfft/2+1].  "twosided" computes spectrum from [0:nfft-1].

     The optional second output W are the normalized angular
     frequencies.  For a one-sided calculation W is in the range [0, pi]
     if NFFT is even and [0, pi) if NFFT is odd.  Similarly, for a
     two-sided calculation W is in the range [0, 2*pi] or [0, 2*pi)
     depending on NFFT.

     If a sampling frequency is specified, FS, then the output
     frequencies F will be in the range [0, FS/2] or [0, FS/2) for
     one-sided calculations.  For two-sided calculations the range will
     be [0, FS).

     When called with no outputs the periodogram is immediately plotted
     in the current figure window.

     See also: *note fft: XREFfft.

 -- : Y = sinetone (FREQ, RATE, SEC, AMPL)
     Return a sinetone of frequency FREQ with a length of SEC seconds at
     sampling rate RATE and with amplitude AMPL.

     The arguments FREQ and AMPL may be vectors of common size.

     The defaults are RATE = 8000, SEC = 1, and AMPL = 64.

     See also: *note sinewave: XREFsinewave.

 -- : Y = 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.

     See also: *note sinetone: XREFsinetone.

 -- : SDE = spectral_adf (C)
 -- : SDE = spectral_adf (C, WIN)
 -- : SDE = 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_lw’.

     If WIN is omitted, the triangle window is used.

     If B is omitted, ‘1 / sqrt (length (X))’ is used.

     See also: *note spectral_xdf: XREFspectral_xdf.

 -- : SDE = spectral_xdf (X)
 -- : SDE = spectral_xdf (X, WIN)
 -- : SDE = 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.

     See also: *note spectral_adf: XREFspectral_adf.

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

 -- : Y = stft (X)
 -- : Y = stft (X, WIN_SIZE)
 -- : Y = stft (X, WIN_SIZE, INC)
 -- : Y = stft (X, WIN_SIZE, INC, NUM_COEF)
 -- : Y = stft (X, WIN_SIZE, INC, NUM_COEF, WIN_TYPE)
 -- : [Y, C] = stft (...)
     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.

     The following defaults are used for unspecified arguments: 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.

     See also: *note synthesis: XREFsynthesis.

 -- : X = 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 , ...)

     See also: *note stft: XREFstft.

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

32 Image Processing
*******************

Since an image is basically 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

32.1 Loading and Saving Images
==============================

The first step in most image processing tasks is to load an image into
Octave which is done with the ‘imread’ function.  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 (J, "my_output_image.img");

 -- : [IMG, MAP, ALPHA] = imread (FILENAME)
 -- : [...] = imread (URL)
 -- : [...] = imread (..., EXT)
 -- : [...] = imread (..., IDX)
 -- : [...] = imread (..., PARAM1, VALUE1, ...)
     Read images from various file formats.

     Read an image as a matrix from the file FILENAME or from the online
     resource URL.  If neither is given, but EXT was specified, look for
     a file with the extension EXT.

     The size and class of the output depends on the format of the
     image.  A color image is returned as an MxNx3 matrix.  Grayscale
     and black-and-white images are of size MxN.  Multipage images will
     have an additional 4th dimension.

     The bit depth of the image determines the class of the output:
     "uint8", "uint16", or "single" for grayscale and color, and
     "logical" for black-and-white.  Note that indexed images always
     return the indexes for a colormap, independent of whether MAP is a
     requested output.  To obtain the actual RGB image, use ‘ind2rgb’.
     When more than one indexed image is being read, MAP is obtained
     from the first.  In some rare cases this may be incorrect and
     ‘imfinfo’ can be used to obtain the colormap of each image.

     See the Octave manual for more information in representing images.
     (*note Representing Images::)

     Some file formats, such as TIFF and GIF, are able to store multiple
     images in a single file.  IDX can be a scalar or vector specifying
     the index of the images to read.  By default, Octave will read only
     the first page.

     Depending on the file format, it is possible to configure the
     reading of images with PARAMETER, VALUE pairs.  The following
     options are supported:

     "Frames" or "Index"
          This is an alternative method to specify IDX.  When specifying
          it in this way, its value can also be the string "all".

     "Info"
          This option exists for MATLAB compatibility, but has no
          effect.  For maximum performance when reading multiple images
          from a single file, use the "Index" option.

     "PixelRegion"
          Controls the image region that is read.  The value must be a
          cell array with two arrays of 3 elements ‘{[ROWS], [COLS]}’.
          The elements in the array are the start, increment, and end
          pixel to be read.  If the increment value is omitted it
          defaults to 1.  For example, the following are all equivalent:

               imread (filename, "PixelRegion", {[200 600], [300 700]});
               imread (filename, "PixelRegion", {[200 1 600], [300 1 700]});
               imread (filename)(200:600, 300:700);

     See also: *note imwrite: XREFimwrite, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

 -- : imwrite (IMG, FILENAME)
 -- : imwrite (IMG, FILENAME, EXT)
 -- : imwrite (IMG, MAP, FILENAME)
 -- : imwrite (..., PARAM1, VAL1, ...)
     Write images in various file formats.

     The image IMG can be a binary, grayscale, RGB, or multi-dimensional
     image.  The size and class of IMG should be the same as what should
     be expected when reading it with ‘imread’: the 3rd and 4th
     dimensions reserved for color space, and multiple pages
     respectively.  If it's an indexed image, the colormap MAP must also
     be specified.

     If EXT is not supplied, the file extension of FILENAME is used to
     determine the format.  The actual supported formats are dependent
     on options made during the build of Octave.  Use ‘imformats’ to
     check the support of the different image formats.

     Depending on the file format, it is possible to configure the
     writing of images with PARAM, VAL pairs.  The following options are
     supported:

     ‘Alpha’
          Alpha (transparency) channel for the image.  This must be a
          matrix with same class, and number of rows and columns of IMG.
          In case of a multipage image, the size of the 4th dimension
          must also match and the third dimension must be a singleton.
          By default, image will be completely opaque.

     ‘Compression’
          Compression to use one the image.  Can be one of the
          following: "none" (default), "bzip", "fax3", "fax4", "jpeg",
          "lzw", "rle", or "deflate".  Note that not all compression
          types are available for all image formats in which it defaults
          to your Magick library.

     ‘DelayTime’
          For formats that accept animations (such as GIF), controls for
          how long a frame is displayed until it moves to the next one.
          The value must be scalar (which will applied to all frames in
          IMG), or a vector of length equal to the number of frames in
          IM.  The value is in seconds, must be between 0 and 655.35,
          and defaults to 0.5.

     ‘DisposalMethod’
          For formats that accept animations (such as GIF), controls
          what happens to a frame before drawing the next one.  Its
          value can be one of the following strings: "doNotSpecify"
          (default); "leaveInPlace"; "restoreBG"; and "restorePrevious",
          or a cell array of those string with length equal to the
          number of frames in IMG.

     ‘LoopCount’
          For formats that accept animations (such as GIF), controls how
          many times the sequence is repeated.  A value of Inf means an
          infinite loop (default), a value of 0 or 1 that the sequence
          is played only once (loops zero times), while a value of 2 or
          above loops that number of times (looping twice means it plays
          the complete sequence 3 times).  This option is ignored when
          there is only a single image at the end of writing the file.

     ‘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.  Defaults to 75.

     ‘WriteMode’
          Some file formats, such as TIFF and GIF, are able to store
          multiple images in a single file.  This option specifies if
          IMG should be appended to the file (if it exists) or if a new
          file should be created for it (possibly overwriting an
          existing file).  The value should be the string "Overwrite"
          (default), or "Append".

          Despite this option, the most efficient method of writing a
          multipage image is to pass a 4 dimensional IMG to ‘imwrite’,
          the same matrix that could be expected when using ‘imread’
          with the option "Index" set to "all".

     See also: *note imread: XREFimread, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     See also: *note EXEC_PATH: XREFEXEC_PATH, *note OCTAVE_HOME:
     XREFOCTAVE_HOME, *note OCTAVE_EXEC_HOME: XREFOCTAVE_EXEC_HOME.

   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.

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

     ‘imfinfo’ returns a structure containing information about the
     image stored in the file FILENAME.  If there is no file FILENAME,
     and EXT was specified, it will look for a file named FILENAME and
     extension EXT, i.e., a file named FILENAME.EXT.

     The output structure INFO contains the following fields:

     ‘Filename’
          The full name of the image file.

     ‘FileModDate’
          Date of last modification to the file.

     ‘FileSize’
          Number of bytes of the image on disk

     ‘Format’
          Image format (e.g., "jpeg").

     ‘Height’
          Image height in pixels.

     ‘Width’
          Image Width in pixels.

     ‘BitDepth’
          Number of bits per channel per pixel.

     ‘ColorType’
          Image type.  Value is "grayscale", "indexed", "truecolor",
          "CMYK", or "undefined".

     ‘XResolution’
          X resolution of the image.

     ‘YResolution’
          Y resolution of the image.

     ‘ResolutionUnit’
          Units of image resolution.  Value is "Inch", "Centimeter", or
          "undefined".

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

     ‘LoopCount’
          Number of iterations to loop an animation.

     ‘ByteOrder’
          Endian option for formats that support it.  Value is
          "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.

     ‘Quality’
          JPEG/MIFF/PNG compression level.  Value is an integer in the
          range [0 100].

     ‘DisposalMethod’
          Only valid for GIF images, control how successive frames are
          rendered (how the preceding frame is disposed of) when
          creating a GIF animation.  Values can be "doNotSpecify",
          "leaveInPlace", "restoreBG", or "restorePrevious".  For
          non-GIF files, value is an empty string.

     ‘Chromaticities’
          Value is a 1x8 Matrix with the x,y chromaticity values for
          white, red, green, and blue points, in that order.

     ‘Comment’
          Image comment.

     ‘Compression’
          Compression type.  Value can be "none", "bzip", "fax3",
          "fax4", "jpeg", "lzw", "rle", "deflate", "lzma", "jpeg2000",
          "jbig2", "jbig2", or "undefined".

     ‘Colormap’
          Colormap for each image.

     ‘Orientation’
          The orientation of the image with respect to the rows and
          columns.  Value is an integer between 1 and 8 as defined in
          the TIFF 6 specifications, and for MATLAB compatibility.

     ‘Software’
          Name and version of the software or firmware of the camera or
          image input device used to generate the image.

     ‘Make’
          The manufacturer of the recording equipment.  This is the
          manufacture of the DSC, scanner, video digitizer or other
          equipment that generated the image.

     ‘Model’
          The model name or model number of the recording equipment as
          mentioned on the field "Make".

     ‘DateTime’
          The date and time of image creation as defined by the Exif
          standard, i.e., it is the date and time the file was changed.

     ‘ImageDescription’
          The title of the image as defined by the Exif standard.

     ‘Artist’
          Name of the camera owner, photographer or image creator.

     ‘Copyright’
          Copyright notice of the person or organization claiming rights
          to the image.

     ‘DigitalCamera’
          A struct with information retrieved from the Exif tag.

     ‘GPSInfo’
          A struct with geotagging information retrieved from the Exif
          tag.

     See also: *note imread: XREFimread, *note imwrite: XREFimwrite,
     *note imshow: XREFimshow, *note imformats: XREFimformats.

   By default, Octave's image IO functions (‘imread’, ‘imwrite’, and
‘imfinfo’) use the ‘GraphicsMagick’ library for their operations.  This
means a vast number of image formats is supported but considering the
large amount of image formats in science and its commonly closed nature,
it is impossible to have a library capable of reading them all.  Because
of this, the function ‘imformats’ keeps a configurable list of available
formats, their extensions, and what functions should the image IO
functions use.  This allows one to expand Octave's image IO capabilities
by creating functions aimed at acting on specific file formats.

   While it would be possible to call the extra functions directly,
properly configuring Octave with ‘imformats’ allows one to keep a
consistent code that is abstracted from file formats.

   It is important to note that a file format is not actually defined by
its file extension and that ‘GraphicsMagick’ is capable to read and
write more file formats than the ones listed by ‘imformats’.  What this
means is that even with an incorrect or missing extension the image may
still be read correctly, and that even unlisted formats are not
necessarily unsupported.

 -- : imformats ()
 -- : FORMATS = imformats (EXT)
 -- : FORMATS = imformats (FORMAT)
 -- : FORMATS = imformats ("add", FORMAT)
 -- : FORMATS = imformats ("remove", EXT)
 -- : FORMATS = imformats ("update", EXT, FORMAT)
 -- : FORMATS = imformats ("factory")
     Manage supported image formats.

     FORMATS is a structure with information about each supported file
     format, or from a specific format EXT, the value displayed on the
     field EXT.  It contains the following fields:

     ext
          The name of the file format.  This may match the file
          extension but Octave will automatically detect the file
          format.

     description
          A long description of the file format.

     isa
          A function handle to confirm if a file is of the specified
          format.

     write
          A function handle to write if a file is of the specified
          format.

     read
          A function handle to open files the specified format.

     info
          A function handle to obtain image information of the specified
          format.

     alpha
          Logical value if format supports alpha channel (transparency
          or matte).

     multipage
          Logical value if format supports multipage (multiple images
          per file).

     It is possible to change the way Octave manages file formats with
     the options "add", "remove", and "update", and supplying a
     structure FORMAT with the required fields.  The option "factory"
     resets the configuration to the default.

     This can be used by Octave packages to extend the image reading
     capabilities Octave, through use of the PKG_ADD and PKG_DEL
     commands.

     See also: *note imfinfo: XREFimfinfo, *note imread: XREFimread,
     *note imwrite: XREFimwrite.


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

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

 -- : imshow (IM)
 -- : imshow (IM, LIMITS)
 -- : imshow (IM, MAP)
 -- : imshow (RGB, ...)
 -- : imshow (FILENAME)
 -- : imshow (..., STRING_PARAM1, VALUE1, ...)
 -- : H = imshow (...)
     Display the image IM, where IM can be a 2-dimensional (grayscale
     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 filename 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.

     "colormap"
          VALUE1 is the colormap to use when displaying an indexed
          image.

     "xdata"
          If VALUE1 is a 2-element vector, it must contain horizontal
          image limits in the form [xfirst, xlast], where xfirst and
          xlast are the abscissa of the centers of the corner pixels.
          Otherwise VALUE1 must be a vector and only the first and last
          elements will be used for xfirst and xlast respectively.

     "ydata"
          If VALUE1 is a 2-element vector, it must contain vertical
          image limits in the form [yfirst, ylast], where yfirst and
          ylast are the ordinates of the center of the corner pixels.
          Otherwise VALUE1 must be a vector and only the first and last
          elements will be used for yfirst and ylast respectively.

     The optional return value H is a graphics handle to the image.

     See also: *note image: XREFimage, *note imagesc: XREFimagesc, *note
     colormap: XREFcolormap, *note gray2ind: XREFgray2ind, *note
     rgb2ind: XREFrgb2ind.

 -- : image (IMG)
 -- : image (X, Y, IMG)
 -- : image (..., "PROP", VAL, ...)
 -- : image ("PROP1", VAL1, ...)
 -- : H = image (...)
     Display a matrix as an indexed color image.

     The elements of IMG are indices into the current colormap.

     X and Y are optional 2-element vectors, ‘[min, max]’, which specify
     the coordinates of the centers of the corner pixels.  If a range is
     specified as ‘[max, min]’ then the image will be reversed along
     that axis.  For convenience, X and Y may be specified as N-element
     vectors matching the length of the data in IMG.  However, only the
     first and last elements will be used to determine the axis limits.

     Multiple property/value pairs may be specified for the image
     object, but they must appear in pairs.

     The optional return value H is a graphics handle to the image.

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

     Calling Forms: The ‘image’ function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls ‘newplot’ to prepare the
     graphic figure and axes.  When the only inputs to ‘image’ are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.

     Graphic Properties: The full list of properties is documented at
     *note Image Properties::.

     See also: *note imshow: XREFimshow, *note imagesc: XREFimagesc,
     *note colormap: XREFcolormap.

 -- : imagesc (IMG)
 -- : imagesc (X, Y, IMG)
 -- : imagesc (..., CLIMITS)
 -- : imagesc (..., "PROP", VAL, ...)
 -- : imagesc ("PROP1", VAL1, ...)
 -- : imagesc (HAX, ...)
 -- : H = imagesc (...)
     Display a scaled version of the matrix IMG as a color image.

     The colormap is scaled so that the entries of the matrix occupy the
     entire colormap.  If ‘CLIMITS = [LO, HI]’ is given, then that range
     is set to the "clim" of the current axes.

     X and Y are optional 2-element vectors, ‘[min, max]’, which specify
     the coordinates of the centers of the corner pixels.  If a range is
     specified as ‘[max, min]’ then the image will be reversed along
     that axis.  For convenience, X and Y may be specified as N-element
     vectors matching the length of the data in IMG.  However, only the
     first and last elements will be used to determine the image limits.

     The optional return value H is a graphics handle to the image.

     Calling Forms: The ‘imagesc’ function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls ‘newplot’ to prepare the
     graphic figure and axes.  When the only inputs to ‘image’ are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.
     The full list of properties is documented at *note Image
     Properties::.

     See also: *note image: XREFimage, *note imshow: XREFimshow, *note
     caxis: XREFcaxis.


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

32.3 Representing Images
========================

In general Octave supports four different kinds of images, grayscale
images, RGB images, binary images, and indexed images.  A grayscale
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 grayscale 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.

   The following convenience functions are available for conversion
between image formats.

 -- : DIMG = im2double (IMG)
 -- : DIMG = im2double (IMG, "indexed")
     Convert image to double precision.

     The conversion of IMG to double precision, is dependent on the type
     of input image.  The following input classes are supported:

     ‘uint8, uint16, and int16’
          The range of values from the class is scaled to the interval
          [0 1].

     ‘logical’
          True and false values are assigned a value of 1 and 0
          respectively.

     ‘single’
          Values are cast to double.

     ‘double’
          Returns the same image.

     If IMG is an indexed image, then the second argument should be the
     string "indexed".  If so, then IMG must either be of floating point
     class, or unsigned integer class and it will simply be cast to
     double.  If it is an integer class, an offset of +1 is applied.

     See also: *note double: XREFdouble.

 -- : IMG = gray2ind (I)
 -- : IMG = gray2ind (I, N)
 -- : IMG = gray2ind (BW)
 -- : IMG = gray2ind (BW, N)
 -- : [IMG, MAP] = gray2ind (...)
     Convert a grayscale or binary intensity image to an indexed image.

     The indexed image will consist of N different intensity values.  If
     not given N defaults to 64 for grayscale images or 2 for binary
     black and white images.

     The output IMG is of class uint8 if N is less than or equal to 256;
     Otherwise the return class is uint16.

     See also: *note ind2gray: XREFind2gray, *note rgb2ind: XREFrgb2ind.

 -- : I = ind2gray (X, MAP)
     Convert a color indexed image to a grayscale intensity image.

     The image X must be an indexed image which will be converted using
     the colormap MAP.  If MAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map before conversion to grayscale.

     The output I is of the same class as the input X and may be one of
     ‘uint8’, ‘uint16’, ‘single’, or ‘double’.

     Implementation Note: There are several ways of converting colors to
     grayscale intensities.  This functions uses the luminance value
     obtained from ‘rgb2gray’ which is ‘I = 0.299*R + 0.587*G +
     0.114*B’.  Other possibilities include the value component from
     ‘rgb2hsv’ or using a single color channel from ‘ind2rgb’.

     See also: *note gray2ind: XREFgray2ind, *note ind2rgb: XREFind2rgb.

 -- : [X, MAP] = rgb2ind (RGB)
 -- : [X, MAP] = rgb2ind (R, G, B)
     Convert an image in red-green-blue (RGB) color space to an indexed
     image.

     The input image RGB can be specified as a single matrix of size
     MxNx3, or as three separate variables, R, G, and B, its three color
     channels, red, green, and blue.

     It outputs an indexed image X and a colormap MAP to interpret an
     image exactly the same as the input.  No dithering or other form of
     color quantization is performed.  The output class of the indexed
     image X can be uint8, uint16 or double, whichever is required to
     specify the number of unique colors in the image (which will be
     equal to the number of rows in MAP) in order.

     Multi-dimensional indexed images (of size MxNx3xK) are also
     supported, both via a single input (RGB) or its three color
     channels as separate variables.

     See also: *note ind2rgb: XREFind2rgb, *note rgb2hsv: XREFrgb2hsv,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB = ind2rgb (X, MAP)
 -- : [R, G, B] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.

     The image X must be an indexed image which will be converted using
     the colormap MAP.  If MAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map.

     The output may be a single RGB image (MxNx3 matrix where M and N
     are the original image X dimensions, one for each of the red, green
     and blue channels).  Alternatively, the individual red, green, and
     blue color matrices of size MxN may be returned.

     Multi-dimensional indexed images (of size MxNx1xK) are also
     supported.

     See also: *note rgb2ind: XREFrgb2ind, *note ind2gray: XREFind2gray,
     *note hsv2rgb: XREFhsv2rgb.

   Octave also provides tools to produce and work with movie frame
structures.  Those structures encapsulate the image data ("cdata" field)
together with the corresponding colormap ("colormap" field).

 -- : FRAME = getframe ()
 -- : FRAME = getframe (HAX)
 -- : FRAME = getframe (HFIG)
 -- : FRAME = getframe (..., RECT)

     Capture a figure or axes as a movie frame structure.

     Without an argument, capture the current axes excluding ticklabels,
     title, and x/y/zlabels.  The returned structure FRAME has a field
     ‘cdata’, which contains the actual image data in the form of an
     NxMx3 (RGB) uint8 matrix in physical screen pixels, and a field
     ‘colormap’ which is provided for MATLAB compatibility but is always
     empty.

     If the first argument HAX is an axes handle, then capture this
     axes, rather than the current axes returned by ‘gca’.

     If the first argument HFIG is a figure handle then the entire
     corresponding figure canvas is captured.

     Finally, if a second argument RECT is provided it must be a
     four-element vector ([left bottom width height]) defining the
     region inside the figure to be captured.  Regardless of the figure
     "units" property, RECT must be defined in *pixels*.

     See also: *note im2frame: XREFim2frame, *note frame2im:
     XREFframe2im, *note movie: XREFmovie.

 -- : movie (MOV)
 -- : movie (MOV, N)
 -- : movie (MOV, N, FPS)
 -- : movie (H, ...)
     Play a movie defined by an array of frame structures.

     The movie MOV must be a struct array of frames with fields "cdata"
     and "colormap", as returned by the ‘getframe’ function.  By default
     all images are displayed once, at 12 fps, in the current axes.

     The optional argument N is a scalar or vector of integers that
     controls the number of times the movie is displayed and which
     particular frames are shown:

     First element:

          N(1) > 0
               Play the movie N(1) times.

          N(1) < 0
               Play the movie ‘abs (N(1)’ times alternatively in forward
               and backward order.

     Other elements (if any):
          Indices of the frames in MOV that will be displayed.

     If the first argument is a handle to a figure or axes H, the movie
     is played in that figure or axes instead of the current axes.

     See also: *note getframe: XREFgetframe, *note im2frame:
     XREFim2frame, *note frame2im: XREFframe2im.

 -- : [X, MAP] = frame2im (FRAME)
     Convert movie frame to indexed image.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images or movies is given when FRAME is a
     struct array.  In such cases, X will be a MxNx1xK or MxNx3xK for
     indexed and RGB movies respectively, with each frame concatenated
     along the 4th dimension.

     See also: *note im2frame: XREFim2frame, *note getframe:
     XREFgetframe.

 -- : FRAME = im2frame (RGB)
 -- : FRAME = im2frame (X, MAP)
     Convert image to movie frame.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images is given when each image
     projection, matrix sizes of MxN and MxNx3 for RGB images, is
     concatenated along the fourth dimension.  In such cases, the
     returned value is a struct array.

     See also: *note frame2im: XREFframe2im.

   The ‘colormap’ function is used to change the colormap of the current
axes or figure.

 -- : CMAP = colormap ()
 -- : CMAP = colormap (MAP)
 -- : CMAP = colormap ("default")
 -- : CMAP = colormap (MAP_NAME)
 -- : CMAP = colormap (HAX, ...)
 -- : colormap MAP_NAME
     Query or set the current colormap.

     With no input arguments, ‘colormap’ returns the current color map.

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

     ‘colormap ("default")’ restores the default colormap (the ‘viridis’
     map with 64 entries).  The default colormap is returned.

     The map may also be specified by a string, MAP_NAME, which is the
     name of a function that returns a colormap.

     If the first argument HAX is an axes handle, then the colormap for
     those axes is queried or set.

     For convenience, it is also possible to use this function with the
     command form, ‘colormap MAP_NAME’.

     The list of built-in colormaps is:

     Map         Description
     --------------------------------------------------------------------------
     viridis     default
     turbo       colormap traversing blue, cyan, green, yellow, red; modern
                 replacement for jet.
     jet         colormap traversing blue, cyan, green, yellow, red.
     cubehelix   colormap traversing black, blue, green, red, white with
                 increasing intensity.
     hsv         cyclic colormap traversing Hue, Saturation, Value space.
     rainbow     colormap traversing red, yellow, blue, green, violet.
     ---------   --------------------------------------------------------------
     hot         colormap traversing black, red, orange, yellow, white.
     cool        colormap traversing cyan, purple, magenta.
     spring      colormap traversing magenta to yellow.
     summer      colormap traversing green to yellow.
     autumn      colormap traversing red, orange, yellow.
     winter      colormap traversing blue to green.
     ---------   --------------------------------------------------------------
     gray        colormap traversing black to white in shades of gray.
     bone        colormap traversing black, gray-blue, white.
     copper      colormap traversing black to light copper.
     pink        colormap traversing black, gray-pink, white.
     ocean       colormap traversing black, dark-blue, white.
     ---------   --------------------------------------------------------------
     colorcube   equally spaced colors in RGB color space.
     flag        cyclic 4-color map of red, white, blue, black.
     lines       cyclic colormap with colors from axes "ColorOrder"
                 property.
     prism       cyclic 6-color map of red, orange, yellow, green, blue,
                 violet.
     ---------   --------------------------------------------------------------
     white       all white colormap (no colors).

     See also: *note viridis: XREFviridis, *note turbo: XREFturbo, *note
     jet: XREFjet, *note cubehelix: XREFcubehelix, *note hsv: XREFhsv,
     *note rainbow: XREFrainbow, *note hot: XREFhot, *note cool:
     XREFcool, *note spring: XREFspring, *note summer: XREFsummer, *note
     autumn: XREFautumn, *note winter: XREFwinter, *note gray: XREFgray,
     *note bone: XREFbone, *note copper: XREFcopper, *note pink:
     XREFpink, *note ocean: XREFocean, *note colorcube: XREFcolorcube,
     *note flag: XREFflag, *note lines: XREFlines, *note prism:
     XREFprism, *note white: XREFwhite.

 -- : TF = iscolormap (CMAP)
     Return true if CMAP is a colormap.

     A colormap is a real matrix, of class single or double, with 3
     columns.  Each row represents a single color.  The 3 columns
     contain red, green, and blue intensities respectively.

     All values in a colormap should be in the [0 1] range but this is
     not enforced.  Each function must decide what to do for values
     outside this range.

     See also: *note colormap: XREFcolormap, *note rgbplot: XREFrgbplot.

   The following functions return predefined colormaps, the same that
can be requested by name using the ‘colormap’ function.

 -- : rgbplot (CMAP)
 -- : rgbplot (CMAP, STYLE)
 -- : H = rgbplot (...)
     Plot the components of a colormap.

     Two different STYLEs are available for displaying the CMAP:

     profile (default)
          Plot the RGB line profile of the colormap for each of the
          channels (red, green and blue) with the plot lines colored
          appropriately.  Each line represents the intensity of an RGB
          component across the colormap.

     composite
          Draw the colormap across the X-axis so that the actual index
          colors are visible rather than the individual color
          components.

     The optional return value H is a graphics handle to the created
     plot.

     Run ‘demo rgbplot’ to see an example of ‘rgbplot’ and each style
     option.

     See also: *note colormap: XREFcolormap.

 -- : MAP = autumn ()
 -- : 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: XREFcolormap.

 -- : MAP = bone ()
 -- : 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: XREFcolormap.

 -- : MAP = colorcube ()
 -- : MAP = colorcube (N)
     Create color colormap.  This colormap is composed of as many
     equally spaced colors (not grays) in the RGB color space as
     possible.

     If there are not a perfect number N of regularly spaced colors then
     the remaining entries in the colormap are gradients of pure red,
     green, blue, and gray.

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

     See also: *note colormap: XREFcolormap.

 -- : MAP = cool ()
 -- : 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: XREFcolormap.

 -- : MAP = copper ()
 -- : 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: XREFcolormap.

 -- : MAP = cubehelix ()
 -- : MAP = cubehelix (N)
 -- : MAP = cubehelix (N, START, ROTS, HUE, GAMMA)
     Create cubehelix colormap.

     This colormap varies from black to white going though blue, green,
     and red tones while maintaining a monotonically increasing
     perception of intensity.  This is achieved by traversing a color
     cube from black to white through a helix, hence the name cubehelix,
     while taking into account the perceived brightness of each channel
     according to the NTSC specifications from 1953.

          rgbplot (cubehelix (256))

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

     Reference: Green, D. A., 2011, ‘A colour scheme for the display of
     astronomical intensity images’, Bulletin of the Astronomical
     Society of India, 39, 289.

     See also: *note colormap: XREFcolormap.

 -- : MAP = flag ()
 -- : 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: XREFcolormap.

 -- : MAP = gray ()
 -- : 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.

     See also: *note colormap: XREFcolormap.

 -- : MAP = hot ()
 -- : 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: XREFcolormap.

 -- : MAP = hsv ()
 -- : MAP = 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.  The map is
     obtained by linearly varying the hue through all possible values
     while keeping constant maximum saturation and value.  The
     equivalent code is ‘hsv2rgb ([(0:N-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: XREFcolormap.

 -- : MAP = jet ()
 -- : 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.

     Programming Note: The ‘jet’ colormap is not perceptually uniform.
     Try the ‘viridis’ colormap if that is important.  For a drop-in
     replacement for ‘jet’ with better perceptual characteristics try
     the ‘turbo’ colormap.

     See also: *note colormap: XREFcolormap, *note turbo: XREFturbo.

 -- : MAP = lines ()
 -- : MAP = lines (N)
     Create color colormap.  This colormap is composed of the list of
     colors in the current axes "ColorOrder" property.  The default is
     blue, orange, yellow, purple, green, light blue, and 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: XREFcolormap.

 -- : MAP = ocean ()
 -- : 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.

     See also: *note colormap: XREFcolormap.

 -- : MAP = pink ()
 -- : MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.

     This colormap 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: XREFcolormap.

 -- : MAP = prism ()
 -- : 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: XREFcolormap.

 -- : MAP = rainbow ()
 -- : 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: XREFcolormap.

 -- : MAP = spring ()
 -- : 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: XREFcolormap.

 -- : MAP = summer ()
 -- : 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: XREFcolormap.

 -- : MAP = turbo ()
 -- : MAP = turbo (N)
     Create color colormap.  This colormap ranges from dark blue through
     green to dark red; similar to the outdated ‘jet’ colormap but
     perceptually uniform.

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

     See also: *note colormap: XREFcolormap.

 -- : MAP = viridis ()
 -- : MAP = viridis (N)
     Create color colormap.  This colormap ranges from dark
     purplish-blue through blue, 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: XREFcolormap.

 -- : MAP = white ()
 -- : MAP = white (N)
     Create color colormap.  This colormap is completely white.

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

     See also: *note colormap: XREFcolormap.

 -- : MAP = winter ()
 -- : 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: XREFcolormap.

 -- : CMAP = contrast (X)
 -- : CMAP = 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.

     See also: *note colormap: XREFcolormap, *note brighten:
     XREFbrighten.

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

 -- : MAP_OUT = brighten (BETA)
 -- : MAP_OUT = brighten (MAP, BETA)
 -- : MAP_OUT = brighten (H, BETA)
 -- : brighten (...)
     Brighten or darken a colormap.

     The argument BETA must be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the 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.

     If no output is specified then the result is written to the current
     colormap.

     See also: *note colormap: XREFcolormap, *note contrast:
     XREFcontrast.

 -- : spinmap ()
 -- : spinmap (T)
 -- : spinmap (T, INC)
 -- : spinmap ("inf")
     Cycle the colormap for T seconds with a color increment of INC.

     Both parameters are optional.  The default cycle time is 5 seconds
     and the default increment is 2.  If the option "inf" is given then
     cycle continuously until ‘Control-C’ is pressed.

     When rotating, the original color 1 becomes color 2, color 2
     becomes color 3, etc.  A positive or negative increment is allowed
     and a higher value of INC will cause faster cycling through the
     colormap.

     See also: *note colormap: XREFcolormap.

 -- : whitebg ()
 -- : whitebg (COLOR)
 -- : whitebg ("none")
 -- : whitebg (HFIG)
 -- : whitebg (HFIG, COLOR)
 -- : whitebg (HFIG, "none")
     Invert the colors in the current color scheme.

     The root properties are also inverted such that all subsequent
     plots will use the new color scheme.

     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 factory
     default colors.

     If the first argument HFIG is a figure handle or list of figure
     handles, then operate on these figures rather than the current
     figure returned by ‘gcf’.  The root properties will not be changed
     unless 0 is in the list of figures.

     Programming Note: ‘whitebg’ operates by changing the color
     properties of the children of the specified figures.  Only objects
     with a single color are affected.  For example, a patch with a
     single "FaceColor" will be changed, but a patch with shading
     ("interp") will not be modified.  For inversion, the new color is
     simply the inversion in RGB space: ‘CNEW = [1-R 1-G 1-B]’.  When a
     color is specified, the axes and figure are set to the new color,
     and the color of child objects are then adjusted to have some
     contrast (visibility) against the new background.

     See also: *note reset: XREFreset, *note get: XREFget, *note set:
     XREFset.

   The following functions can be used to manipulate colormaps.

 -- : [Y, NEWMAP] = cmunique (X, MAP)
 -- : [Y, NEWMAP] = cmunique (RGB)
 -- : [Y, NEWMAP] = cmunique (I)
     Convert an input image X to an output indexed image Y which uses
     the smallest colormap possible NEWMAP.

     When the input is an indexed image (X with colormap MAP) the output
     is a colormap NEWMAP from which any repeated rows have been
     eliminated.  The output image, Y, is the original input image with
     the indices adjusted to match the new, possibly smaller, colormap.

     When the input is an RGB image (an MxNx3 array), the output
     colormap will contain one entry for every unique color in the
     original image.  In the worst case the new map could have as many
     rows as the number of pixels in the original image.

     When the input is a grayscale image I, the output colormap will
     contain one entry for every unique intensity value in the original
     image.  In the worst case the new map could have as many rows as
     the number of pixels in the original image.

     Implementation Details:

     NEWMAP is always an Mx3 matrix, even if the input image is an
     intensity grayscale image I (all three RGB planes are assigned the
     same value).

     The output image is of class uint8 if the size of the new colormap
     is less than or equal to 256.  Otherwise, the output image is of
     class double.

     See also: *note rgb2ind: XREFrgb2ind, *note gray2ind: XREFgray2ind.

 -- : [Y, NEWMAP] = cmpermute (X, MAP)
 -- : [Y, NEWMAP] = cmpermute (X, MAP, INDEX)
     Reorder colors in a colormap.

     When called with only two arguments, ‘cmpermute’ randomly
     rearranges the colormap MAP and returns a new colormap NEWMAP.  It
     also returns the indexed image Y which is the equivalent of the
     original input image X when displayed using NEWMAP.

     When called with an optional third argument the order of colors in
     the new colormap is defined by INDEX.

     *Caution:* INDEX should not have repeated elements or the function
     will fail.


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

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

32.5 Color Conversion
=====================

Octave supports conversion from the RGB color system to the HSV color
system and vice versa.  It is also possible to convert from a color RGB
image to a grayscale image.

 -- : HSV_MAP = rgb2hsv (RGB_MAP)
 -- : HSV_IMG = rgb2hsv (RGB_IMG)
     Transform a colormap or image from RGB to HSV color space.

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

     A color in HSV space is represented by hue, saturation and value
     (brightness) levels in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     Output class and size will be the same as input.

     See also: *note hsv2rgb: XREFhsv2rgb, *note rgb2ind: XREFrgb2ind,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB_MAP = hsv2rgb (HSV_MAP)
 -- : RGB_IMG = hsv2rgb (HSV_IMG)
     Transform a colormap or image from HSV to RGB color space.

     A color in HSV space is represented by hue, saturation and value
     (brightness) levels in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     The input can be both a colormap or RGB image.  In the case of
     floating point input, values are expected to be on the [0 1] range.
     In the case of hue (azimuth), since the value corresponds to an
     angle, ‘mod (h, 1)’ is used.

          >> hsv2rgb ([0.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([2.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([3.5 1 1])
          ⇒ ans = 0 1 1

     Output class and size will be the same as input.

     See also: *note rgb2hsv: XREFrgb2hsv, *note ind2rgb: XREFind2rgb.

 -- : I = rgb2gray (RGB_IMG)
 -- : GRAY_MAP = rgb2gray (RGB_MAP)
     Transform an image or colormap from red-green-blue (RGB) color
     space to a grayscale intensity image.

     The input may be of class uint8, int8, uint16, int16, single, or
     double.  The output is of the same class as the input.

     Implementation Note: The grayscale intensity is calculated as

          I = 0.298936*R + 0.587043*G + 0.114021*B

     which corresponds to the luminance channel when RGB is translated
     to YIQ as documented in <https://en.wikipedia.org/wiki/YIQ>.

     See also: *note rgb2hsv: XREFrgb2hsv, *note rgb2ind: XREFrgb2ind.


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

33 Audio Processing
*******************

* Menu:

* Audio File Utilities::
* Audio Device Information::
* Audio Player::
* Audio Recorder::
* Audio Data Processing::


File: octave.info,  Node: Audio File Utilities,  Next: Audio Device Information,  Up: Audio Processing

33.1 Audio File Utilities
=========================

The following functions allow you to read, write and retrieve
information about audio files.  Various formats are supported including
wav, flac and ogg vorbis.

 -- : INFO = audioinfo (FILENAME)
     Return information about an audio file specified by FILENAME.

     The output INFO is a structure containing the following fields:

     ‘Filename’
          Name of the audio file.

     ‘CompressionMethod’
          Audio compression method.  Unused, only present for
          compatibility with MATLAB.

     ‘NumChannels’
          Number of audio channels.

     ‘SampleRate’
          Sample rate of the audio, in Hertz.

     ‘TotalSamples’
          Number of samples in the file.

     ‘Duration’
          Duration of the audio, in seconds.

     ‘BitsPerSample’
          Number of bits per sample.

     ‘BitRate’
          Audio bit rate.  Unused, only present for compatibility with
          MATLAB.

     ‘Title’
          "Title" audio metadata value as a string, or empty if not
          present.

     ‘Artist’
          "Artist" audio metadata value as a string, or empty if not
          present.

     ‘Comment’
          "Comment" audio metadata value as a string, or empty if not
          present.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.

 -- : [Y, FS] = audioread (FILENAME)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES)

 -- : [Y, FS] = audioread (FILENAME, DATATYPE)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES, DATATYPE)
     Read the audio file FILENAME and return the audio data Y and
     sampling rate FS.

     The audio data is stored as matrix with rows corresponding to audio
     frames and columns corresponding to channels.

     The optional two-element vector argument SAMPLES specifies starting
     and ending frames.

     The optional argument DATATYPE specifies the datatype to return.
     If it is "native", then the type of data depends on how the data is
     stored in the audio file.

     See also: *note audiowrite: XREFaudiowrite, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audiowrite (FILENAME, Y, FS)
 -- : audiowrite (FILENAME, Y, FS, NAME, VALUE, ...)

     Write audio data from the matrix Y to FILENAME at sampling rate FS
     with the file format determined by the file extension.

     Additional name/value argument pairs may be used to specify the
     following options:

     ‘BitsPerSample’
          Number of bits per sample.  Valid values are 8, 16, 24, and
          32.  Default is 16.

     ‘BitRate’
          Valid argument name, but ignored.  Left for compatibility with
          MATLAB.

     ‘Quality’
          Quality setting for the Ogg Vorbis compressor.  Values can
          range between 0 and 100 with 100 being the highest quality
          setting.  Default is 75.

     ‘Title’
          Title for the audio file.

     ‘Artist’
          Artist name.

     ‘Comment’
          Comment.

     See also: *note audioread: XREFaudioread, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audioformats ()
 -- : audioformats (FORMAT)
     Display information about all supported audio formats.

     If the optional argument FORMAT is given, then display only formats
     with names that start with FORMAT.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.


File: octave.info,  Node: Audio Device Information,  Next: Audio Player,  Prev: Audio File Utilities,  Up: Audio Processing

33.2 Audio Device Information
=============================

 -- : DEVINFO = audiodevinfo ()

 -- : DEVS = audiodevinfo (IO)
 -- : NAME = audiodevinfo (IO, ID)
 -- : ID = audiodevinfo (IO, NAME)
 -- : DRIVERVERSION = audiodevinfo (IO, ID, "DriverVersion")
 -- : ID = audiodevinfo (IO, RATE, BITS, CHANS)
 -- : SUPPORTS = audiodevinfo (IO, ID, RATE, BITS, CHANS)

     Return a structure describing the available audio input and output
     devices.

     The DEVINFO structure has two fields "input" and "output".  The
     value of each field is a structure array with fields "Name",
     "DriverVersion" and "ID" describing an audio device.

     If the optional argument IO is 1, return information about input
     devices only.  If it is 0, return information about output devices
     only.  If IO is the only argument supplied, return the number of
     input or output devices available.

     If the optional argument ID is provided, return information about
     the corresponding device.

     If the optional argument NAME is provided, return the ID of the
     named device.

     If the optional argument "DriverVersion" is given, return the name
     of the driver for the specified device.

     Given a sampling rate, bits per sample, and number of channels for
     an input or output device, return the ID of the first device that
     supports playback or recording using the specified parameters.

     If also given a device ID, return true if the device supports
     playback or recording using those parameters.


File: octave.info,  Node: Audio Player,  Next: Audio Recorder,  Prev: Audio Device Information,  Up: Audio Processing

33.3 Audio Player
=================

The following methods are used to create and use audioplayer objects.
These objects can be used to play back audio data stored in Octave
matrices and arrays.  The audioplayer object supports playback from
various devices available to the system, blocking and non-blocking
playback, convenient pausing and resuming and much more.

 -- : PLAYER = audioplayer (Y, FS)
 -- : PLAYER = audioplayer (Y, FS, NBITS)
 -- : PLAYER = audioplayer (Y, FS, NBITS, ID)
 -- : PLAYER = audioplayer (RECORDER)
 -- : PLAYER = audioplayer (RECORDER, ID)
     Create an audioplayer object that will play back data Y at sample
     rate FS.

     The signal Y can be a vector (mono audio) or a two-dimensional
     array (multi-channel audio).

     The optional arguments NBITS and ID specify the number of bits per
     sample and player device ID, respectively.  Device IDs may be found
     using the ‘audiodevinfo’ function.

     Given an audiorecorder object RECORDER, use the data from the
     object to initialize the player.

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

     Method         Description
     ----------------------------------------------------------------------
     get            Read audioplayer property values
     isplaying      Return true if audioplayer is playing
     pause          Pause audioplayer playback
     play           Play audio stored in audioplayer object w/o blocking
     playblocking   Play audio stored in audioplayer object
     resume         Resume playback after pause
     set            Write audioplayer property values
     stop           Stop playback

     Example

     Create an audioplayer object that will play back one second of
     white noise at 44100 sample rate using 8 bits per sample.

          y = 0.25 * randn (2, 44100);
          player = audioplayer (y, 44100, 8);
          play (player);

     See also: *note @audioplayer/get: XREF@audioplayer/get, *note
     @audioplayer/isplaying: XREF@audioplayer/isplaying, *note
     @audioplayer/pause: XREF@audioplayer/pause, *note
     @audioplayer/play: XREF@audioplayer/play, *note
     @audioplayer/playblocking: XREF@audioplayer/playblocking, *note
     @audioplayer/resume: XREF@audioplayer/resume, *note
     @audioplayer/set: XREF@audioplayer/set, *note @audioplayer/stop:
     XREF@audioplayer/stop, *note audiodevinfo: XREFaudiodevinfo, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder,
     *note sound: XREFsound, *note soundsc: XREFsoundsc.

* Menu:

* Playback::
* Player Properties::


File: octave.info,  Node: Playback,  Next: Player Properties,  Up: Audio Player

33.3.1 Playback
---------------

The following methods are used to control player playback.

 -- : play (PLAYER)
 -- : play (PLAYER, START)
 -- : play (PLAYER, [START, END])
     Play audio stored in the audioplayer object PLAYER without
     blocking.

     If the optional argument START is provided, begin playing START
     samples in to the recording.

     If the optional argument END is provided, stop playing at END
     samples into the recording.

     See also: *note @audioplayer/playblocking:
     XREF@audioplayer/playblocking, *note @audioplayer/pause:
     XREF@audioplayer/pause, *note @audioplayer/stop:
     XREF@audioplayer/stop, *note @audioplayer/audioplayer:
     XREF@audioplayer/audioplayer.

 -- : playblocking (PLAYER)
 -- : playblocking (PLAYER, START)
 -- : playblocking (PLAYER, [START, END])
     Play audio stored in the audioplayer object PLAYER with blocking
     (synchronous I/O).

     If the optional argument START is provided, begin playing START
     samples into the recording.

     If the optional argument END is provided, stop playing at END
     samples into the recording.

     See also: *note @audioplayer/play: XREF@audioplayer/play, *note
     @audioplayer/pause: XREF@audioplayer/pause, *note
     @audioplayer/stop: XREF@audioplayer/stop, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.

 -- : pause (PLAYER)
     Pause playback of audioplayer PLAYER.

     See also: *note @audioplayer/resume: XREF@audioplayer/resume, *note
     @audioplayer/stop: XREF@audioplayer/stop, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.

 -- : resume (PLAYER)
     Resume playback for the paused audioplayer object PLAYER.

     See also: *note @audioplayer/pause: XREF@audioplayer/pause, *note
     @audioplayer/stop: XREF@audioplayer/stop, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.

 -- : stop (PLAYER)
     Stop playback of the audioplayer PLAYER and reset relevant
     variables to their initial values.

     See also: *note @audioplayer/pause: XREF@audioplayer/pause, *note
     @audioplayer/resume: XREF@audioplayer/resume, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.

 -- : TF = isplaying (PLAYER)
     Return true if the audioplayer object PLAYER is currently playing
     back audio and false otherwise.

     See also: *note @audioplayer/pause: XREF@audioplayer/pause, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.


File: octave.info,  Node: Player Properties,  Prev: Playback,  Up: Audio Player

33.3.2 Properties
-----------------

The remaining couple of methods are used to get and set various
properties of the audioplayer object.

 -- : VALUE = get (PLAYER, NAME)
 -- : VALUES = get (PLAYER, {NAME1, NAME2, ...})
 -- : VALUES = get (PLAYER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array return the values of the properties
     identified by the elements of the cell array.  Given only the
     player object, return a scalar structure with values for all
     properties of PLAYER.  The field names of the structure correspond
     to the property names.

     See also: *note @audioplayer/set: XREF@audioplayer/set, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.

 -- : set (PLAYER, NAME, VALUE)
 -- : set (PLAYER, NAME_CELL, VALUE_CELL)
 -- : set (PLAYER, PROPERTIES_STRUCT)
 -- : PROPERTIES = set (PLAYER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays, set each property to the
     corresponding value.  Given a structure of properties with fields
     corresponding to property names, set the value of those properties
     to the corresponding field values.  Given only an audioplayer
     object, return a structure of configurable properties (i.e.,
     writeable properties).

     See also: *note @audioplayer/get: XREF@audioplayer/get, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer.


File: octave.info,  Node: Audio Recorder,  Next: Audio Data Processing,  Prev: Audio Player,  Up: Audio Processing

33.4 Audio Recorder
===================

The following methods are used to create and use audiorecorder objects.
These objects can be used to record audio data from various devices
available to the system.  You can use convenient methods to retrieve
that data or audioplayer objects created from that data.  Methods for
blocking and non-blocking recording, pausing and resuming recording and
much more is available.

 -- : RECORDER = audiorecorder ()
 -- : RECORDER = audiorecorder (FS, NBITS, NCHANNELS)
 -- : RECORDER = audiorecorder (FS, NBITS, NCHANNELS, ID)
     Create an audiorecorder object recording 8-bit mono audio at 8000
     Hz sample rate.

     The optional arguments FS, NBITS, NCHANNELS, and ID specify the
     sample rate, number of bits per sample, number of channels, and
     recording device ID, respectively.  Device IDs may be found using
     the ‘audiodevinfo’ function.

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

     Method           Description
     -----------------------------------------------------------------------
     get              Read audiorecorder property values
     getaudiodata     Return audio data as a numeric matrix
     getplayer        Return audioplayer loaded with data from
                      audiorecorder
     isrecording      Return true if audiorecorder is recording
     pause            Pause recording
     play             Play audio stored in audiorecorder object
     record           Record audio in audiorecorder object w/o blocking
     recordblocking   Record audio in audiorecorder object
     resume           Resume recording after pause
     set              Write audiorecorder property values
     stop             Stop recording

See also: *note @audiorecorder/get: XREF@audiorecorder/get, *note
@audiorecorder/getaudiodata: XREF@audiorecorder/getaudiodata, *note
@audiorecorder/getplayer: XREF@audiorecorder/getplayer, *note
@audiorecorder/isrecording: XREF@audiorecorder/isrecording, *note
@audiorecorder/pause: XREF@audiorecorder/pause, *note
@audiorecorder/play: XREF@audiorecorder/play, *note
@audiorecorder/record: XREF@audiorecorder/record, *note
@audiorecorder/recordblocking: XREF@audiorecorder/recordblocking, *note
@audioplayer/resume: XREF@audioplayer/resume, *note @audiorecorder/set:
XREF@audiorecorder/set, *note @audiorecorder/stop:
XREF@audiorecorder/stop, *note audiodevinfo: XREFaudiodevinfo, *note
@audioplayer/audioplayer: XREF@audioplayer/audioplayer, *note record:
XREFrecord.

* Menu:

* Recording::
* Data Retrieval::
* Recorder Properties::


File: octave.info,  Node: Recording,  Next: Data Retrieval,  Up: Audio Recorder

33.4.1 Recording
----------------

The following methods control the recording process.

 -- : record (RECORDER)
 -- : record (RECORDER, LENGTH)
     Record audio without blocking using the audiorecorder object
     RECORDER until paused or stopped by the PAUSE or STOP methods.

     Given the optional argument LENGTH, record for LENGTH seconds.

     See also: *note @audiorecorder/recordblocking:
     XREF@audiorecorder/recordblocking, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.

 -- : recordblocking (RECORDER, LENGTH)
     Record audio with blocking (synchronous I/O).

     The length of the recording in seconds (LENGTH) must be specified.

     See also: *note @audiorecorder/record: XREF@audiorecorder/record,
     *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder.

 -- : pause (RECORDER)
     Pause recording for audiorecorder RECORDER.

     See also: *note @audiorecorder/resume: XREF@audiorecorder/resume,
     *note @audiorecorder/stop: XREF@audiorecorder/stop, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.

 -- : resume (RECORDER)
     Resume recording with the paused audiorecorder object RECORDER.

     See also: *note @audiorecorder/pause: XREF@audiorecorder/pause,
     *note @audiorecorder/stop: XREF@audiorecorder/stop, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.

 -- : stop (RECORDER)
     Stop recording with audiorecorder object RECORDER and clean up any
     audio streams.

     See also: *note @audiorecorder/pause: XREF@audiorecorder/pause,
     *note @audiorecorder/resume: XREF@audiorecorder/resume, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.

 -- : TF = isrecording (RECORDER)
     Return true if the audiorecorder object RECORDER is currently
     recording audio and false otherwise.

     See also: *note @audiorecorder/pause: XREF@audiorecorder/pause,
     *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder.


File: octave.info,  Node: Data Retrieval,  Next: Recorder Properties,  Prev: Recording,  Up: Audio Recorder

33.4.2 Data Retrieval
---------------------

The following methods allow you to retrieve recorded audio data in
various ways.

 -- : DATA = getaudiodata (RECORDER)
 -- : DATA = getaudiodata (RECORDER, DATATYPE)
     Return audio data from audiorecorder object RECORDER as a double
     matrix with values between -1.0 and 1.0 and with as many columns as
     there are channels in RECORDER.

     Given the optional argument DATATYPE, convert the recorded data to
     the specified type, which may be one of "double", "single",
     "int16", "int8" or "uint8".

     See also: *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder.

 -- : PLAYER = getplayer (RECORDER)
     Return an audioplayer object with data recorded by the
     audiorecorder object RECORDER.

     See also: *note @audioplayer/audioplayer:
     XREF@audioplayer/audioplayer, *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder.

 -- : PLAYER = play (RECORDER)
 -- : PLAYER = play (RECORDER, START)
 -- : PLAYER = play (RECORDER, [START, END])
     Play the audio recorded in RECORDER without blocking and return a
     corresponding audioplayer object.

     If the optional argument START is provided, begin playing START
     seconds into the recording.

     If the optional argument END is provided, stop playing at END
     seconds into the recording.

     See also: *note @audiorecorder/getplayer:
     XREF@audiorecorder/getplayer, *note @audioplayer/audioplayer:
     XREF@audioplayer/audioplayer, *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder.


File: octave.info,  Node: Recorder Properties,  Prev: Data Retrieval,  Up: Audio Recorder

33.4.3 Properties
-----------------

The remaining two methods allow you to read or alter the properties of
audiorecorder objects.

 -- : VALUE = get (RECORDER, NAME)
 -- : VALUES = get (RECORDER, {NAME1, NAME2, ...})
 -- : VALUES = get (RECORDER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array return the values of the properties
     identified by the elements of the cell array.  Given only the
     recorder object, return a scalar structure with values for all
     properties of RECORDER.  The field names of the structure
     correspond to the property names.

     See also: *note @audiorecorder/set: XREF@audiorecorder/set, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.

 -- : set (RECORDER, NAME, VALUE)
 -- : set (RECORDER, NAME_CELL, VALUE_CELL)
 -- : set (RECORDER, PROPERTIES_STRUCT)
 -- : PROPERTIES = set (RECORDER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays, set each property to a
     corresponding value.  Given a structure of properties with fields
     corresponding to property names, set the value of those properties
     to the corresponding field values.  Given only a recorder object,
     return a structure of configurable properties (i.e., writeable
     properties).

     See also: *note @audiorecorder/get: XREF@audiorecorder/get, *note
     @audiorecorder/audiorecorder: XREF@audiorecorder/audiorecorder.


File: octave.info,  Node: Audio Data Processing,  Prev: Audio Recorder,  Up: Audio Processing

33.5 Audio Data 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’.

 -- : Y = lin2mu (X)
 -- : Y = lin2mu (X, N)
     Convert audio data from linear to mu-law.

     Linear values use floating point values in the range -1 ≤ X ≤ 1 if
     N is 0 (default), or N-bit signed integers if N is 8 or 16.  Mu-law
     values are 8-bit unsigned integers in the range 0 ≤ Y ≤ 255.

     See also: *note mu2lin: XREFmu2lin.

 -- : Y = mu2lin (X)
 -- : Y = mu2lin (X, N)
     Convert audio data from mu-law to linear.

     Mu-law values are 8-bit unsigned integers in the range 0 ≤ Y ≤ 255.
     Linear values use floating point values in the range -LINMAX ≤ X
     LINMAX (where ‘LINMAX = 32124/32768 =~ 0.98’) when N is zero
     (default).  If N is 8 or 16 then N-bit signed integers are used
     instead.

     Programming Note: ‘mu2lin’ maps maximum mu-law inputs to values
     slightly below the maximum ([-0.98, +0.98]) representable with a
     linear scale.  Because of this, ‘mu2lin (lin2mu (X))’ might not
     reproduce the original input.

     See also: *note lin2mu: XREFlin2mu.

 -- : DATA = record (SEC)
 -- : DATA = record (SEC, FS)
     Record SEC seconds of audio from the system's default audio input
     at a sampling rate of 8000 samples per second.

     If the optional argument FS is given, it specifies the sampling
     rate for recording.

     For more control over audio recording, use the ‘audiorecorder’
     class.

     See also: *note @audiorecorder/audiorecorder:
     XREF@audiorecorder/audiorecorder, *note sound: XREFsound, *note
     soundsc: XREFsoundsc.

 -- : sound (Y)
 -- : sound (Y, FS)
 -- : sound (Y, FS, NBITS)
     Play audio data Y at sample rate FS to the default audio device.

     The audio signal Y can be a vector or a two-column array
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note soundsc: XREFsoundsc, *note
     @audioplayer/audioplayer: XREF@audioplayer/audioplayer, *note
     record: XREFrecord.

 -- : soundsc (Y)
 -- : soundsc (Y, FS)
 -- : soundsc (Y, FS, NBITS)
 -- : soundsc (..., [YMIN, YMAX])
     Scale the audio data Y and play it at sample rate FS to the default
     audio device.

     The audio signal Y can be a vector or a two-column array
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     By default, Y is automatically normalized to the range [-1, 1].  If
     the range [YMIN, YMAX] is given, then elements of Y that fall
     within the range YMIN ≤ Y ≤ YMAX are scaled to the range [-1, 1]
     instead.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note sound: XREFsound, *note @audioplayer/audioplayer:
     XREF@audioplayer/audioplayer, *note record: XREFrecord.


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

34 Object Oriented Programming
******************************

Octave has the ability to create user-defined classes--including the
capabilities of operator and function overloading.  Classes can protect
internal properties so that they may not be altered accidentally which
facilitates data encapsulation.  In addition, rules can be created to
address the issue of class precedence in mixed class operations.

   This chapter discusses the means of constructing a user class, how to
query and set the properties of a class, and how to overload operators
and functions.  Throughout this chapter real code examples are given
using a class designed for polynomials.

* Menu:

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


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

34.1 Creating a Class
=====================

This chapter illustrates user-defined classes and object oriented
programming through a custom class designed for polynomials.  This class
was chosen for its simplicity which does not distract unnecessarily from
the discussion of the programming features of Octave.  Even so, a bit of
background on the goals of the polynomial class is necessary before the
syntax and techniques of Octave object oriented programming are
introduced.

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

   This is a sufficient specification to begin writing the constructor
for the polynomial class.  All object oriented classes in Octave must be
located in a directory that is the name of the class prepended with the
‘@’ symbol.  For example, the polynomial class will have all of its
methods defined in the ‘@polynomial’ directory.

   The constructor for the class must be the name of the class itself;
in this example the constructor resides in the file
‘@polynomial/polynomial.m’.  Ideally, even when the constructor is
called with no arguments it should return a valid object.  A constructor
for the polynomial class might look like

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn
     
     function p = polynomial (a)
     
       if (nargin == 0)
         p.poly = 0;
         p = class (p, "polynomial");
       else
         if (isa (a, "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
     endfunction

   Note that the return value of the constructor must be the output of
the ‘class’ function.  The first argument to the ‘class’ function is a
structure and the second is the name of the class itself.  An example of
calling the class constructor to create an instance is

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

   Methods are defined by m-files in the class directory and can have
embedded documentation the same as any other m-file.  The help for the
constructor can be obtained by using the constructor name alone, that
is, for the polynomial constructor ‘help polynomial’ will return the
help string.  Help can be restricted to a particular class by using the
class directory name followed by the method.  For example, ‘help
@polynomial/polynomial’ is another way of displaying the help string for
the polynomial constructor.  This second means is the only way to obtain
help for the overloaded methods and functions of a class.

   The same specification mechanism can be used wherever Octave expects
a function name.  For example ‘type @polynomial/disp’ will print the
code of the ‘disp’ method of the polynomial class to the screen, and
‘dbstop @polynomial/disp’ will set a breakpoint at the first executable
line of the ‘disp’ method of the polynomial class.

   To check whether a variable belongs to 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

 -- : TF = isobject (X)
     Return true if X is a class object.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo,
     *note isa: XREFisa, *note ismethod: XREFismethod, *note isprop:
     XREFisprop.

The available methods of a class can be displayed with the ‘methods’
function.

 -- : methods (OBJ)
 -- : methods ("CLASSNAME")
 -- : methods (..., "-full")
 -- : MTDS = methods (...)
     List the names of the public methods for the object OBJ or the
     named class CLASSNAME.

     OBJ may be an Octave class object or a Java object.  CLASSNAME may
     be the name of an Octave class or a Java class.

     If the optional argument "-full" is given then Octave returns full
     method signatures which include output type, name of method, and
     the number and type of inputs.

     When called with no output arguments, ‘methods’ prints the list of
     method names to the screen.  Otherwise, the output argument MTDS
     contains the list in a cell array of strings.

     See also: *note ismethod: XREFismethod, *note properties:
     XREFproperties, *note fieldnames: XREFfieldnames.

To inquire whether a particular method exists for a user class, the
‘ismethod’ function can be used.

 -- : TF = ismethod (OBJ, METHOD)
 -- : TF = ismethod (CLASS_NAME, METHOD)
     Return true if the string METHOD is a valid method of the object
     OBJ or of the class CLSNAME.

     See also: *note isprop: XREFisprop, *note isobject: XREFisobject,
     *note isjava: XREFisjava, *note methods: XREFmethods.

For a polynomial class it makes sense to have a method to compute its
roots.

     function r = roots (p)
       r = roots (fliplr (p.poly));
     endfunction

   We can check for the existence of the ‘roots’-method by calling:

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


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

34.2 Class Methods
==================

There are a number of basic class methods that can (and should) be
defined to allow the contents of the classes to be queried and set.  The
most basic of these is the ‘disp’ method.  The ‘disp’ method is used by
Octave whenever a class should be displayed on the screen.  Usually this
is the result of an Octave expression that doesn't end with a semicolon.
If this method is not defined, then Octave won't print anything when
displaying the contents of a class which can be confusing.

An example of a ‘disp’ method for the polynomial class might be

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

   To be consistent with the Octave graphic handle classes, a class
should also define the ‘get’ and ‘set’ methods.  The ‘get’ method
accepts one or two arguments.  The first argument is an object of the
appropriate class.  If no second argument is given then the method
should return a structure with all the properties of the class.  If the
optional second argument is given it should be a property name and the
specified property should be retrieved.

     function val = get (p, prop)
     
       if (nargin < 1)
         print_usage ();
       endif
     
       if (nargin == 1)
         val.poly = p.poly;
       else
         if (! ischar (prop))
           error ("@polynomial/get: PROPERTY must be a string");
         endif
     
         switch (prop)
           case "poly"
             val = p.poly;
           otherwise
             error ('@polynomial/get: invalid PROPERTY "%s"', prop);
         endswitch
       endif
     
     endfunction

Similarly, the first argument to the ‘set’ method should be an object
and any additional arguments should be property/value pairs.

     function pout = set (p, varargin)
     
       if (numel (varargin) < 2 || rem (numel (varargin), 2) != 0)
         error ("@polynomial/set: expecting PROPERTY/VALUE pairs");
       endif
     
       pout = p;
       while (numel (varargin) > 1)
         prop = varargin{1};
         val  = varargin{2};
         varargin(1:2) = [];
         if (! ischar (prop) || ! strcmp (prop, "poly"))
           error ("@polynomial/set: invalid PROPERTY for polynomial class");
         elseif (! (isreal (val) && isvector (val)))
           error ("@polynomial/set: VALUE must be a real vector");
         endif
     
         pout.poly = val(:).';  # force row vector
       endwhile
     
     endfunction

Note that Octave does not implement pass by reference; Therefore, to
modify an object requires an assignment statement using the return value
from the ‘set’ method.

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

The ‘set’ method makes use of the ‘subsasgn’ method of the class, and
therefore this method must also be defined.  The ‘subsasgn’ method is
discussed more thoroughly in the next section (*note Indexing
Objects::).

   Finally, user classes can be considered to be a special type of a
structure, and 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 contain a field that it
doesn't make 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.

 -- : 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: XREFloadobj, *note class: XREFclass.

‘saveobj’ is called just prior to saving the class to a file.
Similarly, 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.

 -- : 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: XREFsaveobj, *note class: XREFclass.


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

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

34.3.1 Defining Indexing And Indexed Assignment
-----------------------------------------------

Objects can be indexed with parentheses or braces, either like
‘OBJ(IDX)’ or like ‘OBJ{IDX}’, or even like ‘OBJ(IDX).FIELD’.  However,
it is up to the programmer to decide what this indexing actually means.
In the case of the 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.

 -- : NEWVAL = subsref (VAL, IDX)
     Perform the subscripted element selection operation on VAL
     according to the subscript specified by IDX.

     The subscript IDX must 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 first two 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)’.

     If IDX is an empty structure array with fields ‘type’ and ‘subs’,
     return VAL.

     The keyword ‘end’ cannot be used within ‘subsref’ for indexing
     assignments.

     See also: *note subsasgn: XREFsubsasgn, *note substruct:
     XREFsubstruct.

   For example, this class uses the convention that indexing with "()"
evaluates the polynomial and indexing with "{}" returns the N-th
coefficient (of the N-th power).  The code for the ‘subsref’ method
looks like

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

   The equivalent functionality for subscripted assignments uses the
‘subsasgn’ method.

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

     The subscript IDX must 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};
          val = 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’.

     If IDX is an empty structure array with fields ‘type’ and ‘subs’,
     return RHS.

     The keyword ‘end’ cannot be used within ‘subsasgn’ for indexing
     assignments.

     See also: *note subsref: XREFsubsref, *note substruct:
     XREFsubstruct, *note optimize_subsasgn_calls:
     XREFoptimize_subsasgn_calls.

 -- : VAL = optimize_subsasgn_calls ()
 -- : OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- : OLD_VAL = optimize_subsasgn_calls (NEW_VAL, "local")
     Query or set the internal flag for ‘subsasgn’ method call
     optimizations.

     If true, Octave will attempt to eliminate the redundant copying
     when calling the ‘subsasgn’ method of a user-defined class.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     See also: *note subsasgn: XREFsubsasgn.

   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 there must be an ‘end’ method defined.  For example, the
‘end’ method for the 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.  An example using the
polynomial class is then

     p = polynomial ([1,2,3,4]);
     p{end-1}
       ⇒ 3

   Objects can also be used themselves as the index in a subscripted
expression and this is controlled by the ‘subsindex’ function.

 -- : IDX = subsindex (OBJ)
     Convert an object to an index vector.

     When OBJ 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 were

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

     then the ‘subsindex’ function

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

     could be used as follows

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

     See also: *note class: XREFclass, *note subsref: XREFsubsref, *note
     subsasgn: XREFsubsasgn.

   Finally, objects can be used like ranges by providing a ‘colon’
method.

 -- : R = colon (BASE, LIMIT)
 -- : R = colon (BASE, INCREMENT, LIMIT)
     Return the result of the colon expression corresponding to BASE,
     LIMIT, and optionally, INCREMENT.

     This function is equivalent to the operator syntax
     ‘BASE : LIMIT’ or ‘BASE : INCREMENT : LIMIT’.

     See also: *note linspace: XREFlinspace.


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

34.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 the
following call to ‘subsasgn’

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

where 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.  In other words,
a constant-time operation is degraded 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 a direct
‘subsasgn’ call as shown above), i.e., ‘x(1) = 1’, AND if the ‘subsasgn’
method is declared with identical input and output arguments, as 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’ will exist in the caller's scope, it
is _solely_ the callee's responsibility to not leave ‘x’ in an invalid
state if an error occurs during 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 function ‘optimize_subsasgn_calls’ is provided to
control it.  This feature is enabled by default.  Another way to avoid
the optimization 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

34.4 Overloading Objects
========================

* Menu:

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


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

34.4.1 Function Overloading
---------------------------

Any Octave function can be overloaded, and this allows an
object-specific version of a function to be called as needed.  A
pertinent example for the polynomial class might be to overload the
‘polyval’ function.

     function [y, dy] = polyval (p, varargin)
     
       if (nargout > 1)
         [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 of an overloaded function for the
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, polyval (p, x), varargin{:});
       else
         plot (x, polyval (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 for overloading are the
class conversion functions such as ‘double’.  Overloading these
functions allows the ‘cast’ function to work with a user class.  It can
also aid in the use of a class object with methods and functions from
other classes since the object can be transformed to the requisite input
form for the new function.  An example ‘double’ function for the
polynomial class might look like

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


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

34.4.2 Operator Overloading
---------------------------

The following table shows, for each built-in numerical operation, the
corresponding function name to use when providing an overloaded method
for a user class.

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

Table 34.1: Available overloaded operators and their corresponding class
method

   An example ‘mtimes’ method for the polynomial class might look like

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


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

34.4.3 Precedence of Objects
----------------------------

Many functions and operators take two or more arguments and the
situation can easily arise where these functions are called with objects
of different classes.  It is therefore necessary to determine the
precedence of which method from 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

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

     See also: *note inferiorto: XREFinferiorto.

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

     See also: *note superiorto: XREFsuperiorto.

   With the 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 the return type should be "polynomial" and
so the ‘superiorto’ function is used in the class constructor.  In
particular the polynomial class constructor would be modified to

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn
     
     function p = polynomial (a)
     
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       else
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
       superiorto ("double");
     
     endfunction

   Note that user classes _always_ have higher precedence than built-in
Octave types.  Thus, marking the polynomial class higher than the
"double" class is not actually necessary.

   When confronted with two objects of equal precedence, Octave will use
the method of the object that appears first in the list of arguments.


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

34.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 structure 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 structure.  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 most easily demonstrated by example.  Suppose the programmer
needs a FIR filter, i.e., a filter with a numerator polynomial but a
denominator of 1.  In traditional Octave programming this would be
performed as follows.

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

   The equivalent behavior can be implemented as a class ‘@FIRfilter’.
The constructor for this class is the file ‘FIRfilter.m’ in the class
directory ‘@FIRfilter’.

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (! isa (p, "polynomial"))
         error ("@FIRfilter: P must be a polynomial object");
       endif
     
       f.polynomial = [];
       f = class (f, "FIRfilter", p);
     
     endfunction

   As before, the leading comments provide documentation for the class
constructor.  This constructor is very similar to the polynomial class
constructor, except that a polynomial object is passed as the third
argument to the ‘class’ function, telling Octave that the ‘FIRfilter’
class will be derived from the polynomial class.  The FIR filter class
itself does not have any data fields, but it must provide a struct to
the ‘class’ function.  Given that the ‘@polynomial’ constructor will add
an element named POLYNOMIAL to the object struct, the ‘@FIRfilter’ just
initializes a struct with a dummy field POLYNOMIAL which will later be
overwritten.

   Note that the sample code always provides for the case in which no
arguments are supplied.  This is important because Octave will call a
constructor with no arguments when loading objects from saved files in
order to determine the inheritance structure.

   A class may be a child of more than one class (*note class:
XREFclass.), 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.

   For the ‘FIRfilter’ class, more control about the object display is
desired.  Therefore, the ‘display’ method rather than the ‘disp’ method
is overloaded (*note Class Methods::).  A simple example might be

     function display (f)
       printf ("%s.polynomial", inputname (1));
       disp (f.polynomial);
     endfunction

   Note that the ‘FIRfilter’'s display method relies on the ‘disp’
method from the ‘polynomial’ class to actually display the filter
coefficients.  Furthermore, note that in the ‘display’ method it makes
sense to start the method with the line ‘printf ("%s =", inputname (1))’
to be consistent with the rest of Octave which prints the variable name
to be displayed followed by the value.  In general it is not recommended
to overload the ‘display’ function.

 -- : display (OBJ)
     Display the contents of the object OBJ prepended by its name.

     The Octave interpreter calls the ‘display’ function whenever it
     needs to present a class on-screen.  Typically, this would be a
     statement which does not end in a semicolon to suppress output.
     For example:

          myclass (...)

     Or:

          myobj = myclass (...)

     In general, user-defined classes should overload the ‘disp’ method
     to avoid the default output:

          myobj = myclass (...)
            ⇒ myobj =

            <class myclass>

     When overloading the ‘display’ method instead, one has to take care
     of properly displaying the object's name.  This can be done by
     using the ‘inputname’ function.

     See also: *note disp: XREFdisp, *note class: XREFclass, *note
     subsref: XREFsubsref, *note subsasgn: XREFsubsasgn.

   Once a constructor and display method exist, it is possible to create
an instance of the class.  It is also possible to check the class type
and examine the underlying structure.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
     f.polynomial = 0.33333 + 0.33333 * X + 0.33333 * 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 =

       scalar structure containing the fields:

     polynomial = 0.33333 + 0.33333 * X + 0.33333 * X ^ 2

   The only thing remaining to make this class usable is a method for
processing data.  But before that, it is usually desirable to also have
a way of changing the data stored in a class.  Since the fields in the
underlying struct are private by default, it is necessary to provide a
mechanism to access the fields.  The ‘subsref’ method may be used for
both tasks.

     function r = subsref (f, x)
     
       switch (x.type)
     
         case "()"
           n = f.polynomial;
           r = filter (n.poly, 1, x.subs{1});
     
         case "."
           fld = x.subs;
           if (! strcmp (fld, "polynomial"))
             error ('@FIRfilter/subsref: invalid property "%s"', fld);
           endif
           r = f.polynomial;
     
         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.33333 + 0.33333 * X + 0.33333 * X ^ 2

   In order to change the contents of the object a ‘subsasgn’ method is
needed.  For example, the following code makes the polynomial field
publicly writable

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

so that

     octave:1> f = FIRfilter ();
     octave:2> 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 a FIRfilter object may be used any place that a polynomial
object may be used.  This is not a normal use of a filter.  It may be a
more sensible design approach to use aggregation rather than
inheritance.  In this case, the polynomial is simply a field in the
class structure.  A class constructor for the aggregation case might be

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       else
         if (! isa (p, "polynomial"))
           error ("@FIRfilter: P must be a polynomial object");
         endif
     
         f.polynomial = p;
       endif
     
       f = class (f, "FIRfilter");
     
     endfunction

   For this example only the constructor needs changing, and all other
class methods stay the same.


File: octave.info,  Node: classdef Classes,  Prev: Inheritance and Aggregation,  Up: Object Oriented Programming

34.6 ‘classdef’ Classes
=======================

Since version 4.0, Octave has limited support for ‘classdef’ classes.
In contrast to the aforementioned classes, called “old style classes” in
this section, ‘classdef’ classes can be defined within a single m-file.
Other innovations of ‘classdef’ classes are:

   • access rights for properties and methods,

   • static methods, i.e., methods that are independent of an object,
     and

   • the distinction between value and handle classes.

   Several features have to be added in future versions of Octave to be
fully compatible to MATLAB.  An overview of what is missing can be found
at <https://wiki.octave.org/Classdef>.

* Menu:

* Creating a classdef Class::
* Properties::
* Methods::
* Inheritance::
* Value Classes vs. Handle Classes::


File: octave.info,  Node: Creating a classdef Class,  Next: Properties,  Up: classdef Classes

34.6.1 Creating a ‘classdef’ Class
----------------------------------

A very basic ‘classdef’ value class (*note Value Classes vs. Handle
Classes::) is defined by:

     classdef some_class
       properties
       endproperties

       methods
       endmethods
     endclassdef

   In contrast to old style classes, the ‘properties’-‘endproperties’
block as well as the ‘methods’-‘endmethods’ block can be used to define
properties and methods of the class.  Because both blocks are empty,
they can be omitted in this particular case.

   For simplicity, a more advanced implementation of a ‘classdef’ class
is shown using the ‘polynomial’ example again (*note Creating a
Class::):

     classdef polynomial2
       properties
         poly = 0;
       endproperties
     
       methods
         function p = polynomial2 (a)
           if (nargin == 1)
             if (isa (a, "polynomial2"))
               p.poly = a.poly;
             elseif (isreal (a) && isvector (a))
               p.poly = a(:).';  # force row vector
             else
               error ("polynomial2: A must be a real vector");
             endif
           endif
         endfunction
     
         function disp (p)
           a = p.poly;
           first = true;
           for i = 1 : length (a);
             if (a(i) != 0)
               if (first)
                 first = false;
               elseif (a(i) > 0 || isnan (a(i)))
                 printf (" +");
               endif
               if (a(i) < 0)
                 printf (" -");
               endif
               if (i == 1)
                 printf (" %.5g", abs (a(i)));
               elseif (abs (a(i)) != 1)
                 printf (" %.5g *", abs (a(i)));
               endif
               if (i > 1)
                 printf (" X");
               endif
               if (i > 2)
                 printf (" ^ %d", i - 1);
               endif
             endif
           endfor
     
           if (first)
             printf (" 0");
           endif
           printf ("\n");
         endfunction
       endmethods
     endclassdef

An object of class ‘polynomial2’ is created by calling the class
constructor:

     >> p = polynomial2 ([1, 0, 1])
     ⇒ p =

      1 + X ^ 2


File: octave.info,  Node: Properties,  Next: Methods,  Prev: Creating a classdef Class,  Up: classdef Classes

34.6.2 Properties
-----------------

All class properties must be defined within ‘properties’ blocks.  The
definition of a default value for a property is optional and can be
omitted.  The default initial value for each class property is ‘[]’.

   A ‘properties’ block can have additional attributes to specify access
rights or to define constants:

     classdef some_class
       properties (Access = MODE)
         PROP1
       endproperties

       properties (SetAccess = MODE, GetAccess = MODE)
         PROP2
       endproperties

       properties (Constant = true)
         PROP3 = pi ()
       endproperties

       properties
         PROP4 = 1337
       endproperties
     endclassdef

where MODE can be one of:

‘public’
     The properties can be accessed from everywhere.

‘private’
     The properties can only be accessed from class methods.  Subclasses
     of that class cannot access them.

‘protected’
     The properties can only be accessed from class methods and from
     subclasses of that class.

   When creating an object of ‘some_class’, PROP1 has the default value
‘[]’ and reading from and writing to PROP1 is defined by a single MODE.
For PROP2 the read and write access can be set differently.  Finally,
PROP3 is a constant property which can only be initialized once within
the ‘properties’ block.

   By default, in the example PROP4, properties are not constant and
have public read and write access.

 -- : properties (OBJ)
 -- : properties (CLASS_NAME)
 -- : PROPLIST = properties (...)
     Display or return the public properties for the classdef object OBJ
     or the named class CLASS_NAME.

     If an output value is requested, return the list of property names
     in a cell array.

     Programming Note: Property names are returned if the ‘GetAccess’
     attribute is public and if the ‘Hidden’ attribute is false.

     See also: *note methods: XREFmethods.


File: octave.info,  Node: Methods,  Next: Inheritance,  Prev: Properties,  Up: classdef Classes

34.6.3 Methods
--------------

All class methods must be defined within ‘methods’ blocks.  An exception
to this rule is described at the end of this subsection.  Those
‘methods’ blocks can have additional attributes specifying the access
rights or whether the methods are static, i.e., methods that can be
called without creating an object of that class.

     classdef some_class
       methods
         function obj = some_class ()
           disp ("New instance created.");
         endfunction

         function disp (obj)
           disp ("Here is some_class.");
         endfunction
       endmethods

       methods (Access = MODE)
         function r = func (obj, r)
           r = 2 * r;
         endfunction
       endmethods

       methods (Static = true)
         function c = circumference (radius)
           c = 2 * pi () .* radius;
         endfunction
       endmethods
     endclassdef

   The constructor of the class is declared in the ‘methods’ block and
must have the same name as the class and exactly one output argument
which is an object of its class.

   It is also possible to overload built-in or inherited methods, like
the ‘disp’ function in the example above to tell Octave how objects of
‘some_class’ should be displayed (*note Class Methods::).

   In general, the first argument in a method definition is always the
object that it is called from.  Class methods can either be called by
passing the object as the first argument to that method or by calling
the object followed by a dot ("‘.’") and the method's name with
subsequent arguments:

     >> obj = some_class ();
     New instance created.
     >> disp (obj);   # both are
     >> obj.disp ();  # equal

   In ‘some_class’, the method ‘func’ is defined within a ‘methods’
block setting the ‘Access’ attribute to MODE, which is one of:

‘public’
     The methods can be accessed from everywhere.

‘private’
     The methods can only be accessed from other class methods.
     Subclasses of that class cannot access them.

‘protected’
     The methods can only be accessed from other class methods and from
     subclasses of that class.

The default access for methods is ‘public’.

   Finally, the method ‘circumference’ is defined in a static ‘methods’
block and can be used without creating an object of ‘some_class’.  This
is useful for methods, that do not depend on any class properties.  The
class name and the name of the static method, separated by a dot
("‘.’"), call this static method.  In contrast to non-static methods,
the object is not passed as first argument even if called using an
object of ‘some_class’.

     >> some_class.circumference (3)
     ⇒ ans =  18.850
     >> obj = some_class ();
     New instance created.
     >> obj.circumference (3)
     ⇒ ans =  18.850

   Additionally, class methods can be defined as functions in a folder
of the same name as the class prepended with the ‘@’ symbol (*note
Creating a Class::).  The main ‘classdef’ file has to be stored in this
class folder as well.


File: octave.info,  Node: Inheritance,  Next: Value Classes vs. Handle Classes,  Prev: Methods,  Up: classdef Classes

34.6.4 Inheritance
------------------

Classes can inherit from other classes.  In this case all properties and
methods of the superclass are inherited to the subclass, considering
their access rights.  Use this syntax to inherit from ‘superclass’:

     classdef subclass < superclass
       ...
     endclassdef


File: octave.info,  Node: Value Classes vs. Handle Classes,  Prev: Inheritance,  Up: classdef Classes

34.6.5 Value Classes vs. Handle Classes
---------------------------------------

There are two intrinsically different types of ‘classdef’ classes, whose
major difference is the behavior regarding variable assignment.  The
first type are value classes:

     classdef value_class
       properties
         prop1
       endproperties

       methods
         function obj = set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

Assigning an object of that class to another variable essentially
creates a new object:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  1

   But that also means that you might have to assign the output of a
method that changes properties back to the object manually:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> a.set_prop1 (3);
     ⇒ ans =

     <object value_class>

     >> ans.prop1
     ⇒ ans =  3
     >> a.prop1
     ⇒ ans =  1

   The second type are handle classes.  Those classes have to be derived
from the abstract ‘handle’ class:

     classdef handle_class < handle
       properties
         prop1
       endproperties

       methods
         function set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

   In the following example, the variables ‘a’ and ‘b’ refer to the very
same object of class ‘handle_class’:

     >> a = handle_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  2

   Object properties that are modified by a method of an handle class
are changed persistently:

     >> a.set_prop1 (3);
     >> a.prop1
     ⇒ ans =  3


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

35 GUI Development
******************

Octave is principally a batch or command-line language.  However, it
does offer some features for constructing graphical interfaces that
interact with users.

   The GUI elements available are I/O dialogs, a progress bar, and UI
elements for plot windows.  For example, rather than hardcoding a
filename for output results a script can open a dialog box and allow the
user to choose a file.  Similarly, if a calculation is expected to take
a long time a script can display a progress bar.  The various UI
elements can be used to fully customize the plot window with menubars,
toolbars, context menus, pushbuttons, sliders, etc.

   Several utility functions make it possible to store private data for
use with a GUI which will not pollute the user's variable space.

   Finally, a program written in Octave might want to have long term
storage of preferences or state variables.  This can be done with
user-defined preferences.

* Menu:

* I/O Dialogs::
* Progress Bar::
* UI Elements::
* GUI Utility Functions::
* User-Defined Preferences::
* Octave Workspace Windows::


File: octave.info,  Node: I/O Dialogs,  Next: Progress Bar,  Up: GUI Development

35.1 I/O Dialogs
================

Simple dialog menus are available for choosing directories or files.
They return a string variable which can then be used with any command
requiring a filename.

 -- : DIRNAME = uigetdir ()
 -- : DIRNAME = uigetdir (INIT_PATH)
 -- : DIRNAME = uigetdir (INIT_PATH, DIALOG_NAME)
     Open a GUI dialog for selecting a directory.

     If INIT_PATH is not given the current working directory is used.

     DIALOG_NAME may be used to customize the dialog title.

     The output DIRNAME is a character string with the name of the
     selected directory.  However, if the ‘Cancel’ button is clicked the
     output is of type double with the value ‘0’.

     See also: *note uigetfile: XREFuigetfile, *note uiputfile:
     XREFuiputfile.

 -- : [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- : [...] = uigetfile (FLT)
 -- : [...] = uigetfile (FLT, DIALOG_NAME)
 -- : [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- : [...] = uigetfile (..., "MultiSelect", MODE)

     Open a GUI dialog for selecting a file and return the filename
     FNAME, the path to this file FPATH, and the filter index FLTIDX.

     FLT contains a (list of) file filter string(s) in one of the
     following formats:

     "/path/to/filename.ext"
          If a filename is given then the file extension is extracted
          and used as filter.  In addition, the path is selected as
          current path in the dialog and the filename is selected as
          default file.  Example: ‘uigetfile ("myfcn.m")’

     A single file extension "*.ext"
          Example: ‘uigetfile ("*.ext")’

     A 2-column cell array
          containing a file extension in the first column and a brief
          description in the second column.  Example: ‘uigetfile
          ({"*.ext", "My Description";"*.xyz", "XYZ-Format"})’

          The filter string can also contain a semicolon separated list
          of filter extensions.  Example: ‘uigetfile
          ({"*.gif;*.png;*.jpg", "Supported Picture Formats"})’

     A directory name or path name
          If the folder name of path name contains a trailing file
          separator, the contents of that folder will be displayed.  If
          no trailing file separator is present the parent directory is
          listed.  The substring to the right of the rightmost file
          separator (if any) will be interpreted as a file or directory
          name and if that file or directory exists it will be
          highlighted.  If the path name or directory name is entirely
          or partly nonexistent, the current working directory will be
          displayed.  No filter will be active.

     DIALOG_NAME can be used to customize the dialog title.

     If DEFAULT_FILE is given then it will be selected in the GUI
     dialog.  If, in addition, a path is given it is also used as
     current path.

     Two or more files can be selected when setting the "MultiSelect"
     key to "on".  In that case, FNAME is a cell array containing the
     files.

     The outputs FNAME and FPATH are strings returning the chosen name
     and path, respectively.  However, if the ‘Cancel’ button is clicked
     the outputs are of type double with a value of ‘0’.  FLTIDX is the
     index in the list of filter extensions FLT that was selected.

     See also: *note uiputfile: XREFuiputfile, *note uigetdir:
     XREFuigetdir.

 -- : [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME,
          DEFAULT_FILE)
     Open a GUI dialog for selecting a file.

     FLT contains a (list of) file filter string(s) in one of the
     following formats:

     "/path/to/filename.ext"
          If a filename is given the file extension is extracted and
          used as filter.  In addition the path is selected as current
          path in the dialog and the filename is selected as default
          file.  Example: ‘uiputfile ("myfcn.m")’

     "*.ext"
          A single file extension.  Example: ‘uiputfile ("*.ext")’

     ‘{"*.ext", "My Description"}’
          A 2-column cell array containing the file extension in the 1st
          column and a brief description in the 2nd column.  Example:
          ‘uiputfile ({"*.ext","My Description";"*.xyz", "XYZ-Format"})’

     The filter string can also contain a semicolon separated list of
     filter extensions.  Example: ‘uiputfile ({"*.gif;*.png;*.jpg",
     "Supported Picture Formats"})’

     DIALOG_NAME can be used to customize the dialog title.  If
     DEFAULT_FILE is given it is preselected in the GUI dialog.  If, in
     addition, a path is given it is also used as current path.

     FNAME and FPATH return the chosen name and path, respectively.
     FLTIDX is the index in the list of filter extensions FLT that was
     selected.

     See also: *note uigetfile: XREFuigetfile, *note uigetdir:
     XREFuigetdir.

   Additionally, there are dialog boxes for displaying help messages,
warnings, or errors, and for getting text input from the user.

 -- : errordlg ()
 -- : errordlg (MSG)
 -- : errordlg (MSG, TITLE)
 -- : errordlg (MSG, TITLE, OPT)
 -- : H = errordlg (...)
     Display an error dialog box with error message MSG and caption
     TITLE.

     The default error message is "This is the default error string."
     and the default caption is "Error Dialog".

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

     The third optional argument OPT controls the behavior of the
     dialog.  For details, *note ‘msgbox’: XREFmsgbox.

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          errordlg ("Some fancy error occurred.");
          errordlg ("Some fancy error\nwith two lines.");
          errordlg ({"Some fancy error", "with two lines."});
          errordlg ("Some fancy error occurred.", "Fancy caption");

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

 -- : helpdlg ()
 -- : helpdlg (MSG)
 -- : helpdlg (MSG, TITLE)
 -- : H = helpdlg (...)
     Display a help dialog box with help message MSG and caption TITLE.

     The default help message is "This is the default help string." and
     the default caption is "Help Dialog".

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

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          helpdlg ("Some helpful text for the user.");
          helpdlg ("Some helpful text\nwith two lines.");
          helpdlg ({"Some helpful text", "with two lines."});
          helpdlg ("Some helpful text for the user.", "Fancy caption");

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

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

     Inputs:

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

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

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

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

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

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

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

     OPTIONS
          Not supported, only for MATLAB compatibility.

     Example:

          prompt = {"Width", "Height", "Depth"};
          defaults = {"1.10", "2.20", "3.30"};
          rowscols = [1,10; 2,20; 3,30];
          dims = inputdlg (prompt, "Enter Box Dimensions", ...
                           rowscols, defaults);

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

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

     The indices in SEL are 1-based.

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

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

     Valid KEY and VALUE pairs are:

     "ListString"
          a cell array of strings specifying the items to list in the
          dialog.

     "SelectionMode"
          can be either "Single" (only one item may be selected at a
          time) or "Multiple" (default).

     "ListSize"
          a two-element vector ‘[WIDTH, HEIGHT]’ specifying the size of
          the list field in pixels.  The default is [160, 300].

     "InitialValue"
          a vector containing 1-based indices of elements which will be
          pre-selected when the list dialog is first displayed.  The
          default is 1 (first item).

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

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

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

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

     Example:

          my_options = {"An item", "another", "yet another"};
          [sel, ok] = listdlg ("ListString", my_options,
                               "SelectionMode", "Multiple");
          if (ok == 1)
            disp ("You selected:");
            for i = 1:numel (sel)
              disp (sprintf ("\t%s", my_options{sel(i)}));
            endfor
          else
            disp ("You cancelled.");
          endif

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

 -- : H = msgbox (MSG)
 -- : H = msgbox (MSG, TITLE)
 -- : H = msgbox (MSG, TITLE, ICON)
 -- : H = msgbox (MSG, TITLE, "custom", CDATA)
 -- : H = msgbox (MSG, TITLE, "custom", CDATA, COLORMAP)
 -- : H = msgbox (..., OPT)
     Display MSG using a message dialog box.

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

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

     The optional argument ICON selects a dialog icon.  It can be one of
     "none" (default), "error", "help", "warn", or "custom".  The latter
     must be followed by an image array CDATA, and for indexed images
     the associated colormap.

     The final optional argument OPT controls the behavior of the
     dialog.  If OPT is a string, it may be one of

     "non-modal" (default)
          The dialog is normal.

     "modal"
          If any dialogs already exist with the same title, the most
          recent is reused and all others are closed.  The dialog is
          displayed "modal" which means it prevents users from
          interacting with any other GUI element until the dialog has
          been closed.

     "replace"
          If any dialogs already exist with the same title, the most
          recent is reused and all others are closed.  The resulting
          dialog is set "non-modal".

     If OPT is a structure, it must contain fields "WindowStyle" and
     "Interpreter":

     "WindowStyle"
          The value must be "non-modal", "modal", or "replace".  See
          above.

     "Interpreter"
          Controls the "interpreter" property of the text object used
          for displaying the message.  The value must be "tex"
          (default), "none", or "latex".

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          msgbox ("Some message for the user.");
          msgbox ("Some message\nwith two lines.");
          msgbox ({"Some message", "with two lines."});
          msgbox ("Some message for the user.", "Fancy caption");

          ## A message dialog box with error icon
          msgbox ("Some message for the user.", "Fancy caption", "error");

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

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

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

     The optional TITLE (character string) can be used to specify the
     dialog caption.  It defaults to "Question Dialog".

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

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

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

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

     Examples:

          btn = questdlg ("Close Octave?", "Some fancy title", ...
                          "Yes", "No", "No");
          if (strcmp (btn, "Yes"))
            exit ();
          endif

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

 -- : warndlg ()
 -- : warndlg (MSG)
 -- : warndlg (MSG, TITLE)
 -- : warndlg (MSG, TITLE, OPT)
 -- : H = warndlg (...)
     Display a warning dialog box with warning message MSG and caption
     TITLE.

     The default warning message is "This is the default warning
     string." and the default caption is "Warning Dialog".

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

     The third optional argument OPT controls the behavior of the
     dialog.  For details, *note ‘msgbox’: XREFmsgbox.

     The return value H is a handle to the figure object used for
     building the dialog.

     Examples:

          warndlg ("Some warning text for the user.");
          warndlg ("Some warning text\nwith two lines.");
          warndlg ({"Some warning text", "with two lines."});
          warndlg ("Some warning text for the user.", "Fancy caption");

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

 -- : uisetfont ()
 -- : uisetfont (H)
 -- : uisetfont (FONTSTRUCT)
 -- : uisetfont (..., TITLE)
 -- : FONTSTRUCT = uisetfont (...)
     Open a font selection dialog.

     If the first argument is a handle to a text, axes, or uicontrol
     object, pressing the OK button will change the font properties of
     the object.

     The first argument may also be a structure with fields ‘FontName’,
     ‘FontWeight’, ‘FontAngle’, ‘FontUnits’, and ‘FontSize’, indicating
     the initially selected font.

     The title of the dialog window can be specified by using the last
     argument TITLE.

     If an output argument FONTSTRUCT is requested, the selected font
     structure is returned.  Otherwise, the font information is
     displayed onscreen.

     Programming Note: On systems that don't use FontConfig natively
     (all but Linux), the font cache is built when Octave is installed.
     You will need to run ‘system ("fc-cache -fv")’ manually after
     installing new fonts.

     See also: *note listfonts: XREFlistfonts, *note text: XREFtext,
     *note axes: XREFaxes, *note uicontrol: XREFuicontrol.

   For creating new dialog types, there is a dialog function.

 -- : H = dialog ()
 -- : H = dialog ("PROPERTY", VALUE, ...)

     Create an empty modal dialog window to which other uicontrols can
     be added.

     The dialog box is a figure object with properties as recommended
     for a dialog box.

     The default properties differing from a figure are:

     buttondownfcn
          ‘if isempty (allchild(gcbf)), close (gcbf), endif’

     colormap
          []

     color
          defaultuicontrolbackgroundcolor

     dockcontrols
          off

     handlevisibility
          callback

     integerhandle
          off

     inverthardcopy
          off

     menubar
          none

     numbertitle
          off

     paperpositionmode
          auto

     resize
          off

     windowstyle
          modal

     Multiple property-value pairs may be specified for the dialog
     object, but they must appear in pairs.  The full list of properties
     is documented at *note Figure Properties::.

     The return value H is a graphics handle to the created figure.

     Example:

          ## create an empty dialog window titled "Dialog Example"
          h = dialog ("name", "Dialog Example");

          ## create a button (default style)
          b = uicontrol (h, "string", "OK",
                            "position", [10 10 150 40],
                            "callback", "delete (gcf)");

          ## wait for dialog to resume or close
          uiwait (h);

     See also: *note errordlg: XREFerrordlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg, *note
     figure: XREFfigure, *note uiwait: XREFuiwait.


File: octave.info,  Node: Progress Bar,  Next: UI Elements,  Prev: I/O Dialogs,  Up: GUI Development

35.2 Progress Bar
=================

 -- : H = waitbar (FRAC)
 -- : H = waitbar (FRAC, MSG)
 -- : H = waitbar (..., "createcancelbtn", FCN, ...)
 -- : H = waitbar (..., PROP, VAL, ...)
 -- : waitbar (FRAC)
 -- : waitbar (FRAC, H)
 -- : waitbar (FRAC, H, MSG)
     Return a handle H to a new progress indicator ("waitbar") object.

     The waitbar is filled to fraction FRAC which must be in the range
     [0, 1].

     The optional message MSG is centered and displayed above the
     waitbar.

     A cancel button can be added to the bottom of the waitbar using the
     "createcancelbtn" property of waitbar figures.  The action to be
     executed when the user presses the button is specified using a
     string or function handle FCN.

     The appearance of the waitbar figure window can be configured by
     passing PROP/VAL pairs to the function.  The full list of
     properties is documented at *note Figure Properties::.

     When called with a single input the current waitbar, if it exists,
     is updated to the new value FRAC.  If there are multiple
     outstanding waitbars they can be updated individually by passing
     the handle H of the specific waitbar to modify.

     See also: *note delete: XREFdelete.


File: octave.info,  Node: UI Elements,  Next: GUI Utility Functions,  Prev: Progress Bar,  Up: GUI Development

35.3 UI Elements
================

The ui* series of functions work best with the ‘qt’ graphics toolkit,
although some functionality is available with the ‘fltk’ toolkit.  There
is no support for the ‘gnuplot’ toolkit.

 -- : H = uifigure ()
 -- : H = uifigure ("PROPERTY", VALUE, ...)
     Create a new figure window for applications.

     Multiple property-value pairs may be specified for the figure
     object, but they must occur in pairs.

     The return value H is a graphics handle to the created figure
     object.

     Programming Note: The full list of properties is documented at
     *note Figure Properties::.  This function differs from ‘figure’ in
     that the created figure is optimized for application development,
     rather than plotting.  This means features such as menubars and
     toolbars are turned off.

     See also: *note uipanel: XREFuipanel, *note uibuttongroup:
     XREFuibuttongroup.

 -- : HUI = uipanel ()
 -- : HUI = uipanel (PROPERTY, VALUE, ...)
 -- : HUI = uipanel (PARENT)
 -- : HUI = uipanel (PARENT, PROPERTY, VALUE, ...)

     Create a uipanel object.

     uipanels are used as containers to group other uicontrol objects.

     If PARENT is omitted then a uipanel for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uipanel relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uipanel object.

     The full list of properties is documented at *note Uipanel
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uipanel object.

     Examples:

          ## create figure and panel on it
          f = figure;
          p = uipanel ("title", "Panel Title", "position", [.25 .25 .5 .5]);

          ## add two buttons to the panel
          b1 = uicontrol ("parent", p, "string", "A Button", ...
                          "position", [18 10 150 36]);
          b2 = uicontrol ("parent", p, "string", "Another Button", ...
                          "position",[18 60 150 36]);


     See also: *note figure: XREFfigure, *note uicontrol: XREFuicontrol.

 -- : HUI = uibuttongroup ()
 -- : HUI = uibuttongroup (PROPERTY, VALUE, ...)
 -- : HUI = uibuttongroup (PARENT)
 -- : HUI = uibuttongroup (PARENT, PROPERTY, VALUE, ...)
 -- : uibuttongroup (H)

     Create a uibuttongroup object and return a handle to it.

     A uibuttongroup is used to group uicontrol objects.

     If PARENT is omitted then a uibuttongroup for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uibuttongroup relative to PARENT is
     created.

     Any provided property value pairs will override the default values
     of the created uibuttongroup object.

     The full list of properties is documented at *note Uibuttongroup
     Properties::.

     Examples:

          ## Create figure and panel on it
          f = figure;
          ## Create a button group
          gp = uibuttongroup (f, "Position", [ 0 0.5 1 1])
          ## Create a buttons in the group
          b1 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 1", ...
                          "Position", [ 10 150 100 50 ]);
          b2 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 2", ...
                          "Position", [ 10 50 100 30 ]);
          ## Create a button not in the group
          b3 = uicontrol (f, "style", "radiobutton", ...
                          "string", "Not in the group", ...
                          "Position", [ 10 50 100 50 ]);

     When called with a single argument H which is a handle to an
     existing uibuttongroup object, switch the focus to the specified
     uibuttongroup.  This functionality is not currently implemented.

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : HUI = uicontrol ()
 -- : HUI = uicontrol (PROPERTY, VALUE, ...)
 -- : HUI = uicontrol (PARENT)
 -- : HUI = uicontrol (PARENT, PROPERTY, VALUE, ...)
 -- : uicontrol (H)

     Create a uicontrol object and return a handle to it.

     A uicontrol object is used to create simple interactive controls
     such as push buttons, checkboxes, edit and list controls.

     If PARENT is omitted then a uicontrol for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uicontrol relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uicontrol object.

     The full list of properties is documented at *note Uicontrol
     Properties::.

     The type of uicontrol created is specified by the STYLE property.
     If no style property is provided, a push button will be created.

     Valid styles for uicontrol are:

     "checkbox"
          Create a checkbox control that allows user on/off selection.

     "edit"
          Create an edit control that allows user input of single or
          multiple lines of text.

     "listbox"
          Create a listbox control that displays a list of items and
          allows user selection of single or multiple items.

     "popupmenu"
          Create a popupmenu control that displays a list of options
          that can be selected when the user clicks on the control.

     "pushbutton"
          Create a push button control that allows user to press to
          cause an action.

     "radiobutton"
          Create a radio button control intended to be used for mutually
          exclusive input in a group of radiobutton controls.

     "slider"
          Create a slider control that allows user selection from a
          range of values by sliding knob on the control.

     "text"
          Create a static text control to display single or multiple
          lines of text.

     "togglebutton"
          Create a toggle button control that appears like a push button
          but allows the user to select between two states.

     Note: For the "edit" and "listbox" styles, the single or multiple
     line/selection behavior is determined by the "Min" and "Max"
     properties, permitting multiple lines/selections when the values
     are set such that ‘Max - Min > 1’.

     Examples:

          ## Create figure and panel on it
          f = figure;
          ## Create a button (default style)
          b1 = uicontrol (f, "string", "A Button", ...
                             "position", [10 10 150 40]);
          ## Create an edit control
          e1 = uicontrol (f, "style", "edit", "string", "editable text", ...
                             "position", [10 60 300 40]);
          ## Create a checkbox
          c1 = uicontrol (f, "style", "checkbox", "string", "a checkbox", ...
                             "position", [10 120 150 40]);

     When called with a single argument H which is a handle to an
     existing uicontrol object, switch the keyboard focus to the
     specified uicontrol.  As a result, the uicontrol object will
     receive keyboard events that can be processed using the
     "keypressfcn" callback.

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : HUI = uitable (PROPERTY, VALUE, ...)
 -- : HUI = uitable (PARENT, PROPERTY, VALUE, ...)
     Create a uitable object and return a handle to it.

     A uitable object is used to show tables of data in a figure window.

     If PARENT is omitted then a uitable for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uitable relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uitable object.

     The full list of properties is documented at *note Uitable
     Properties::.

     Examples:

          ## Create figure and place a table on it
          f = figure ();
          m = magic (8);
          t = uitable (f, "Data", m, "ColumnWidth", { 40 });

          ## Create a table with labeled rows and columns
          f = figure ();
          d = reshape (1:9, [3, 3]);
          row_names = { "Row1", "Row2", "Row3" };
          col_names = { "Col1", "Col2", "Col3" };
          t = uitable (f, "Data", d, ...
                       "RowName", row_names, "ColumnName", col_names);

          p = get (t, "Position");
          e = get (t, "Extent");
          p(3:4) = e(3:4);
          set (t, "Position", p);

          ## Long demo with callbacks
          function uitable_demo ()
            f = figure ("Name", "uitable Demo", "Menu", "none", ...
                        "Position", [10 10 1000 680]);

            ## A basic example
            d = { "char"   , "A string";
                  "double" , 12.3456789;
                  "complex", 1+2i;
                  "bool"   , true;
                  "single" , single(12.3456789);
                  "int8"   , int8(-128);
                  "uint8"  , uint8(128);
                  "int16"  , int16(-32768);
                  "uint16" , uint16(32768);
                  "int32"  , int32(-2147483648);
                  "uint32" , uint32(2147483648);
                  "int64"  , int64(-2147483649);
                  "uint64" , uint64(2147843649)};

            popup_options = {"A", "B", "C", "D", "E"};

            columnformat_options = { "[]", "char", "pop-up", "numeric", ...
                                     "short", "short e", "short eng", ...
                                     "short g", "long", "long e", ...
                                     "long eng", "long g", "bank", "+", ...
                                     "rat", "logical"};
            columnformat_values = columnformat_options;
            columnformat_values{1} = "";
            columnformat_values{3} = popup_options;

            default_data = repmat (d(:,2), 1, columns (columnformat_options));
            b_add = uicontrol (f, "Position", [285 630 600 50], ...
                      "UserData", [rows(d), 1], ...
                      "Style", "pushbutton", ...
                      "String", "Set data at selected point to selected datatype");

            l_type_table = uicontrol (f, "Position", [ 0 603 120 25 ], ...
                "String", "Datatype Table:", ...
                "Style", "text");
            t_type_table = uitable (f, "Position", [ 0 530 1000 70 ], ...
                "Data", transpose (d(:, 2)), ...
                "ColumnName", transpose (d(:, 1)), ...
                "RowName", "Value", ...
                "CellSelectionCallback", ...
                     @(x, y) set (b_add, "UserData", y.Indices ));

            l_point_table = uicontrol (f, "Position", [ 0 640 60 25 ], ...
                "String", "Point:", ...
                "Style", "text");
            t_point_table = uitable (f, "Position", [ 80 630 160 42 ], ...
                "RowName", [], ...
                "ColumnName", {"x", "y"}, ...
                "Data", [ 1, 1 ], ...
                "ColumnEditable", true);

            l_editable_table = uicontrol (f, "Position", [ 0 502 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Columns Editable:");
            t_editable_table = ...
              uitable (f, "Position", [ 0 434 1000 65 ], ...
                          "Data", repmat (false, 1, columns (default_data)), ...
                          "ColumnEditable", true);

            l_format_table = uicontrol (f, "Position", [ 0 406 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Column Format:");
            t_format_table = ...
              uitable (f, "Position", [ 0 338 1000 65 ], ...
                          "Data", columnformat_options, ...
                          "ColumnEditable", true, ...
                          "ColumnFormat", arrayfun (@(x) {columnformat_options}, ...
                                                    1:columns (columnformat_options)));

            l_data_table = uicontrol (f, "Style", "text", ...
                                         "String", "Data:", ...
                                         "Position", [ 0 310 60 25 ]);
            t_data_table = uitable (f, "Position", [ 0 15 1000 290 ], ...
                "Data", default_data, ...
                "ColumnFormat", columnformat_values);

            set (t_format_table, ...
                 "CellEditCallback", ...
                 @(x, y) update_column_format (y.NewData, y.Indices, ...
                                                t_data_table, popup_options));
            set (t_point_table, "CellEditCallback", ...
                 @(x, y) validate_point_table (x, y, t_data_table));
            set (t_editable_table, "CellEditCallback", ...
                 @(x,y) set (t_data_table, ...
                              "ColumnEditable", get (t_editable_table, "Data")));
            set (b_add, ...
                 "Callback", @(x, y) update_data (b_add, t_point_table, ...
                                                   t_type_table, t_data_table));
            set (t_data_table, "CellSelectionCallback", ...
                 @(x, y) update_point_table (y.Indices, t_point_table));
          endfunction

          function validate_point_table (h, dat, t_data_table)
            if (! (dat.NewData > 0 && ...
              dat.NewData < size (get (t_data_table, "Data"), dat.Indices(1, 1)) + 1))

              d = get (h, "Data");
              d(dat.Indices) = 1;
              set (h, "Data", d);
            endif
          endfunction

          function update_column_format (format, indices, t_data_table, ...
                                         popup_options)
            cf = get (t_data_table, "ColumnFormat");
            if (strcmp (format, "[]"))
              format = "";
            elseif (strcmp (format, "pop-up"))
              format = popup_options;
            endif
            cf{indices(1,2)} = format;
            set (t_data_table, "ColumnFormat", cf);
          endfunction

          function update_point_table (indices, t_point_table)
            if (isempty (indices))
              indices = [1, 1];
            endif
            set (t_point_table, "Data", indices(1,:));
          endfunction

          function update_data (b_add, t_point_table, t_type_table, ...
                                t_data_table)
            indices = get (b_add, "UserData");
            if (isempty (indices))
              indices = [1, 1];
            endif
            d = get (t_data_table, "Data");
            t_type_table_data = get (t_type_table, "Data");
            p = get (t_point_table, "Data");
            d(p(1,2), p(1,1)) = t_type_table_data(indices(1,2));
            set (t_data_table, "Data", d);
          endfunction

     See also: *note figure: XREFfigure, *note uicontrol: XREFuicontrol.

 -- : HUI = uimenu (PROPERTY, VALUE, ...)
 -- : HUI = uimenu (H, PROPERTY, VALUE, ...)
     Create a uimenu object and return a handle to it.

     If H is omitted then a top-level menu for the current figure is
     created.  If H is given then a submenu relative to H is created.

     uimenu objects have the following specific properties:

     "accelerator"
          A string containing the key, together with CTRL, to execute
          this menu entry (e.g., "x" for CTRL+x).

     "checked"
          Can be set "on" or "off".  Sets a mark at this menu entry.

     "enable"
          Can be set "on" or "off".  If disabled then the menu entry
          cannot be selected and is grayed out.

     "foregroundcolor"
          A color value for the text of the menu entry.

     "menuselectedfcn"
          The function called when this menu entry is executed.  It can
          be either a function string (e.g., "myfcn"), a function handle
          (e.g., @myfcn) or a cell array containing the function handle
          and arguments for the callback function (e.g., {@myfcn, arg1,
          arg2}).

     "position"
          A scalar value containing the relative menu position.  The
          first position has value 1 and will be either the left or top
          depending on the orientation of the uimenu.

     "separator"
          Can be set "on" or "off".  If enabled, a separator line is
          drawn above the current position.  This property is ignored
          for top-level entries.

     "text"
          A string containing the text for this menu entry.  A
          "&"-symbol can be used to mark the "accelerator" character
          (e.g., "E&xit").

     The full list of properties is documented at *note Uimenu
     Properties::.

     Examples:

          f = uimenu ("text", "&File", "accelerator", "f");
          e = uimenu ("text", "&Edit", "accelerator", "e");
          uimenu (f, "text", "Close", "accelerator", "q", ...
                     "menuselectedfcn", "close (gcf)");
          uimenu (e, "text", "Toggle &Grid", "accelerator", "g", ...
                     "menuselectedfcn", "grid (gca)");

     See also: *note figure: XREFfigure.

 -- : HUI = uicontextmenu (PROPERTY, VALUE, ...)
 -- : HUI = uicontextmenu (H, PROPERTY, VALUE, ...)

     Create a uicontextmenu object and return a handle to it.

     If H is omitted then a uicontextmenu for the current figure is
     created.  If no figure is available, a new figure is created first.

     If H is given then a uicontextmenu relative to H is created.

     Any provided property value pairs will override the default values
     of the created uicontextmenu object.

     The full list of properties is documented at *note Uicontextmenu
     Properties::.

     Examples:

          ## create figure and uicontextmenu
          f = figure ();
          c = uicontextmenu (f);

          ## create menus in the context menu
          m1 = uimenu ("parent", c, "label", "Menu item 1", ...
                       "callback", "disp('menu item 1')");
          m2 = uimenu ("parent", c, "label", "Menu item 2", ...
                       "callback", "disp('menu item 2')");

          ## set the context menu for the figure
          set (f, "uicontextmenu", c);

     See also: *note figure: XREFfigure, *note uimenu: XREFuimenu.

 -- : HUI = uitoolbar ()
 -- : HUI = uitoolbar (PROPERTY, VALUE, ...)
 -- : HUI = uitoolbar (PARENT)
 -- : HUI = uitoolbar (PARENT, PROPERTY, VALUE, ...)

     Create a uitoolbar object.  A uitoolbar displays uitoggletool and
     uipushtool buttons.

     If PARENT is omitted then a uitoolbar for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uitoolbar relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uitoolbar object.

     The full list of properties is documented at *note Uitoolbar
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoolbar object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);

     See also: *note figure: XREFfigure, *note uitoggletool:
     XREFuitoggletool, *note uipushtool: XREFuipushtool.

 -- : HUI = uipushtool ()
 -- : HUI = uipushtool (PROPERTY, VALUE, ...)
 -- : HUI = uipushtool (PARENT)
 -- : HUI = uipushtool (PARENT, PROPERTY, VALUE, ...)

     Create a uipushtool object.

     uipushtools are buttons that appear on a figure toolbar.  The
     button is created with a border that is shown when the user hovers
     over the button.  An image can be set using the cdata property.

     If PARENT is omitted then a uipushtool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uipushtool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uipushtool object.

     The full list of properties is documented at *note Uipushtool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uipushtool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add pushtool button to toolbar
          b = uipushtool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uitoggletool: XREFuitoggletool.

 -- : HUI = uitoggletool ()
 -- : HUI = uitoggletool (PROPERTY, VALUE, ...)
 -- : HUI = uitoggletool (PARENT)
 -- : HUI = uitoggletool (PARENT, PROPERTY, VALUE, ...)

     Create a uitoggletool object.

     uitoggletool are togglebuttons that appear on a figure toolbar.
     The button is created with a border that is shown when the user
     hovers over the button.  An image can be set using the cdata
     property.

     If PARENT is omitted then a uitoggletool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uitoggletool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uitoggletool object.

     The full list of properties is documented at *note Uitoggletool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoggletool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add uitoggletool button to toolbar
          b = uitoggletool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uipushtool: XREFuipushtool.


File: octave.info,  Node: GUI Utility Functions,  Next: User-Defined Preferences,  Prev: UI Elements,  Up: GUI Development

35.4 GUI Utility Functions
==========================

These functions do not implement a GUI element but are useful when
developing programs that do.  The functions ‘uiwait’, ‘uiresume’, and
‘waitfor’ are only available with the ‘qt’ or ‘fltk’ toolkits.

 -- : DATA = guidata (H)
 -- : guidata (H, DATA)
     Query or set user-custom GUI data.

     The GUI data is stored in the figure handle H.  If H is not a
     figure handle then it's parent figure will be used for storage.

     DATA must be a single object which means it is usually preferable
     for it to be a data container such as a cell array or struct so
     that additional data items can be added easily.

     See also: *note getappdata: XREFgetappdata, *note setappdata:
     XREFsetappdata, *note get: XREFget, *note set: XREFset, *note
     getpref: XREFgetpref, *note setpref: XREFsetpref.

 -- : HDATA = guihandles (H)
 -- : HDATA = guihandles
     Return a structure of object handles for the figure associated with
     handle H.

     If no handle is specified the current figure returned by ‘gcf’ is
     used.

     The fieldname for each entry of HDATA is taken from the "tag"
     property of the graphic object.  If the tag is empty then the
     handle is not returned.  If there are multiple graphic objects with
     the same tag then the entry in HDATA will be a vector of handles.
     ‘guihandles’ includes all possible handles, including those for
     which "HandleVisibility" is "off".

     See also: *note guidata: XREFguidata, *note findobj: XREFfindobj,
     *note findall: XREFfindall, *note allchild: XREFallchild.

 -- : TF = have_window_system ()
     Return true if a window system is available (X11, Windows, or Apple
     OS X) and false otherwise.

     See also: *note isguirunning: XREFisguirunning.

 -- : TF = isguirunning ()
     Return true if Octave is running in GUI mode and false otherwise.

     See also: *note have_window_system: XREFhave_window_system.

 -- : POS = getpixelposition (H)
 -- : POS = getpixelposition (H, REL_TO_FIG)
     Return the position of a user interface component in pixel units.

     The first argument H must be a handle to a valid graphics object of
     type uibuttongroup, uicontrol, uipanel, uitable, axes, or figure.
     For other object types, the function returns zeros.

     By default, the position is returned relative to the object's
     parent.  If the second argument REL_TO_FIG is logically true, the
     position is computed relative to the enclosing figure object.

     The return value POS is a 4-element vector with values
     ‘[lower_left_X, lower_left_Y, width, height]’.

     See also: *note get: XREFget.

 -- : fonts = listfonts ()
 -- : fonts = listfonts (H)
     List system fonts.

     If a handle to a graphics object H is provided, also include the
     font from the object's "FontName" property in the list.

     Programming Note: On systems that don't use FontConfig natively
     (all but Linux), the font cache is built when Octave is installed.
     You will need to run ‘system ("fc-cache -fv")’ manually after
     installing new fonts.

     See also: *note uisetfont: XREFuisetfont, *note text: XREFtext,
     *note axes: XREFaxes, *note uicontrol: XREFuicontrol.

 -- : movegui
 -- : movegui (H)
 -- : movegui (POS)
 -- : movegui (H, POS)
 -- : movegui (H, EVENT)
 -- : movegui (H, EVENT, POS)
     Move a figure specified by figure handle H to a position on the
     screen defined by POS.

     H is a figure handle, or a handle to a graphics object.  In the
     latter case, its parent figure will be used.  If unspecified, H
     will be set to the handle of the relevant figure if a callback is
     being executed (‘gcbf’), otherwise it will be set to the handle of
     the current figure (‘gcf’).

     POS is either a two-value numeric vector or a string.  If POS is
     numeric then it must be of the form ‘[h, v]’ specifying the
     horizontal and vertical offsets of the figure with respect to the
     screen.  A positive value indicates the offset between the left (or
     bottom for the vertical component) of the screen, and the left (or
     bottom) of the figure.  A negative value indicates the offset
     between the right (or top) of the screen and the right (or top) of
     the figure.

     Possible values for POS as a string are

     ‘north’
          Top center of the screen.

     ‘south’
          Bottom center of the screen.

     ‘east’
          Right center of the screen.

     ‘west’
          Left center of the screen.

     ‘northeast’
          Top right of the screen.

     ‘northwest’
          Top left of the screen.

     ‘southeast’
          Bottom right of the screen.

     ‘southwest’
          Bottom left of the screen.

     ‘center’
          Center of the screen.

     ‘onscreen (default)’
          The figure will be minimally moved to be entirely visible on
          the screen, with a 30 pixel extra padding from the sides of
          the screen.  This is the default value if none is provided.

     EVENT contains event data that will be ignored.  This construct
     facilitates a call to movegui from a callback.

 -- : openvar (NAME)
     Open the variable NAME in the graphical Variable Editor.

 -- : uiwait
 -- : uiwait (H)
 -- : uiwait (H, TIMEOUT)
     Suspend program execution until the figure with handle H is deleted
     or ‘uiresume’ is called.

     When no figure handle is specified this function uses the current
     figure.  If the figure handle is invalid or there is no current
     figure, this functions returns immediately.

     When specified, TIMEOUT defines the number of seconds to wait for
     the figure deletion or the ‘uiresume’ call.  The timeout value must
     be at least 1.  If a smaller value is specified, a warning is
     issued and a timeout value of 1 is used instead.  If a non-integer
     value is specified, it is truncated towards 0.  If TIMEOUT is not
     specified, the program execution is suspended indefinitely.

     See also: *note uiresume: XREFuiresume, *note waitfor: XREFwaitfor.

 -- : uiresume (H)
     Resume program execution suspended with ‘uiwait’.

     The handle H must be the same as the on specified in ‘uiwait’.  If
     the handle is invalid or there is no ‘uiwait’ call pending for the
     figure with handle H, this function does nothing.

     See also: *note uiwait: XREFuiwait.

 -- : waitfor (H)
 -- : waitfor (H, PROP)
 -- : waitfor (H, PROP, VALUE)
 -- : waitfor (..., "timeout", TIMEOUT)
     Suspend the execution of the current program until a condition is
     satisfied on the graphics handle H.

     While the program is suspended graphics events are still processed
     normally, allowing callbacks to modify the state of graphics
     objects.  This function is reentrant and can be called from a
     callback, while another ‘waitfor’ call is pending at the top-level.

     In the first form, program execution is suspended until the
     graphics object H is destroyed.  If the graphics handle is invalid
     or if H is the root graphics handle and no property PROP was
     provided, the function returns immediately.

     In the second form, execution is suspended until the graphics
     object is destroyed or the property named PROP is modified.  If the
     graphics handle is invalid or the property does not exist, the
     function returns immediately.

     In the third form, execution is suspended until the graphics object
     is destroyed or the property named PROP is set to VALUE.  The
     function ‘isequal’ is used to compare property values.  If the
     graphics handle is invalid, the property does not exist or the
     property is already set to VALUE, the function returns immediately.

     An optional timeout can be specified using the property "timeout".
     This timeout value is the number of seconds to wait for the
     condition to be true.  TIMEOUT must be at least 1.  If a smaller
     value is specified, a warning is issued and a value of 1 is used
     instead.  If the timeout value is not an integer, it is truncated
     towards 0.

     To define a condition on a property named "timeout", use the string
     '\timeout' instead.

     In all cases, typing CTRL-C stops program execution immediately.

     See also: *note waitforbuttonpress: XREFwaitforbuttonpress, *note
     isequal: XREFisequal.


File: octave.info,  Node: User-Defined Preferences,  Next: Octave Workspace Windows,  Prev: GUI Utility Functions,  Up: GUI Development

35.5 User-Defined Preferences
=============================

 -- : VAL = getpref ("GROUP", "PREF")
 -- : VAL = getpref ("GROUP", "PREF", DEFAULT)
 -- : {VAL1, VAL2, ...} = getpref ("GROUP", {"PREF1", "PREF2", ...})
 -- : PREFSTRUCT = getpref ("GROUP")
 -- : PREFSTRUCT = getpref ()
     Return the preference value corresponding to the named preference
     PREF in the preference group GROUP.

     The named preference group must be a string.

     If PREF does not exist in GROUP and DEFAULT is specified, create
     the preference with value DEFAULT and return DEFAULT.

     The preference PREF may be a string or cell array of strings.  If
     it is a cell array of strings then a cell array of preferences is
     returned.

     The corresponding default value DEFAULT may be any Octave value,
     .e.g., double, struct, cell array, object, etc.  Or, if PREF is a
     cell array of strings then DEFAULT must be a cell array of values
     with the same size as PREF.

     If neither PREF nor DEFAULT are specified, return a structure of
     preferences for the preference group GROUP.

     If no arguments are specified, return a structure containing all
     groups of preferences and their values.

     See also: *note addpref: XREFaddpref, *note setpref: XREFsetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- : setpref ("GROUP", "PREF", VAL)
 -- : setpref ("GROUP", {"PREF1", "PREF2", ...}, {VAL1, VAL2, ...})
     Set the preference PREF to the given VAL in the named preference
     group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or a cell array of strings.

     The corresponding value VAL may be any Octave value, .e.g., double,
     struct, cell array, object, etc.  Or, if PREF is a cell array of
     strings then VAL must be a cell array of values with the same size
     as PREF.

     If the named preference or group does not exist, it is added.

     See also: *note addpref: XREFaddpref, *note getpref: XREFgetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- : addpref ("GROUP", "PREF", VAL)
 -- : addpref ("GROUP", {"PREF1", "PREF2", ...}, {VAL1, VAL2, ...})
     Add the preference PREF and associated value VAL to the named
     preference group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or a cell array of strings.  An
     error will be issued if the preference already exists.

     The corresponding value VAL may be any Octave value, .e.g., double,
     struct, cell array, object, etc.  Or, if PREF is a cell array of
     strings then VAL must be a cell array of values with the same size
     as PREF.

     See also: *note setpref: XREFsetpref, *note getpref: XREFgetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- : rmpref ("GROUP", "PREF")
 -- : rmpref ("GROUP", {"PREF1", "PREF2", ...})
 -- : rmpref ("GROUP")
     Remove the named preference PREF from the preference group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or cell array of strings.

     If PREF is not specified, remove the preference group GROUP.

     It is an error to remove a nonexistent preference or group.

     See also: *note addpref: XREFaddpref, *note ispref: XREFispref,
     *note setpref: XREFsetpref, *note getpref: XREFgetpref.

 -- : TF = ispref ("GROUP", "PREF")
 -- : TF = ispref ("GROUP", {"PREF1", "PREF2", ...})
 -- : TF = ispref ("GROUP")
     Return true if the named preference PREF exists in the preference
     group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or a cell array of strings.

     If PREF is not specified, return true if the preference group GROUP
     exists.

     See also: *note getpref: XREFgetpref, *note addpref: XREFaddpref,
     *note setpref: XREFsetpref, *note rmpref: XREFrmpref.

 -- : DIR = prefdir
 -- : DIR = prefdir (1)
     Return the directory that holds the preferences for Octave.

     Examples:

     Display the preferences directory

          prefdir

     Change to the preferences folder

          cd (prefdir)

     If called with an argument, the preferences directory is created if
     it doesn't already exist.

     See also: *note getpref: XREFgetpref, *note setpref: XREFsetpref,
     *note addpref: XREFaddpref, *note rmpref: XREFrmpref, *note ispref:
     XREFispref.

 -- : preferences
     Display the GUI preferences dialog window for Octave.


File: octave.info,  Node: Octave Workspace Windows,  Prev: User-Defined Preferences,  Up: GUI Development

35.6 Octave Workspace Windows
=============================

The functions below make windows that are a part of Octave's own GUI
interface visible, and move the keyboard focus to the selected window.
Their utility lies in the ability to call these functions from a script
and highlight a window without using a mouse for selection.

 -- : commandhistory ()
     Show the GUI command history window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     filebrowser: XREFfilebrowser, *note workspace: XREFworkspace.

 -- : commandwindow ()
     Show the GUI command window and give it the keyboard focus.

     See also: *note commandhistory: XREFcommandhistory, *note
     filebrowser: XREFfilebrowser, *note workspace: XREFworkspace.

 -- : filebrowser ()
     Show the GUI file browser window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     commandhistory: XREFcommandhistory, *note workspace: XREFworkspace.

 -- : workspace ()
     Show the GUI workspace window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     commandhistory: XREFcommandhistory, *note filebrowser:
     XREFfilebrowser.


File: octave.info,  Node: System Utilities,  Next: Packages,  Prev: GUI Development,  Up: Top

36 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

36.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-60).  This number can be 60 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 saving time flag.

‘gmtoff’
     Seconds offset from UTC.

‘zone’
     Time zone.

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

 -- : SECONDS = time ()
     Return the current time as the number of seconds since the epoch.

     The epoch is referenced to 00:00:00 UTC (Coordinated Universal
     Time) 1 Jan 1970.  For example, on Monday February 17, 1997 at
     07:15:06 UTC, the value returned by ‘time’ was 856163706.

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note gmtime:
     XREFgmtime, *note mktime: XREFmktime, *note now: XREFnow, *note
     date: XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum,
     *note datestr: XREFdatestr, *note datevec: XREFdatevec, *note
     calendar: XREFcalendar, *note weekday: XREFweekday.

 -- : t = now ()
     Return the current local date/time as a serial day number (*note
     ‘datenum’: XREFdatenum.).

     The integral part, ‘floor (now)’ corresponds to the number of days
     between today and Jan 1, 0000.

     The fractional part, ‘rem (now, 1)’ corresponds to the current
     time.

     See also: *note clock: XREFclock, *note date: XREFdate, *note
     datenum: XREFdatenum.

 -- : STR = 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"

     See also: *note asctime: XREFasctime, *note time: XREFtime, *note
     localtime: XREFlocaltime.

 -- : TM_STRUCT = gmtime (T)
     Given a value returned from ‘time’, or any non-negative integer,
     return a time structure corresponding to UTC (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
                     gmtoff = 0
                     zone = GMT
                  }

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note mktime:
     XREFmktime, *note time: XREFtime, *note now: XREFnow, *note date:
     XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum, *note
     datestr: XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- : 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
                     gmtoff = -21600
                     zone = CST
                  }

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- : 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: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note gmtime:
     XREFgmtime, *note time: XREFtime, *note now: XREFnow, *note date:
     XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum, *note
     datestr: XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- : STR = asctime (TM_STRUCT)
     Convert a time structure to a string using the following format:
     "ddd mmm mm HH:MM:SS yyyy\n".

     For example:

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

     This is equivalent to ‘ctime (time ())’.

     See also: *note ctime: XREFctime, *note localtime: XREFlocaltime,
     *note time: XREFtime.

 -- : STR = 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’
          Offset from UTC (±hhmm), or nothing if no time zone is
          determinable.

     ‘%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: XREFstrptime, *note localtime:
     XREFlocaltime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- : [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: XREFstrftime, *note localtime:
     XREFlocaltime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

   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.

 -- : DATEVEC = clock ()
 -- : [DATEVEC, ISDST] = clock ()
     Return the current local date and time as a date vector.

     The date vector contains the following fields: current year, month
     (1-12), day (1-31), hour (0-23), minute (0-59), and second (0-61).
     The seconds field has a fractional part after the decimal point for
     extended accuracy.

     The optional second output ISDST is true if Daylight Savings Time
     (DST) is in effect for the system's time zone.

     For example:

          fix (clock ())
            ⇒   1993      8     20      4     56      1

     ‘clock’ is more accurate on systems that have the ‘gettimeofday’
     function.

     See also: *note now: XREFnow, *note date: XREFdate, *note datevec:
     XREFdatevec.

 -- : STR = date ()
     Return the current date as a character string in the form
     DD-MMM-YYYY.

     For example:

          date ()
            ⇒ 20-Aug-1993

     See also: *note now: XREFnow, *note clock: XREFclock, *note
     datestr: XREFdatestr, *note localtime: XREFlocaltime.

 -- : SECS = 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: XREFtic, *note toc: XREFtoc, *note clock:
     XREFclock, *note cputime: XREFcputime, *note addtodate:
     XREFaddtodate.

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

     See also: *note tic: XREFtic, *note toc: XREFtoc.

 -- : TF = is_leap_year ()
 -- : TF = is_leap_year (YEAR)
     Return true if YEAR is a leap year and false otherwise.

     If no year is specified, ‘is_leap_year’ uses the current year.

     For example:

          is_leap_year (2000)
             ⇒ 1

     See also: *note weekday: XREFweekday, *note eomday: XREFeomday,
     *note calendar: XREFcalendar.

 -- : tic ()
 -- : ID = tic ()
     Initialize a wall-clock timer.

     Calling ‘tic’ without an output argument resets the internal timer.
     Subsequent calls to ‘toc’ return the number of seconds since the
     timer was set.

     If called with one output argument, ‘tic’ creates a new timer
     instance and returns a timer identifier ID.  The ID is a scalar of
     type ‘uint64’ that may be passed to ‘toc’ to check elapsed time on
     this timer, rather than the default internal timer.

     Example 1 : benchmarking code with internal timer

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

     Example 2 : mixed timer id and internal timer

          tic;
          pause (1);
          toc
          ⇒ Elapsed time is 1.0089 seconds.
          id = tic;
          pause (2);
          toc (id)
          ⇒ Elapsed time is 2.01142 seconds.
          toc
          Elapsed time is 3.02308 seconds.

     Calling ‘tic’ and ‘toc’ in this way allows nested timing calls.

     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.

     See also: *note toc: XREFtoc, *note cputime: XREFcputime.

 -- : toc ()
 -- : toc (ID)
 -- : ELAPSED_TIME = toc (...)
     Measure elapsed time on a wall-clock timer.

     With no arguments, return the number of seconds elapsed on the
     internal timer since the last call to ‘tic’.

     When given the identifier ID of a specific timer, return the number
     of seconds elapsed since the timer ID was initialized.

     *Note ‘tic’: XREFtic, for examples of the use of ‘tic’/‘toc’.

     See also: *note tic: XREFtic, *note cputime: XREFcputime.

 -- : pause ()
 -- : pause (N)
 -- : OLD_STATE = pause ("on")
 -- : OLD_STATE = pause ("off")
 -- : OLD_STATE = pause ("query")
     Suspend the execution of the program or change the state of the
     pause function.

     If invoked without an input arguments then the program is suspended
     until a character is typed.  If argument N is a positive real
     value, it indicates the number of seconds the program shall be
     suspended, for example:

          tic; pause (0.05); toc
               ⊣ Elapsed time is 0.05039 seconds.

     The following example prints a message and then waits 5 seconds
     before clearing the screen.

          disp ("wait please...");
          pause (5);
          clc;

     If invoked with a string argument "on", "off", or "query", the
     state of the pause function is changed or queried.  When the state
     is "off", the pause function returns immediately.  The optional
     return value contains the previous state of the pause function.  In
     the following example pause is disabled locally:

          old_state = pause ("off");
          tic; pause (0.05); toc
               ⊣ Elapsed time is 3.00407e-05 seconds.
          pause (old_state);

     While the program is suspended Octave still handles figures
     painting and graphics callbacks execution.

     See also: *note kbhit: XREFkbhit.

 -- : DAYS = datenum (DATEVEC)
 -- : DAYS = datenum (YEAR, MONTH, DAY)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND)
 -- : DAYS = datenum ("datestr")
 -- : DAYS = datenum ("datestr", F)
 -- : DAYS = datenum ("datestr", P)
 -- : [DAYS, SECS] = datenum (...)
     Return the date/time input as a serial day number, with Jan 1, 0000
     defined as day 1.

     The integer part, ‘floor (DAYS)’ counts the number of complete days
     in the date input.

     The fractional part, ‘rem (DAYS, 1)’ corresponds to the time on the
     given day.

     The input may be a date vector (*note ‘datevec’: XREFdatevec.),
     date string (*note ‘datestr’: XREFdatestr.), or directly specified
     as input.

     When processing input datestrings, F is the format string used to
     interpret date strings (*note ‘datestr’: XREFdatestr.).  If no
     format F is specified, then a relatively slow search is performed
     through various formats.  It is always preferable to specify the
     format string F if it is known.  Formats which do not specify a
     particular time component will have the value set to zero.  Formats
     which do not specify a date will default to January 1st of the
     current year.

     When passing separate YEAR, MONTH, DAY, etc. arguments, each may be
     a scalar or nonscalar array.  Nonscalar inputs must all be of the
     same size.  Scalar inputs will be expanded to be the size of the
     nonscalar inputs.

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

     The optional output SECS holds the time on the specified day with
     greater precision than DAYS.

     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.

     Examples:

          Convert from datestrs:
          d = datenum ("1966-06-14")
          ⇒ d = 718232

          d = datenum ({"1966-06-14", "1966-06-15", "1966-06-16"})
          ⇒ d =
                718232
                718233
                718234

          Convert from datevec:
          d = datenum ([1966 06 14])
          ⇒ d = 718232

          d = datenum ([1966 06 14 23 59 59])
          ⇒ d = 718232.9999884259

          Specify date components separately:
          d = datenum (1966, 6, 14)
          ⇒ d = 718232

          d = datenum (1966, magic(3), 1)
          ⇒ d =

                718280   718068   718219
                718127   718188   718249
                718158   718311   718099

     *Caution:* datenums represent a specific time for the Earth as a
     whole.  They do not take in to account time zones (shifts in time
     based on location), nor seasonal changes due to Daylight Savings
     Time (shifts in time based on local regulation).  Be aware that it
     is possible to create datenums that, when interpreted by a function
     which accounts for time zone and DST shifts such as ‘datestr’, are
     nonexistent or ambiguous.

     *Caution:* this function does not attempt to handle Julian
     calendars so dates before October 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 datestr: XREFdatestr, *note datevec: XREFdatevec,
     *note now: XREFnow, *note clock: XREFclock, *note date: XREFdate.

   Algorithm: Peter Baum (http://vsg.cape.com/~pbaum/date/date0.htm)

 -- : STR = datestr (DATE)
 -- : STR = datestr (DATE, F)
 -- : 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 (*note ‘datenum’: XREFdatenum.), a
     date vector (*note ‘datevec’: XREFdatevec.), or a string or cell
     array of strings.  In the latter case, it is passed to ‘datevec’ to
     guess the input date format.

     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                      3:38:09 PM
     15      HH:MM                            15:38
     16      HH:MM PM                         3:38 PM
     17      QQ-YY                            Q3-00
     18      QQ                               Q3
     19      dd/mm                            07/09
     20      dd/mm/yy                         07/09/00
     21      mmm.dd,yyyy HH:MM:SS             Sep.07,2000 15:38:08
     22      mmm.dd,yyyy                      Sep.07,2000
     23      mm/dd/yyyy                       09/07/2000
     24      dd/mm/yyyy                       07/09/2000
     25      yy/mm/dd                         00/09/07
     26      yyyy/mm/dd                       2000/09/07
     27      QQ-YYYY                          Q3-2000
     28      mmmyyyy                          Sep2000
     29      yyyy-mm-dd                       2000-09-07
     30      yyyymmddTHHMMSS                  20000907T153808
     31      yyyy-mm-dd HH:MM:SS              2000-09-07 15:38:08

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

     Symbol  Meaning                                            Example
     --------------------------------------------------------------------------
     yyyy    Full year                                          2005
     yy      Two-digit year                                     05
     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,                    09:00
             or padded with spaces if PM is set                 9:00 AM
     MM      Minute of hour (padded with zeros)                 10:05
     SS      Second of minute (padded with zeros)               10:05:03
     FFF     Milliseconds of second (padded with zeros)         10:05:03.012
     AM      Use 12-hour time format                            11:30 AM
     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 not specified, it defaults to the current year minus 50.

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

     See also: *note datenum: XREFdatenum, *note datevec: XREFdatevec,
     *note date: XREFdate, *note now: XREFnow, *note clock: XREFclock.

 -- : V = datevec (DATE)
 -- : V = datevec (DATE, F)
 -- : V = datevec (DATE, P)
 -- : V = datevec (DATE, F, P)
 -- : [Y, M, D, H, MI, S] = datevec (...)
     Convert a serial date number (*note ‘datenum’: XREFdatenum.) or
     date string (*note ‘datestr’: XREFdatestr.) into a date vector.

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

     Date number inputs can be either a scalar or nonscalar array.  Date
     string inputs can be either a single date string, a two-dimensional
     character array of dates with each row being a date string, or a
     cell string array of any dimension with each cell element
     containing a single date string.

     V is a two-dimensional array of date vectors, one date vector per
     row.  For array inputs, ordering of V is based on column major
     order of dates in DATA.

     F is the format string used to interpret date strings (*note
     ‘datestr’: XREFdatestr.).  If DATE is a string or a cell array of
     strings, but no format is specified, heuristics are used to guess
     the input format.  These heuristics could lead to matches that
     differ from the result a user might expect.  Additionally, this
     involves a relatively slow search through various formats.  It is
     always preferable to specify the format string F if it is known.
     Formats which do not specify a particular time component will have
     the value set to zero.  Formats which do not specify a particular
     date component will default that component to January 1st of the
     current year.  Trailing characters are ignored for the purpose of
     calculating the date vector, even if the characters contain
     additional time/date information.

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

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr,
     *note clock: XREFclock, *note now: XREFnow, *note date: XREFdate.

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

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

     See also: *note datenum: XREFdatenum, *note datevec: XREFdatevec,
     *note etime: XREFetime.

 -- : C = calendar ()
 -- : C = calendar (D)
 -- : C = calendar (Y, M)
 -- : calendar (...)
     Return the current monthly calendar in a 6x7 matrix.

     If D is specified, return the calendar for the month containing the
     date 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: XREFdatenum, *note datestr: XREFdatestr.

 -- : [N, S] = weekday (D)
 -- : [N, S] = weekday (D, FORMAT)
     Return the day of the week as a number in N and as a string in S.

     The days of the week are numbered 1-7 with the first day being
     Sunday.

     D is a serial date number or a date string.

     If the string FORMAT is not present or is equal to "short" then S
     will contain the abbreviated name of the weekday.  If FORMAT is
     "long" then S will contain the full name.

     Table of return values based on FORMAT:

     N    "short"   "long"
     ----------------------------
     1    Sun       Sunday
     2    Mon       Monday
     3    Tue       Tuesday
     4    Wed       Wednesday
     5    Thu       Thursday
     6    Fri       Friday
     7    Sat       Saturday

     See also: *note eomday: XREFeomday, *note is_leap_year:
     XREFis_leap_year, *note calendar: XREFcalendar, *note datenum:
     XREFdatenum, *note datevec: XREFdatevec.

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

     See also: *note weekday: XREFweekday, *note datenum: XREFdatenum,
     *note datevec: XREFdatevec, *note is_leap_year: XREFis_leap_year,
     *note calendar: XREFcalendar.

 -- : datetick ()
 -- : datetick (AXIS_STR)
 -- : datetick (DATE_FORMAT)
 -- : datetick (AXIS_STR, DATE_FORMAT)
 -- : datetick (..., "keeplimits")
 -- : datetick (..., "keepticks")
 -- : datetick (HAX, ...)
     Add date-formatted tick labels to an axis.

     The axis to apply the ticks to is determined by AXIS_STR which can
     take the values "x", "y", or "z".  The default value is "x".

     The formatting of the labels is determined by the variable
     DATE_FORMAT, which can either be a string or positive integer that
     ‘datestr’ accepts.

     If the first argument HAX is an axes handle, then plot into this
     axes, rather than the current axes returned by ‘gca’.

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr.

