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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996-2013 John W. Eaton.

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

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

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


File: octave.info,  Node: Finding Roots,  Next: Products of Polynomials,  Prev: Evaluating Polynomials,  Up: Polynomial Manipulations

28.2 Finding Roots
==================

Octave can find the roots of a given polynomial.  This is done by
computing the companion matrix of the polynomial (see the 'compan'
function for a definition), and then finding its eigenvalues.

 -- Function File: roots (V)

     For a vector V with N components, return the roots of the
     polynomial

          v(1) * z^(N-1) + ... + v(N-1) * z + v(N)

     As an example, the following code finds the roots of the quadratic
     polynomial

          p(x) = x^2 - 5.

          c = [1, 0, -5];
          roots (c)
          =>  2.2361
          => -2.2361

     Note that the true result is +/- sqrt(5) which is roughly +/-
     2.2361.

     See also: *note poly: XREFpoly, *note compan: XREFcompan, *note
     fzero: XREFfzero.

 -- Function File: Z = polyeig (C0, C1, ..., CL)
 -- Function File: [V, Z] = polyeig (C0, C1, ..., CL)

     Solve the polynomial eigenvalue problem of degree L.

     Given an N*N matrix polynomial 'C(s) = C0 + C1 s + ... + CL s^l'
     polyeig solves the eigenvalue problem '(C0 + C1 + ... + CL)v = 0'.

     Note that the eigenvalues Z are the zeros of the matrix polynomial.
     Z is a row vector with N*L elements.  V is a matrix (N x N*L) with
     columns that correspond to the eigenvectors.

     See also: *note eig: XREFeig, *note eigs: XREFeigs, *note compan:
     XREFcompan.

 -- Function File: compan (C)
     Compute the companion matrix corresponding to polynomial
     coefficient vector C.

     The companion matrix is

               _                                                        _
              |  -c(2)/c(1)   -c(3)/c(1)  ...  -c(N)/c(1)  -c(N+1)/c(1)  |
              |       1            0      ...       0             0      |
              |       0            1      ...       0             0      |
          A = |       .            .      .         .             .      |
              |       .            .       .        .             .      |
              |       .            .        .       .             .      |
              |_      0            0      ...       1             0     _|

     The eigenvalues of the companion matrix are equal to the roots of
     the polynomial.

     See also: *note roots: XREFroots, *note poly: XREFpoly, *note eig:
     XREFeig.

 -- Function File: [MULTP, IDXP] = mpoles (P)
 -- Function File: [MULTP, IDXP] = mpoles (P, TOL)
 -- Function File: [MULTP, IDXP] = mpoles (P, TOL, REORDER)
     Identify unique poles in P and their associated multiplicity.  The
     output is ordered from largest pole to smallest pole.

     If the relative difference of two poles is less than TOL then they
     are considered to be multiples.  The default value for TOL is
     0.001.

     If the optional parameter REORDER is zero, poles are not sorted.

     The output MULTP is a vector specifying the multiplicity of the
     poles.  'MULTP(n)' refers to the multiplicity of the Nth pole
     'P(IDXP(n))'.

     For example:

          p = [2 3 1 1 2];
          [m, n] = mpoles (p)
             => m = [1; 1; 2; 1; 2]
             => n = [2; 5; 1; 4; 3]
             => p(n) = [3, 2, 2, 1, 1]

     See also: *note residue: XREFresidue, *note poly: XREFpoly, *note
     roots: XREFroots, *note conv: XREFconv, *note deconv: XREFdeconv.


File: octave.info,  Node: Products of Polynomials,  Next: Derivatives / Integrals / Transforms,  Prev: Finding Roots,  Up: Polynomial Manipulations

28.3 Products of Polynomials
============================

 -- Function File: conv (A, B)
 -- Function File: conv (A, B, SHAPE)
     Convolve two vectors A and B.

     The output convolution is a vector with length equal to 'length (A)
     + length (B) - 1'.  When A and B are the coefficient vectors of two
     polynomials, the convolution represents the coefficient vector of
     the product polynomial.

     The optional SHAPE argument may be

     SHAPE = "full"
          Return the full convolution.  (default)

     SHAPE = "same"
          Return the central part of the convolution with the same size
          as A.

     See also: *note deconv: XREFdeconv, *note conv2: XREFconv2, *note
     convn: XREFconvn, *note fftconv: XREFfftconv.

 -- Built-in Function: C = convn (A, B)
 -- Built-in Function: C = convn (A, B, SHAPE)
     Return the n-D convolution of A and B.  The size of the result is
     determined by the optional SHAPE argument which takes the following
     values

     SHAPE = "full"
          Return the full convolution.  (default)

     SHAPE = "same"
          Return central part of the convolution with the same size as
          A.  The central part of the convolution begins at the indices
          'floor ([size(B)/2] + 1)'.

     SHAPE = "valid"
          Return only the parts which do not include zero-padded edges.
          The size of the result is 'max (size (A) - size (B) + 1, 0)'.

     See also: *note conv2: XREFconv2, *note conv: XREFconv.

 -- Function File: deconv (Y, A)
     Deconvolve two vectors.

     '[b, r] = deconv (y, a)' solves for B and R such that 'y = conv (a,
     b) + r'.

     If Y and A are polynomial coefficient vectors, B will contain the
     coefficients of the polynomial quotient and R will be a remainder
     polynomial of lowest order.

     See also: *note conv: XREFconv, *note residue: XREFresidue.

 -- Built-in Function: conv2 (A, B)
 -- Built-in Function: conv2 (V1, V2, M)
 -- Built-in Function: conv2 (..., SHAPE)
     Return the 2-D convolution of A and B.  The size of the result is
     determined by the optional SHAPE argument which takes the following
     values

     SHAPE = "full"
          Return the full convolution.  (default)

     SHAPE = "same"
          Return the central part of the convolution with the same size
          as A.  The central part of the convolution begins at the
          indices 'floor ([size(B)/2] + 1)'.

     SHAPE = "valid"
          Return only the parts which do not include zero-padded edges.
          The size of the result is 'max (size (A) - size (B) + 1, 0)'.

     When the third argument is a matrix, return the convolution of the
     matrix M by the vector V1 in the column direction and by the vector
     V2 in the row direction.

     See also: *note conv: XREFconv, *note convn: XREFconvn.

 -- Function File: Q = polygcd (B, A)
 -- Function File: Q = polygcd (B, A, TOL)

     Find the greatest common divisor of two polynomials.  This is
     equivalent to the polynomial found by multiplying together all the
     common roots.  Together with deconv, you can reduce a ratio of two
     polynomials.  The tolerance TOL defaults to 'sqrt (eps)'.

     *Caution:* This is a numerically unstable algorithm and should not
     be used on large polynomials.

     Example code:

          polygcd (poly (1:8), poly (3:12)) - poly (3:8)
          => [ 0, 0, 0, 0, 0, 0, 0 ]
          deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))) - poly (1:2)
          => [ 0, 0, 0 ]

     See also: *note poly: XREFpoly, *note roots: XREFroots, *note conv:
     XREFconv, *note deconv: XREFdeconv, *note residue: XREFresidue.

 -- Function File: [R, P, K, E] = residue (B, A)
 -- Function File: [B, A] = residue (R, P, K)
 -- Function File: [B, A] = residue (R, P, K, E)
     The first calling form computes the partial fraction expansion for
     the quotient of the polynomials, B and A.

          B(s)    M       r(m)         N
          ---- = SUM -------------  + SUM k(i)*s^(N-i)
          A(s)   m=1 (s-p(m))^e(m)    i=1

     where M is the number of poles (the length of the R, P, and E), the
     K vector is a polynomial of order N-1 representing the direct
     contribution, and the E vector specifies the multiplicity of the
     m-th residue's pole.

     For example,

          b = [1, 1, 1];
          a = [1, -5, 8, -4];
          [r, p, k, e] = residue (b, a)
             => r = [-2; 7; 3]
             => p = [2; 2; 1]
             => k = [](0x0)
             => e = [1; 2; 1]

     which represents the following partial fraction expansion

                  s^2 + s + 1       -2        7        3
             ------------------- = ----- + ------- + -----
             s^3 - 5s^2 + 8s - 4   (s-2)   (s-2)^2   (s-1)

     The second calling form performs the inverse operation and computes
     the reconstituted quotient of polynomials, B(s)/A(s), from the
     partial fraction expansion; represented by the residues, poles, and
     a direct polynomial specified by R, P and K, and the pole
     multiplicity E.

     If the multiplicity, E, is not explicitly specified the
     multiplicity is determined by the function 'mpoles'.

     For example:

          r = [-2; 7; 3];
          p = [2; 2; 1];
          k = [1, 0];
          [b, a] = residue (r, p, k)
             => b = [1, -5, 9, -3, 1]
             => a = [1, -5, 8, -4]

          where mpoles is used to determine e = [1; 2; 1]

     Alternatively the multiplicity may be defined explicitly, for
     example,

          r = [7; 3; -2];
          p = [2; 1; 2];
          k = [1, 0];
          e = [2; 1; 1];
          [b, a] = residue (r, p, k, e)
             => b = [1, -5, 9, -3, 1]
             => a = [1, -5, 8, -4]

     which represents the following partial fraction expansion

           -2        7        3         s^4 - 5s^3 + 9s^2 - 3s + 1
          ----- + ------- + ----- + s = --------------------------
          (s-2)   (s-2)^2   (s-1)          s^3 - 5s^2 + 8s - 4

     See also: *note mpoles: XREFmpoles, *note poly: XREFpoly, *note
     roots: XREFroots, *note conv: XREFconv, *note deconv: XREFdeconv.


File: octave.info,  Node: Derivatives / Integrals / Transforms,  Next: Polynomial Interpolation,  Prev: Products of Polynomials,  Up: Polynomial Manipulations

28.4 Derivatives / Integrals / Transforms
=========================================

Octave comes with functions for computing the derivative and the
integral of a polynomial.  The functions 'polyder' and 'polyint' both
return new polynomials describing the result.  As an example we'll
compute the definite integral of p(x) = x^2 + 1 from 0 to 3.

     c = [1, 0, 1];
     integral = polyint (c);
     area = polyval (integral, 3) - polyval (integral, 0)
     => 12

 -- Function File: polyder (P)
 -- Function File: [K] = polyder (A, B)
 -- Function File: [Q, D] = polyder (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by the vector P.  If a pair of polynomials
     is given, return the derivative of the product A*B.  If two inputs
     and two outputs are given, return the derivative of the polynomial
     quotient B/A.  The quotient numerator is in Q and the denominator
     in D.

     See also: *note polyint: XREFpolyint, *note polyval: XREFpolyval,
     *note polyreduce: XREFpolyreduce.

 -- Function File: polyint (P)
 -- Function File: polyint (P, K)
     Return the coefficients of the integral of the polynomial whose
     coefficients are represented by the vector P.  The variable K is
     the constant of integration, which by default is set to zero.

     See also: *note polyder: XREFpolyder, *note polyval: XREFpolyval.

 -- Function File: polyaffine (F, MU)
     Return the coefficients of the polynomial vector F after an affine
     transformation.  If F is the vector representing the polynomial
     f(x), then 'G = polyaffine (F, MU)' is the vector representing:

          g(x) = f( (x - MU(1)) / MU(2) )

     See also: *note polyval: XREFpolyval, *note polyfit: XREFpolyfit.


File: octave.info,  Node: Polynomial Interpolation,  Next: Miscellaneous Functions,  Prev: Derivatives / Integrals / Transforms,  Up: Polynomial Manipulations

28.5 Polynomial Interpolation
=============================

Octave comes with good support for various kinds of interpolation, most
of which are described in *note Interpolation::.  One simple alternative
to the functions described in the aforementioned chapter, is to fit a
single polynomial, or a piecewise polynomial (spline) to some given data
points.  To avoid a highly fluctuating polynomial, one most often wants
to fit a low-order polynomial to data.  This usually means that it is
necessary to fit the polynomial in a least-squares sense, which just is
what the 'polyfit' function does.

 -- Function File: P = polyfit (X, Y, N)
 -- Function File: [P, S] = polyfit (X, Y, N)
 -- Function File: [P, S, MU] = polyfit (X, Y, N)
     Return the coefficients of a polynomial P(X) of degree N that
     minimizes the least-squares-error of the fit to the points '[X,
     Y]'.  If N is a logical vector, it is used as a mask to selectively
     force the corresponding polynomial coefficients to be used or
     ignored.

     The polynomial coefficients are returned in a row vector.

     The optional output S is a structure containing the following
     fields:

     'R'
          Triangular factor R from the QR decomposition.

     'X'
          The Vandermonde matrix used to compute the polynomial
          coefficients.

     'C'
          The unscaled covariance matrix, formally equal to the inverse
          of X'*X, but computed in a way minimizing roundoff error
          propagation.

     'df'
          The degrees of freedom.

     'normr'
          The norm of the residuals.

     'yf'
          The values of the polynomial for each value of X.

     The second output may be used by 'polyval' to calculate the
     statistical error limits of the predicted values.  In particular,
     the standard deviation of P coefficients is given by
     'sqrt (diag (s.C)/s.df)*s.normr'.

     When the third output, MU, is present the coefficients, P, are
     associated with a polynomial in XHAT = (X-MU(1))/MU(2).  Where
     MU(1) = mean (X), and MU(2) = std (X).  This linear transformation
     of X improves the numerical stability of the fit.

     See also: *note polyval: XREFpolyval, *note polyaffine:
     XREFpolyaffine, *note roots: XREFroots, *note vander: XREFvander,
     *note zscore: XREFzscore.

   In situations where a single polynomial isn't good enough, a solution
is to use several polynomials pieced together.  The function 'splinefit'
fits a peicewise polynomial (spline) to a set of data.

 -- Function File: PP = splinefit (X, Y, BREAKS)
 -- Function File: PP = splinefit (X, Y, P)
 -- Function File: PP = splinefit (..., "periodic", PERIODIC)
 -- Function File: PP = splinefit (..., "robust", ROBUST)
 -- Function File: PP = splinefit (..., "beta", BETA)
 -- Function File: PP = splinefit (..., "order", ORDER)
 -- Function File: PP = splinefit (..., "constraints", CONSTRAINTS)

     Fit a piecewise cubic spline with breaks (knots) BREAKS to the
     noisy data, X and Y.  X is a vector, and Y is a vector or N-D
     array.  If Y is an N-D array, then X(j) is matched to Y(:,...,:,j).

     The fitted spline is returned as a piecewise polynomial, PP, and
     may be evaluated using 'ppval'.

     P is a positive integer defining the number of intervals along X,
     and P+1 is the number of breaks.  The number of points in each
     interval differ by no more than 1.

     The optional property PERIODIC is a logical value which specifies
     whether a periodic boundary condition is applied to the spline.
     The length of the period is 'max (BREAKS) - min (BREAKS)'.  The
     default value is 'false'.

     The optional property ROBUST is a logical value which specifies if
     robust fitting is to be applied to reduce the influence of outlying
     data points.  Three iterations of weighted least squares are
     performed.  Weights are computed from previous residuals.  The
     sensitivity of outlier identification is controlled by the property
     BETA.  The value of BETA is stricted to the range, 0 < BETA < 1.
     The default value is BETA = 1/2.  Values close to 0 give all data
     equal weighting.  Increasing values of BETA reduce the influence of
     outlying data.  Values close to unity may cause instability or rank
     deficiency.

     The splines are constructed of polynomials with degree ORDER.  The
     default is a cubic, ORDER=3.  A spline with P pieces has P+ORDER
     degrees of freedom.  With periodic boundary conditions the degrees
     of freedom are reduced to P.

     The optional property, CONSTAINTS, is a structure specifying linear
     constraints on the fit.  The structure has three fields, "xc",
     "yc", and "cc".

     "xc"
          Vector of the x-locations of the constraints.

     "yc"
          Constraining values at the locations XC.  The default is an
          array of zeros.

     "cc"
          Coefficients (matrix).  The default is an array of ones.  The
          number of rows is limited to the order of the piecewise
          polynomials, ORDER.

     Constraints are linear combinations of derivatives of order 0 to
     ORDER-1 according to

          cc(1,j) * y(xc(j)) + cc(2,j) * y'(xc(j)) + ... = yc(:,...,:,j).

     See also: *note interp1: XREFinterp1, *note unmkpp: XREFunmkpp,
     *note ppval: XREFppval, *note spline: XREFspline, *note pchip:
     XREFpchip, *note ppder: XREFppder, *note ppint: XREFppint, *note
     ppjumps: XREFppjumps.

   The number of BREAKS (or knots) used to construct the piecewise
polynomial is a significant factor in suppressing the noise present in
the input data, X and Y.  This is demonstrated by the example below.

     x = 2 * pi * rand (1, 200);
     y = sin (x) + sin (2 * x) + 0.2 * randn (size (x));
     ## Uniform breaks
     breaks = linspace (0, 2 * pi, 41); % 41 breaks, 40 pieces
     pp1 = splinefit (x, y, breaks);
     ## Breaks interpolated from data
     pp2 = splinefit (x, y, 10);  % 11 breaks, 10 pieces
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "41 breaks, 40 pieces", "11 breaks, 10 pieces"})

   The piecewise polynomial fit, provided by 'splinefit', has continuous
derivatives up to the ORDER-1.  For example, a cubic fit has continuous
first and second derivatives.  This is demonstrated by the code

     ## Data (200 points)
     x = 2 * pi * rand (1, 200);
     y = sin (x) + sin (2 * x) + 0.1 * randn (size (x));
     ## Piecewise constant
     pp1 = splinefit (x, y, 8, "order", 0);
     ## Piecewise linear
     pp2 = splinefit (x, y, 8, "order", 1);
     ## Piecewise quadratic
     pp3 = splinefit (x, y, 8, "order", 2);
     ## Piecewise cubic
     pp4 = splinefit (x, y, 8, "order", 3);
     ## Piecewise quartic
     pp5 = splinefit (x, y, 8, "order", 4);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     y3 = ppval (pp3, xx);
     y4 = ppval (pp4, xx);
     y5 = ppval (pp5, xx);
     plot (x, y, ".", xx, [y1; y2; y3; y4; y5])
     axis tight
     ylim auto
     legend ({"data", "order 0", "order 1", "order 2", "order 3", "order 4"})

   When the underlying function to provide a fit to is periodic,
'splinefit' is able to apply the boundary conditions needed to manifest
a periodic fit.  This is demonstrated by the code below.

     ## Data (100 points)
     x = 2 * pi * [0, (rand (1, 98)), 1];
     y = sin (x) - cos (2 * x) + 0.2 * randn (size (x));
     ## No constraints
     pp1 = splinefit (x, y, 10, "order", 5);
     ## Periodic boundaries
     pp2 = splinefit (x, y, 10, "order", 5, "periodic", true);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "no constraints", "periodic"})

   More complex constraints may be added as well.  For example, the code
below illustrates a periodic fit with values that have been clamped at
the endpoints, and a second periodic fit which is hinged at the
endpoints.

     ## Data (200 points)
     x = 2 * pi * rand (1, 200);
     y = sin (2 * x) + 0.1 * randn (size (x));
     ## Breaks
     breaks = linspace (0, 2 * pi, 10);
     ## Clamped endpoints, y = y' = 0
     xc = [0, 0, 2*pi, 2*pi];
     cc = [(eye (2)), (eye (2))];
     con = struct ("xc", xc, "cc", cc);
     pp1 = splinefit (x, y, breaks, "constraints", con);
     ## Hinged periodic endpoints, y = 0
     con = struct ("xc", 0);
     pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true);
     ## Plot
     xx = linspace (0, 2 * pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     plot (x, y, ".", xx, [y1; y2])
     axis tight
     ylim auto
     legend ({"data", "clamped", "hinged periodic"})

   The 'splinefit' function also provides the convenience of a ROBUST
fitting, where the effect of outlying data is reduced.  In the example
below, three different fits are provided.  Two with differing levels of
outlier suppression and a third illustrating the non-robust solution.

     ## Data
     x = linspace (0, 2*pi, 200);
     y = sin (x) + sin (2 * x) + 0.05 * randn (size (x));
     ## Add outliers
     x = [x, linspace(0,2*pi,60)];
     y = [y, -ones(1,60)];
     ## Fit splines with hinged conditions
     con = struct ("xc", [0, 2*pi]);
     ## Robust fitting, beta = 0.25
     pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25);
     ## Robust fitting, beta = 0.75
     pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75);
     ## No robust fitting
     pp3 = splinefit (x, y, 8, "constraints", con);
     ## Plot
     xx = linspace (0, 2*pi, 400);
     y1 = ppval (pp1, xx);
     y2 = ppval (pp2, xx);
     y3 = ppval (pp3, xx);
     plot (x, y, ".", xx, [y1; y2; y3])
     legend ({"data with outliers","robust, beta = 0.25", ...
              "robust, beta = 0.75", "no robust fitting"})
     axis tight
     ylim auto

   The function, 'ppval', evaluates the piecewise polynomials, created
by 'mkpp' or other means, and 'unmkpp' returns detailed information
about the piecewise polynomial.

   The following example shows how to combine two linear functions and a
quadratic into one function.  Each of these functions is expressed on
adjoined intervals.

     x = [-2, -1, 1, 2];
     p = [ 0,  1, 0;
           1, -2, 1;
           0, -1, 1 ];
     pp = mkpp (x, p);
     xi = linspace (-2, 2, 50);
     yi = ppval (pp, xi);
     plot (xi, yi);

 -- Function File: PP = mkpp (BREAKS, COEFS)
 -- Function File: PP = mkpp (BREAKS, COEFS, D)

     Construct a piecewise polynomial (pp) structure from sample points
     BREAKS and coefficients COEFS.  BREAKS must be a vector of strictly
     increasing values.  The number of intervals is given by 'NI =
     length (BREAKS) - 1'.  When M is the polynomial order COEFS must be
     of size: NI x M + 1.

     The i-th row of COEFS, 'COEFS (I,:)', contains the coefficients for
     the polynomial over the I-th interval, ordered from highest (M) to
     lowest (0).

     COEFS may also be a multi-dimensional array, specifying a
     vector-valued or array-valued polynomial.  In that case the
     polynomial order is defined by the length of the last dimension of
     COEFS.  The size of first dimension(s) are given by the scalar or
     vector D.  If D is not given it is set to '1'.  In any case COEFS
     is reshaped to a 2-D matrix of size '[NI*prod(D M)] '

     See also: *note unmkpp: XREFunmkpp, *note ppval: XREFppval, *note
     spline: XREFspline, *note pchip: XREFpchip, *note ppder: XREFppder,
     *note ppint: XREFppint, *note ppjumps: XREFppjumps.

 -- Function File: [X, P, N, K, D] = unmkpp (PP)

     Extract the components of a piecewise polynomial structure PP.  The
     components are:

     X
          Sample points.

     P
          Polynomial coefficients for points in sample interval.  'P (I,
          :)' contains the coefficients for the polynomial over interval
          I ordered from highest to lowest.  If 'D > 1', 'P (R, I, :)'
          contains the coefficients for the r-th polynomial defined on
          interval I.

     N
          Number of polynomial pieces.

     K
          Order of the polynomial plus 1.

     D
          Number of polynomials defined for each interval.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     spline: XREFspline, *note pchip: XREFpchip.

 -- Function File: YI = ppval (PP, XI)
     Evaluate the piecewise polynomial structure PP at the points XI.
     If PP describes a scalar polynomial function, the result is an
     array of the same shape as XI.  Otherwise, the size of the result
     is '[pp.dim, length(XI)]' if XI is a vector, or '[pp.dim,
     size(XI)]' if it is a multi-dimensional array.

     See also: *note mkpp: XREFmkpp, *note unmkpp: XREFunmkpp, *note
     spline: XREFspline, *note pchip: XREFpchip.

 -- Function File: ppd = ppder (pp)
 -- Function File: ppd = ppder (pp, m)
     Compute the piecewise M-th derivative of a piecewise polynomial
     struct PP.  If M is omitted the first derivative is calculated.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     ppint: XREFppint.

 -- Function File: PPI = ppint (PP)
 -- Function File: PPI = ppint (PP, C)
     Compute the integral of the piecewise polynomial struct PP.  C, if
     given, is the constant of integration.

     See also: *note mkpp: XREFmkpp, *note ppval: XREFppval, *note
     ppder: XREFppder.

 -- Function File: JUMPS = ppjumps (PP)
     Evaluate the boundary jumps of a piecewise polynomial.  If there
     are n intervals, and the dimensionality of PP is d, the resulting
     array has dimensions '[d, n-1]'.

     See also: *note mkpp: XREFmkpp.


File: octave.info,  Node: Miscellaneous Functions,  Prev: Polynomial Interpolation,  Up: Polynomial Manipulations

28.6 Miscellaneous Functions
============================

 -- Function File: poly (A)
 -- Function File: poly (X)
     If A is a square N-by-N matrix, 'poly (A)' is the row vector of the
     coefficients of 'det (z * eye (N) - A)', the characteristic
     polynomial of A.  For example, the following code finds the
     eigenvalues of A which are the roots of 'poly (A)'.

          roots (poly (eye (3)))
              => 1.00001 + 0.00001i
                 1.00001 - 0.00001i
                 0.99999 + 0.00000i

     In fact, all three eigenvalues are exactly 1 which emphasizes that
     for numerical performance the 'eig' function should be used to
     compute eigenvalues.

     If X is a vector, 'poly (X)' is a vector of the coefficients of the
     polynomial whose roots are the elements of X.  That is, if C is a
     polynomial, then the elements of 'D = roots (poly (C))' are
     contained in C.  The vectors C and D are not identical, however,
     due to sorting and numerical errors.

     See also: *note roots: XREFroots, *note eig: XREFeig.

 -- Function File: polyout (C)
 -- Function File: polyout (C, X)
 -- Function File: STR = polyout (...)
     Write formatted polynomial

          c(x) = c(1) * x^n + ... + c(n) x + c(n+1)

     and return it as a string or write it to the screen (if NARGOUT is
     zero).  X defaults to the string "s".

     See also: *note polyreduce: XREFpolyreduce.

 -- Function File: polyreduce (C)
     Reduce a polynomial coefficient vector to a minimum number of terms
     by stripping off any leading zeros.

     See also: *note polyout: XREFpolyout.


File: octave.info,  Node: Interpolation,  Next: Geometry,  Prev: Polynomial Manipulations,  Up: Top

29 Interpolation
****************

* Menu:

* One-dimensional Interpolation::
* Multi-dimensional Interpolation::


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

29.1 One-dimensional Interpolation
==================================

Octave supports several methods for one-dimensional interpolation, most
of which are described in this section.  *note Polynomial
Interpolation:: and *note Interpolation on Scattered Data:: describe
additional methods.

 -- Function File: YI = interp1 (X, Y, XI)
 -- Function File: YI = interp1 (Y, XI)
 -- Function File: YI = interp1 (..., METHOD)
 -- Function File: YI = interp1 (..., EXTRAP)
 -- Function File: YI = interp1 (..., "left")
 -- Function File: YI = interp1 (..., "right")
 -- Function File: PP = interp1 (..., "pp")

     One-dimensional interpolation.

     Interpolate input data to determine the value of YI at the points
     XI.  If not specified, X is taken to be the indices of Y ('1:length
     (Y)').  If Y is a matrix or an N-dimensional array, the
     interpolation is performed on each column of Y.

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "previous"
          Return the previous neighbor.

     "next"
          Return the next neighbor.

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

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

     "cubic"
          Cubic interpolation (same as "pchip").

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

     Adding '*' to the start of any method above forces 'interp1' to
     assume that X is uniformly spaced, and only 'X(1)' and 'X(2)' are
     referenced.  This is usually faster, and is never slower.  The
     default method is "linear".

     If EXTRAP is the string "extrap", then extrapolate values beyond
     the endpoints using the current METHOD.  If EXTRAP is a number,
     then replace values beyond the endpoints with that number.  When
     unspecified, EXTRAP defaults to 'NA'.

     If the string argument "pp" is specified, then XI should not be
     supplied and 'interp1' returns a piecewise polynomial object.  This
     object can later be used with 'ppval' to evaluate the
     interpolation.  There is an equivalence, such that 'ppval (interp1
     (X, Y, METHOD, "pp"), XI) == interp1 (X, Y, XI, METHOD, "extrap")'.

     Duplicate points in X specify a discontinuous interpolant.  There
     may be at most 2 consecutive points with the same value.  If X is
     increasing, the default discontinuous interpolant is
     right-continuous.  If X is decreasing, the default discontinuous
     interpolant is left-continuous.  The continuity condition of the
     interpolant may be specified by using the options "left" or "right"
     to select a left-continuous or right-continuous interpolant,
     respectively.  Discontinuous interpolation is only allowed for
     "nearest" and "linear" methods; in all other cases, the X-values
     must be unique.

     An example of the use of 'interp1' is

          xf = [0:0.05:10];
          yf = sin (2*pi*xf/5);
          xp = [0:10];
          yp = sin (2*pi*xp/5);
          lin = interp1 (xp, yp, xf);
          near = interp1 (xp, yp, xf, "nearest");
          pch = interp1 (xp, yp, xf, "pchip");
          spl = interp1 (xp, yp, xf, "spline");
          plot (xf,yf,"r", xf,near,"g", xf,lin,"b", xf,pch,"c", xf,spl,"m",
                xp,yp,"r*");
          legend ("original", "nearest", "linear", "pchip", "spline");

     See also: *note pchip: XREFpchip, *note spline: XREFspline, *note
     interpft: XREFinterpft, *note interp2: XREFinterp2, *note interp3:
     XREFinterp3, *note interpn: XREFinterpn.

   There are some important differences between the various
interpolation methods.  The "spline" method enforces that both the first
and second derivatives of the interpolated values have a continuous
derivative, whereas the other methods do not.  This means that the
results of the "spline" method are generally smoother.  If the function
to be interpolated is in fact smooth, then "spline" will give excellent
results.  However, if the function to be evaluated is in some manner
discontinuous, then "pchip" interpolation might give better results.

   This can be demonstrated by the code

     t = -2:2;
     dt = 1;
     ti =-2:0.025:2;
     dti = 0.025;
     y = sign (t);
     ys = interp1 (t,y,ti,"spline");
     yp = interp1 (t,y,ti,"pchip");
     ddys = diff (diff (ys)./dti) ./ dti;
     ddyp = diff (diff (yp)./dti) ./ dti;
     figure (1);
     plot (ti,ys,"r-", ti,yp,"g-");
     legend ("spline", "pchip", 4);
     figure (2);
     plot (ti,ddys,"r+", ti,ddyp,"g*");
     legend ("spline", "pchip");

   Fourier interpolation, is a resampling technique where a signal is
converted to the frequency domain, padded with zeros and then
reconverted to the time domain.

 -- Function File: interpft (X, N)
 -- Function File: interpft (X, N, DIM)

     Fourier interpolation.  If X is a vector, then X is resampled with
     N points.  The data in X is assumed to be equispaced.  If X is a
     matrix or an N-dimensional array, the interpolation is performed on
     each column of X.  If DIM is specified, then interpolate along the
     dimension DIM.

     'interpft' assumes that the interpolated function is periodic, and
     so assumptions are made about the endpoints of the interpolation.

     See also: *note interp1: XREFinterp1.

   There are two significant limitations on Fourier interpolation.
First, the function signal is assumed to be periodic, and so
non-periodic signals will be poorly represented at the edges.  Second,
both the signal and its interpolation are required to be sampled at
equispaced points.  An example of the use of 'interpft' is

     t = 0 : 0.3 : pi; dt = t(2)-t(1);
     n = length (t); k = 100;
     ti = t(1) + [0 : k-1]*dt*n/k;
     y = sin (4*t + 0.3) .* cos (3*t - 0.1);
     yp = sin (4*ti + 0.3) .* cos (3*ti - 0.1);
     plot (ti, yp, "g", ti, interp1 (t, y, ti, "spline"), "b", ...
           ti, interpft (y, k), "c", t, y, "r+");
     legend ("sin(4t+0.3)cos(3t-0.1)", "spline", "interpft", "data");

which demonstrates the poor behavior of Fourier interpolation for
non-periodic functions.

   In addition, the support functions 'spline' and 'lookup' that
underlie the 'interp1' function can be called directly.

 -- Function File: PP = spline (X, Y)
 -- Function File: YI = spline (X, Y, XI)
     Return the cubic spline interpolant of points X and Y.

     When 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, 'spline'
     evaluates the spline at the points XI.  The third calling form
     'spline (X, Y, XI)' is equivalent to 'ppval (spline (X, Y), XI)'.

     The variable X must be a vector of length N.  Y can be either a
     vector or array.  If Y is a vector it must have a length of either
     N or 'N + 2'.  If the length of Y is N, then the "not-a-knot" end
     condition is used.  If the length of Y is 'N + 2', then the first
     and last values of the vector Y are the values of the first
     derivative of the cubic spline at the endpoints.

     If Y is an array, then the size of Y must have the form '[S1, S2,
     ..., SK, N]' or '[S1, S2, ..., SK, N + 2]'.  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 pchip: XREFpchip, *note ppval: XREFppval, *note
     mkpp: XREFmkpp, *note unmkpp: XREFunmkpp.


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

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

     Two-dimensional interpolation.

     Interpolate 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 (same as "pchip").

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

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

     Three-dimensional interpolation.

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

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

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

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

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

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

 -- Function File: TRI = delaunay (X, Y)
 -- Function File: TETR = delaunay (X, Y, Z)
 -- Function File: TRI = delaunay (X)
 -- Function File: 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., only a single
     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., only a single
     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.

     The optional last 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", "Qz"}'.

     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.

 -- Function File: T = delaunayn (PTS)
 -- Function File: 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", "Qz"}'

        * 4-D and higher: OPTIONS = '{"Qt", "Qbb", "Qc", "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 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", 2);
     x = rand (10, 1);
     y = rand (10, 1);
     T = delaunay (x, y);
     X = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
     Y = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
     axis ([0, 1, 0, 1]);
     plot (X, Y, "b", x, y, "r*");

* Menu:

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


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

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.

 -- Function File: triplot (TRI, X, Y)
 -- Function File: triplot (TRI, X, Y, LINESPEC)
 -- Function File: 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.

 -- Function File: trimesh (TRI, X, Y, Z, C)
 -- Function File: trimesh (TRI, X, Y, Z)
 -- Function File: trimesh (TRI, X, Y)
 -- Function File: trimesh (..., PROP, VAL, ...)
 -- Function File: 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 a color matrix, C.  If Z has N elements, then C
     should be an Nx1 vector for colormap data or an Nx3 matrix for RGB
     data.

     Any property/value pairs are passed directly to the underlying
     patch object.

     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.

 -- Function File: trisurf (TRI, X, Y, Z, C)
 -- Function File: trisurf (TRI, X, Y, Z)
 -- Function File: trisurf (..., PROP, VAL, ...)
 -- Function File: 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 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 a color matrix, C.  If Z has N elements, then C
     should be an Nx1 vector for colormap data or an Nx3 matrix for RGB
     data.

     Any property/value pairs are passed directly to the underlying
     patch object.

     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.

 -- Function File: tetramesh (T, X)
 -- Function File: tetramesh (T, X, C)
 -- Function File: tetramesh (..., PROPERTY, VAL, ...)
 -- Function File: 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 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 'triplot', is that
the former only plots the 2-dimensional triangulation itself, whereas
the second two plot the value of a function 'f (X, Y)'.  An example of
the use of the 'triplot' function is

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

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


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

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 = sum (BETA(1:N+1) * T(1:N+1),:)

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

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

is imposed, and we can therefore write the above as

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

Solving for BETA we can then write

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

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

     0 <= BETA(I) <= 1

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

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

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

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

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

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

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

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

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

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

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

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

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

     See also: *note dsearchn: XREFdsearchn, *note tsearch: XREFtsearch.

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

     See also: *note dsearch: 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 vertexes of the Voronoi tessellation are the centers of the
circum-circles of the simplices of the Delaunay tessellation.

 -- Function File: voronoi (X, Y)
 -- Function File: voronoi (X, Y, OPTIONS)
 -- Function File: voronoi (..., "linespec")
 -- Function File: voronoi (HAX, ...)
 -- Function File: H = voronoi (...)
 -- Function File: [VX, VY] = voronoi (...)
     Plot the Voronoi diagram of points '(X, Y)'.  The Voronoi facets
     with points at infinity are not drawn.

     If "linespec" is given it is used to set the color and line style
     of the plot.  If an axis graphics handle HAX is supplied then the
     Voronoi diagram is drawn on the specified axis rather than in a new
     figure.

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

 -- Function File: [C, F] = voronoin (PTS)
 -- Function File: [C, F] = voronoin (PTS, OPTIONS)
     Compute N-dimensional Voronoi facets.  The input matrix PTS of size
     [n, dim] contains n points 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.

 -- Function File: polyarea (X, Y)
 -- Function File: 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'

 -- Function File: AREA = rectint (A, B)
     Compute area or volume of intersection of rectangles or ND 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.

 -- Function File: IN = inpolygon (X, Y, XV, YV)
 -- Function File: [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 variables X, 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.

 -- Function File: H = convhull (X, Y)
 -- Function File: H = convhull (X, Y, OPTIONS)
     Compute the convex hull of the set of points defined by the arrays
     X and Y.  The hull H is an index vector into the set of points and
     specifies which points form the enclosing hull.

     An optional third 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.

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

 -- Loadable Function: H = convhulln (PTS)
 -- Loadable Function: H = convhulln (PTS, OPTIONS)
 -- Loadable Function: [H, V] = convhulln (...)
     Compute the convex hull of the set of points PTS which 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,  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'.

 -- Function File: ZI = griddata (X, Y, Z, XI, YI)
 -- Function File: ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- Function File: [XI, YI, ZI] = griddata (...)

     Generate a regular mesh from irregular data using interpolation.
     The function is defined by 'Z = f (X, Y)'.  Inputs 'X, Y, Z' are
     vectors of the same length or 'X, Y' are vectors and 'Z' is matrix.

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

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

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

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

     Generate a regular mesh from irregular data using interpolation.
     The function is defined by 'V = f (X, Y, Z)'.  The interpolation
     points are specified by XI, YI, ZI.

     The interpolation method can be "nearest" or "linear".  If method
     is omitted 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.

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

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

     Generate a regular mesh from irregular data using interpolation.
     The function is defined by 'Y = f (X)'.  The interpolation points
     are all XI.

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

     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.

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

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


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

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.

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

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

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

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

     See also: *note ifft: XREFifft, *note fft2: XREFfft2, *note fftn:
     XREFfftn, *note fftw: XREFfftw.

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

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

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

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

     See also: *note fft: XREFfft, *note ifft2: XREFifft2, *note ifftn:
     XREFifftn, *note fftw: XREFfftw.

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

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

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

     See also: ifft2, fft, fftn, fftw.

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

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

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

     See also: fft2, ifft, ifftn, fftw.

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

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

     See also: *note ifftn: XREFifftn, *note fft: XREFfft, *note fft2:
     XREFfft2, *note fftw: XREFfftw.

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

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

     See also: *note fftn: 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.

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

     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.  The number of processors available to the
     current process is used per default.

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

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

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

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

     See also: *note deconv: XREFdeconv, *note conv: XREFconv, *note
     conv2: XREFconv2.

 -- Function File: fftfilt (B, X)
 -- Function File: fftfilt (B, X, N)

     With two arguments, 'fftfilt' filters X with the FIR filter B using
     the FFT.

     Given the optional third argument, N, 'fftfilt' uses the
     overlap-add method to filter X with B using an N-point FFT.  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.

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

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

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

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

     where N=length(a)-1 and M=length(b)-1.  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.

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

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

     "same"
          unpadded X (default)

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

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

     See also: *note conv2: XREFconv2.

 -- Function File: [H, W] = freqz (B, A, N, "whole")
 -- Function File: [H, W] = freqz (B)
 -- Function File: [H, W] = freqz (B, A)
 -- Function File: [H, W] = freqz (B, A, N)
 -- Function File: H = freqz (B, A, W)
 -- Function File: [H, W] = freqz (..., FS)
 -- Function File: 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.

 -- Function File: freqz_plot (W, H)
 -- Function File: 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.

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

 -- Function File: B = unwrap (X)
 -- Function File: B = unwrap (X, TOL)
 -- Function File: B = unwrap (X, TOL, DIM)

     Unwrap radian phases by adding multiples of 2*pi as appropriate to
     remove jumps greater than TOL.  TOL defaults to pi.

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

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

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

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

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

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

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

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

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

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

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

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

          y = x * b + e

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

     I.e., the model is

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

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

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

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

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

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

     as the t-th row of X.

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

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

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

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

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

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

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

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

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

 -- Function File: blackman (M)
 -- Function File: blackman (M, "periodic")
 -- Function File: 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'.

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

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

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

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

     See also: *note polyfit: XREFpolyfit.

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

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

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

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

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

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

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

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

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

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

     where df = 1 / dt.

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

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

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

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

 -- Function File: hamming (M)
 -- Function File: hamming (M, "periodic")
 -- Function File: 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'.

 -- Function File: hanning (M)
 -- Function File: hanning (M, "periodic")
 -- Function File: 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'.

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

 -- Function File: PP = pchip (X, Y)
 -- Function File: YI = pchip (X, Y, XI)
     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.

 -- Function File: [PXX, W] = periodogram (X)
 -- Function File: [PXX, W] = periodogram (X, WIN)
 -- Function File: [PXX, W] = periodogram (X, WIN, NFFT)
 -- Function File: [PXX, F] = periodogram (X, WIN, NFFT, FS)
 -- Function File: [PXX, F] = periodogram (..., "RANGE")
 -- Function File: 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.

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

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

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

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

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

     The window name, e.g., "triangle" or "rectangle" is used to search
     for a function called 'WIN_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.

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

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

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

     See also: *note spectral_adf: XREFspectral_adf.

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

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

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

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

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


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

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

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

     Reads an image as a matrix from the file FILENAME.  If there is no
     file FILENAME, and EXT was specified, it will look for a file with
     the extension EXT.  Finally, it will attempt to download and read
     an image from URL.

     The size and class of the output depends on the format of the
     image.  A color image is returned as an MxNx3 matrix.  Gray-level
     and black-and-white images are of size MxN. 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 gray and color, and "logical" for
     black and white.  Note that indexed images always return the
     indexes for a colormap, independent if 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.

     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 only read
     the first page.

     Depending on the file format, it is possible to configure the
     reading of images with PARAM, VAL 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 and has no effect.
          For maximum performance while reading multiple images from a
          single file, use the Index option.

     '"PixelRegion"'
          Controls the image region that is read.  Takes as value 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, 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.

 -- Function File: imwrite (IMG, FILENAME)
 -- Function File: imwrite (IMG, FILENAME, EXT)
 -- Function File: imwrite (IMG, MAP, FILENAME)
 -- Function File: 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.

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

 -- Built-in Function: VAL = IMAGE_PATH ()
 -- Built-in Function: OLD_VAL = IMAGE_PATH (NEW_VAL)
 -- Built-in Function: 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.

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

 -- Function File: INFO = imfinfo (FILENAME)
 -- Function File: INFO = imfinfo (URL)
 -- Function File: 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.

 -- Function File: imformats ()
 -- Function File: FORMATS = imformats (EXT)
 -- Function File: FORMATS = imformats (FORMAT)
 -- Function File: FORMATS = imformats ("add", FORMAT)
 -- Function File: FORMATS = imformats ("remove", EXT)
 -- Function File: FORMATS = imformats ("update", EXT, FORMAT)
 -- Function File: 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.

 -- Function File: imshow (IM)
 -- Function File: imshow (IM, LIMITS)
 -- Function File: imshow (IM, MAP)
 -- Function File: imshow (RGB, ...)
 -- Function File: imshow (FILENAME)
 -- Function File: imshow (..., STRING_PARAM1, VALUE1, ...)
 -- Function File: 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 file name is given instead of an image, the file will be read
     and shown.

     If given, the parameter STRING_PARAM1 has value VALUE1.
     STRING_PARAM1 can be any of the following:

     "displayrange"
          VALUE1 is the display range as described above.

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

     "xdata"
          If VALUE1 is a two element vector, it must contain horizontal
          axis limits in the form [xmin xmax]; Otherwise VALUE1 must be
          a vector and only the first and last elements will be used for
          xmin and xmax respectively.

     "ydata"
          If VALUE1 is a two element vector, it must contain vertical
          axis limits in the form [ymin ymax]; Otherwise VALUE1 must be
          a vector and only the first and last elements will be used for
          ymin and ymax 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.

 -- Function File: image (IMG)
 -- Function File: image (X, Y, IMG)
 -- Function File: image (..., "PROP", VAL, ...)
 -- Function File: image ("PROP1", VAL1, ...)
 -- Function File: 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
     range for the axis labels.  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.  *Warning:* X and Y are
     ignored when using gnuplot 4.0 or earlier.

     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.

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

 -- Function File: imagesc (IMG)
 -- Function File: imagesc (X, Y, IMG)
 -- Function File: imagesc (..., CLIMITS)
 -- Function File: imagesc (..., "PROP", VAL, ...)
 -- Function File: imagesc ("PROP1", VAL1, ...)
 -- Function File: imagesc (HAX, ...)
 -- Function File: 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.

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

     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.

     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.

 -- Function File: iscolormap (CMAP)
     Return true if CMAP is a colormap.

     A colormap is a real matrix with N rows and 3 columns.  Each row
     represents a single color.  The columns contain red, green, and
     blue intensities respectively.  All entries must be between 0 and 1
     inclusive.

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

 -- Function File: IMG = gray2ind (I)
 -- Function File: IMG = gray2ind (I, N)
 -- Function File: IMG = gray2ind (BW)
 -- Function File: IMG = gray2ind (BW, N)
 -- Function File: [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.

 -- Function File: 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 CMAP.  If CMAP 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 'rgb2ntsc' 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.

 -- Function File: [X, MAP] = rgb2ind (RGB)
 -- Function File: [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 rgb2ntsc: XREFrgb2ntsc.

 -- Function File: RGB = ind2rgb (X, MAP)
 -- Function File: [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, *note ntsc2rgb: XREFntsc2rgb.

 -- Function File: CMAP = colormap ()
 -- Function File: CMAP = colormap (MAP)
 -- Function File: CMAP = colormap ("default")
 -- Function File: CMAP = colormap ("MAP_NAME")
 -- Function File: CMAP = colormap (HAX, ...)
 -- Command: colormap MAP_NAME
 -- Function File: CMAPS = colormap ("list")
 -- Function File: colormap ("register", "NAME")
 -- Function File: colormap ("unregister", "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 'jet' map
     with 64 entries).  The default colormap is returned.

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

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

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

     'colormap ("list")' returns a cell array with all of the available
     colormaps.  The options "register" and "unregister" add or remove
     the colormap NAME from this list.

     See also: *note jet: XREFjet.

 -- Function File: rgbplot (CMAP)
 -- Function File: rgbplot (CMAP, STYLE)
 -- Function File: 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 each RGB
          components 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.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = colorcube ()
 -- Function File: 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.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = cubehelix ()
 -- Function File: MAP = cubehelix (N)
     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 transversing 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 and corresponds to the lenght of
     the colormap.  Defaults to the length of the current colormap.

     Development of this colormap is described in '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.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

 -- Function File: hsv (N)
     Create color colormap.  This colormap begins with red, changes
     through yellow, green, cyan, blue, and magenta, before returning to
     red.  It is useful for displaying periodic functions.  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.

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

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = lines ()
 -- Function File: 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, green, red, cyan, pink, yellow, 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.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

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

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

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

     See also: *note colormap: XREFcolormap.

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

 -- Function File: MAP_OUT = brighten (MAP, BETA)
 -- Function File: MAP_OUT = brighten (BETA)
 -- Function File: MAP_OUT = brighten (H, BETA)
     Brighten or darken a 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.

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

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

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

 -- Function File: spinmap ()
 -- Function File: spinmap (T)
 -- Function File: spinmap (T, INC)
 -- Function File: 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.

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

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

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

     If the first argument HFIG is a figure handle, then operate on this
     figure rather than the current figure returned by 'gcf'.  The root
     properties will not be changed.

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

   The following functions can be used to manipulate colormaps.

 -- Function File: [Y, NEWMAP] = cmunique (X, MAP)
 -- Function File: [Y, NEWMAP] = cmunique (RGB)
 -- Function File: [Y, NEWMAP] = cmunique (I)
     Convert an input image X to an ouput 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.

 -- Function File: [Y, NEWMAP] = cmpermute (X, MAP)
 -- Function File: [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 NTSC and HSV and
vice versa.

 -- Function File: HSV_MAP = rgb2hsv (RGB)
 -- Function File: HSV_MAP = rgb2hsv (RGB)
     Transform a colormap or image from red-green-blue (RGB) space to
     hue-saturation-value (HSV) 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.  Value gives the amount of light in the color.
     Hue describes the dominant wavelength.  Saturation is the amount of
     hue mixed into the color.

     See also: *note hsv2rgb: XREFhsv2rgb, *note rgb2ind: XREFrgb2ind,
     *note rgb2ntsc: XREFrgb2ntsc.

 -- Function File: RGB_MAP = hsv2rgb (HSV_MAP)
 -- Function File: RGB_IMG = hsv2rgb (HSV_IMG)
     Transform a colormap or image from hue-saturation-value (HSV) space
     to red-green-blue (RGB) space.

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

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

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

 -- Function File: YIQ_MAP = rgb2ntsc (RGB_MAP)
 -- Function File: YIQ_IMG = rgb2ntsc (RGB_IMG)
     Transform a colormap or image from red-green-blue (RGB) color space
     to luminance-chrominance (NTSC) space.  The input may be of class
     uint8, uint16, single, or double.  The output is of class double.

     Implementation Note: The reference matrix for the transformation is

          /Y\     0.299  0.587  0.114  /R\
          |I|  =  0.596 -0.274 -0.322  |G|
          \Q/     0.211 -0.523  0.312  \B/

     as documented in <http://en.wikipedia.org/wiki/YIQ> and truncated
     to 3 significant figures.  Note: The FCC version of NTSC uses only
     2 significant digits and is slightly different.

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

 -- Function File: RGB_MAP = ntsc2rgb (YIQ_MAP)
 -- Function File: RGB_IMG = ntsc2rgb (YIQ_IMG)
     Transform a colormap or image from luminance-chrominance (NTSC)
     space to red-green-blue (RGB) color space.

     Implementation Note: The conversion matrix is chosen to be the
     inverse of the matrix used for rgb2ntsc such that

          x == ntsc2rgb (rgb2ntsc (x))

     MATLAB uses a slightly different matrix where rounding means the
     equality above does not hold.

     See also: *note rgb2ntsc: XREFrgb2ntsc, *note hsv2rgb: XREFhsv2rgb,
     *note ind2rgb: XREFind2rgb.


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.

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

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

 -- Loadable Function: [Y, FS] = audioread (FILENAME, DATATYPE)
 -- Loadable Function: [Y, FS] = audioread (FILENAME, SAMPLES, DATATYPE)
     Read the audio file FILENAME and return the audio data and sampling
     rate.  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.

     Read a file and return a specified range of frames in an array of
     specified type.

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

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

     Additional name and 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.


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

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

 -- Loadable Function: DEVINFO = audiodevinfo ()

 -- Loadable Function: DEVS = audiodevinfo (IO)
 -- Loadable Function: NAME = audiodevinfo (IO, ID)
 -- Loadable Function: ID = audiodevinfo (IO, NAME)
 -- Loadable Function: ID = audiodevinfo (IO, RATE, BITS, CHANS)

 -- Loadable Function: SUPPORTS = audiodevinfo (IO, ID, RATE, BITS,
          CHANS)

     Return a structure with 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 the optional argument ID is provided, return information about
     corresponding device.

     If the optional argument NAME is provided, return the id of the
     named 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.

 -- Function File: PLAYER = audioplayer (Y, FS)
 -- Function File: PLAYER = audioplayer (Y, FS, NBITS)
 -- Function File: PLAYER = audioplayer (Y, FS, NBITS, ID)
 -- Function File: PLAYER = audioplayer (RECORDER)
 -- Function File: PLAYER = audioplayer (RECORDER, ID)
     Create an audioplayer object that will play back data Y at sample
     rate FS.  The optional arguments NBITS, and ID specify the bit
     depth and player device id, respectively.  Device IDs may be found
     using the audiodevinfo function.  Given an audioplayer object, use
     the data from the object to initialize the player.

     The signal Y can be a vector or a two-dimensional array.

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

          y = randn (2, 44100) - 0.5;
          player = audioplayer (y, 44100, 8);
          play (player);

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

 -- Function File: play (PLAYER)
 -- Function File: play (PLAYER, START)
 -- Function File: play (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER without
     blocking.  Given optional argument start, begin playing at START
     seconds in the recording.  Given a two-element vector LIMITS, begin
     and end playing at the number of seconds specified by the elements
     of the vector.

 -- Function File: playblocking (PLAYER)
 -- Function File: playblocking (PLAYER, START)
 -- Function File: playblocking (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER with blocking.
     Given optional argument start, begin playing at START seconds in
     the recording.  Given a two-element vector LIMITS, begin and end
     playing at the number of seconds specified by the elements of the
     vector.

 -- Function File: pause (PLAYER)
     Pause the audioplayer PLAYER.

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

 -- Function File: stop (PLAYER)
     Stop the playback for the audioplayer PLAYER and reset the relevant
     variables to their starting values.

 -- Function File: isplaying (PLAYER)
     Return 1 if the audioplayer object PLAYERis currently playing back
     audio and 0 otherwise.


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.

 -- Function File: VALUE = get (PLAYER, NAME)
 -- Function File: 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 of all properties of PLAYER.  The
     field names of the structure correspond to property names.

 -- Function File: set (PLAYER, NAME, VALUE)
 -- Function File: set (PLAYER, PROPERTIES)
 -- Function File: 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 field values.  Given only the audioplayer object, return a
     structure of settable properties.


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.

 -- Function File: RECORDER = audiorecorder ()
 -- Function File: RECORDER = audiorecorder (FS, NBITS, CHANNELS)
 -- Function File: RECORDER = audiorecorder (FS, NBITS, CHANNELS, ID)
     Create an audiorecorder object recording 8 bit mono audio at 8000
     Hz sample rate.  The optional arguments FS, NBITS, CHANNELS, and ID
     specify the sample rate, bit depth, number of channels and
     recording device id, respectively.  Device IDs may be found using
     the audiodevinfo function.

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

 -- Function File: record (RECORDER)
 -- Function File: record (RECORDER, LENGTH)
     Record audio without blocking using the audiorecorder object
     RECORDER until stopped or paused by the STOP or PAUSE method.
     Given the optional argument LENGTH, record for LENGTH seconds.

 -- Function File: recordblocking (RECORDER, LENGTH)
     Record audio with blocking (synchronous I/O). You must specify the
     length of the recording in seconds.

 -- Function File: pause (RECORDER)
     Pause recording with audiorecorder object RECORDER.

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

 -- Function File: stop (RECORDER)
     Stop the audiorecorder object RECORDER and clean up any audio
     streams.

 -- Function File: isrecording (RECORDER)
     Return 1 if the audiorecorder object RECORDER is currently
     recording audio and 0 otherwise.


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.

 -- Function File: DATA = getaudiodata (RECORDER)
 -- Function File: DATA = getaudiodata (RECORDER, DATATYPE)
     Return recorder audio data as a matrix with values between -1.0 and
     1.0 and with as many columns as there are channels in the 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".

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

 -- Function File: PLAYER = play (RECORDER)
 -- Function File: PLAYER = play (RECORDER, START)
 -- Function File: PLAYER = play (RECORDER, [START, END])
     Play the audio recorded in RECORDER and return a corresponding
     audioplayer object.  If the optional argument START is provided,
     begin playing START seconds in to the recording.  If the optional
     argument END is provided, stop playing at END seconds in the
     recording.


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.

 -- Function File: VALUE = get (RECORDER, NAME)
 -- Function File: VALUES = get (RECORDER)
     Return the VALUE of the property identified by NAME.  If NAME is a
     cell array, return the values of the properties corresponding to
     the elements of the cell array.  Given only the recorder object,
     return a scalar structure with values of all properties of
     RECORDER.  The field names of the structure correspond to property
     names.

 -- Function File: set (RECORDER, NAME, VALUE)
 -- Function File: set (RECORDER, PROPERTIES)
 -- Function File: PROPERTIES = set (RECORDER)
     Set the value of property specified by NAME to a given VALUE.  If
     NAME and VALUE are cell arrays of the same size, set each property
     to a corresponding value.  Given a structure with fields
     corresponding to property names, set the value of those properties
     to the corresponding field values.  Given only the recorder object,
     return a structure of settable properties.


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

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

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

     See also: *note mu2lin: XREFmu2lin.

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

     If N is not specified it defaults to 0.

     See also: *note lin2mu: XREFlin2mu.

 -- Function File: record (SEC)
 -- Function File: 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.

 -- Function File: sound (Y)
 -- Function File: sound (Y, FS)
 -- Function File: sound (Y, FS, NBITS)
     Play audio data Y at sample rate FS to the default audio device.
     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.

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

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

     See also: *note record: XREFrecord, *note soundsc: XREFsoundsc.

 -- Function File: soundsc (Y)
 -- Function File: soundsc (Y, FS)
 -- Function File: soundsc (Y, FS, NBITS)
 -- Function File: soundsc (..., [YMIN, YMAX])
     Scale the audio data Y and play it at sample rate FS to the default
     audio device.  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.

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

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

     See also: *note record: XREFrecord, *note sound: XREFsound.

 -- Function File: Y = wavread (FILENAME)
 -- Function File: [Y, FS, NBITS] = wavread (FILENAME)
 -- Function File: [...] = wavread (FILENAME, N)
 -- Function File: [...] = wavread (FILENAME, [N1 N2])
 -- Function File: [...] = wavread (..., DATATYPE)
 -- Function File: SZ = wavread (FILENAME, "size")
     Read the audio signal Y from the RIFF/WAVE sound file FILENAME.  If
     the file contains multichannel data, then Y is a matrix with the
     channels represented as columns.

     The optional return value FS is the sample rate of the audio file
     in Hz.  The optional return value NBITS is the number of bits per
     sample as encoded in the file.

     If N is specified, only the first N samples of the file are
     returned.  If [N1 N2] is specified, only the range of samples from
     N1 to N2 is returned.  A value of 'Inf' can be used to represent
     the total number of samples in the file.

     If the option "size" is given, then the size of the audio signal is
     returned instead of the data.  The size is returned in a row vector
     of the form [SAMPLES CHANNELS].  If there are two output arguments,
     the number of samples is assigned to the first and the number of
     channels is assigned to the second.

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

 -- Function File: wavwrite (Y, FILENAME)
 -- Function File: wavwrite (Y, FS, FILENAME)
 -- Function File: wavwrite (Y, FS, NBITS, FILENAME)
     Write the audio signal Y to the RIFF/WAVE sound file FILENAME.  If
     Y is a matrix, the columns represent multiple audio channels.

     The optional argument FS specifies the sample rate of the audio
     signal in Hz.  The optional argument NBITS specifies the number of
     bits per sample to write to FILENAME.  The default sample rate is
     8000 Hz and the default bit depth is 16 bits per sample.

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


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

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

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

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

* Menu:

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


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

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

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

   The polynomial class is used to represent polynomials of the form

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

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

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

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

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

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## 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");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
     endfunction


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

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

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

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

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

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

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

     See also: *note class: 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.

 -- Function File: methods (OBJ)
 -- Function File: methods ("CLASSNAME")
 -- Function File: MTDS = methods (...)

     Return a cell array containing the names of the methods for the
     object OBJ or the named class CLASSNAME.  OBJ may be an Octave
     class object or a Java object.

     See also: *note fieldnames: XREFfieldnames.

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

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

     See also: *note isprop: XREFisprop, *note isobject: XREFisobject.

For example:

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


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

34.2 Manipulating Classes
=========================

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

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

          myclass (...)

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

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

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

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


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

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

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


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

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


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

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

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

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

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

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

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

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

     See also: *note loadobj: XREFloadobj, *note class: XREFclass.

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

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

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

     See also: *note saveobj: XREFsaveobj, *note class: XREFclass.


File: octave.info,  Node: Indexing Objects,  Next: Overloading Objects,  Prev: Manipulating Classes,  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, either like 'A (IDX)' or like
'A {IDX}', or even like 'A (IDX).FIELD'.  However, it is up to the user
to decide what this indexing actually means.  In the case of our
polynomial class 'P (N)' might mean either the coefficient of the N-th
power of the polynomial, or it might be the evaluation of the polynomial
at N.  The meaning of this subscripted referencing is determined by the
'subsref' method.

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

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

     The following example shows how to extract the 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.

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

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

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


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

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

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

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

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

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

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

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

 -- Built-in Function: VAL = optimize_subsasgn_calls ()
 -- Built-in Function: OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- Built-in Function: 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.

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

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

     function r = end (obj, index_pos, num_indices)

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

       r = length (obj.poly) - 1;

     endfunction


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

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

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

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

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

     then the 'subsindex' function

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

     can then be used as follows

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

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

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

 -- Built-in Function: R = colon (BASE, LIMIT)
 -- Built-in Function: 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'.


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 a
call to subsasgn:

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

and the corresponding method looking like this:

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

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

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

       x(1) = 1;

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

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

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

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


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

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 allows an object specific
version of this function to be called as needed.  A pertinent example
for our polynomial class might be to overload the 'polyval' function
like

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


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

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


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

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

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



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

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

Table 34.1: Available overloaded operators and their corresponding class
method

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

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



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

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

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

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

     See also: *note inferiorto: XREFinferiorto.

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

     See also: *note superiorto: XREFsuperiorto.

   For example with our polynomial class consider the case

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

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

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## 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");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
       superiorto ("double");
     endfunction


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

   When faced with two objects that have the same precedence, Octave
will use the method of the object that appears first on the list of
arguments.


File: octave.info,  Node: Inheritance and Aggregation,  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 struct that contains the data fields
required by the class, and then call the class function to indicate that
an object is to be created from the struct.  Creating a child of an
existing object is done by creating an object of the parent class and
providing that object as the third argument of the class function.

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

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

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

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

     function f = FIRfilter (p)

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


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

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

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

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

     function display (f)

       display (f.polynomial);

     endfunction



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

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

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

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

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


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

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

        0.33333
        0.66667
        1.00000
        1.00000
        1.00000

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

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

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

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


   So that

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

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

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

     function f = FIRfilter (p)

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


   For our example, the remaining class methods remain unchanged.


File: octave.info,  Node: 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,
context menus,

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


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

 -- Function File: DIRNAME = uigetdir ()
 -- Function File: DIRNAME = uigetdir (INIT_PATH)
 -- Function File: 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.

     See also: *note uigetfile: XREFuigetfile, *note uiputfile:
     XREFuiputfile.

 -- Function File: [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- Function File: [...] = uigetfile (FLT)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- Function File: [...] = uigetfile (..., "Position", [PX PY])
 -- Function 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 and the filename is selected as default file.
          Example: 'uigetfile ("myfun.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"})'

     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.

     The screen position of the GUI dialog can be set using the
     "Position" key and a 2-element vector containing the pixel
     coordinates.  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.

     See also: *note uiputfile: XREFuiputfile, *note uigetdir:
     XREFuigetdir.

 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- Function File: [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 and the filename is selected as default file.  Example:
          'uiputfile ("myfun.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.

     See also: *note uigetfile: XREFuigetfile, *note uigetdir:
     XREFuigetdir.


File: octave.info,  Node: Progress Bar,  Next: UI Elements,  Prev: I/O Dialogs,  Up: GUI Development

35.2 Progress Bar
=================

 -- Function File: H = waitbar (FRAC)
 -- Function File: H = waitbar (FRAC, MSG)
 -- Function File: H = waitbar (..., "FigureProperty", "Value", ...)
 -- Function File: waitbar (FRAC)
 -- Function File: waitbar (FRAC, HWBAR)
 -- Function File: waitbar (FRAC, HWBAR, MSG)
     Return a handle H to a new 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.  The appearance of the waitbar figure window can be
     configured by passing property/value pairs to the function.

     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 HWBAR of the specific waitbar to modify.


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.

 -- Function File: HUI = uicontextmenu ("Name", value, ...)

 -- Function File: HUI = uicontrol ("Name", value, ...)
 -- Function File: HUI = uicontrol (PARENT, "Name", value, ...)
 -- Function File: uicontrol (H)

 -- Function File: HUI = uipanel ("Name", value, ...)
 -- Function File: HUI = uipanel (PARENT, "Name", value, ...)

 -- Function File: HUI = uipushtool ("Name", value, ...)
 -- Function File: HUI = uipushtool (PARENT, "Name", value, ...)

 -- Function File: HUI = uitoggletool ("Name", value, ...)
 -- Function File: HUI = uitoggletool (PARENT, "Name", value, ...)

 -- Function File: HUI = uitoolbar ("Name", value, ...)
 -- Function File: HUI = uitoolbar (PARENT, "Name", value, ...)


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.

 -- Function File: USED = desktop ("-inuse")
     Return true if the desktop (GUI) is currently in use.

     See also: *note isguirunning: XREFisguirunning.

 -- Function File: DATA = guidata (H)
 -- Function File: 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.

 -- Function File: HDATA = guihandles (H)
 -- Function File: 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.

 -- Built-in Function: 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.

 -- Built-in Function: isguirunning ()
     Return true if Octave is running in GUI mode and false otherwise.

     See also: *note have_window_system: XREFhave_window_system.

 -- Function File: uiwait
 -- Function File: uiwait (H)
 -- Function File: 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.

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

 -- Built-in Function: waitfor (H)
 -- Built-in Function: waitfor (H, PROP)
 -- Built-in Function: waitfor (H, PROP, VALUE)
 -- Built-in Function: 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 being
     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,
     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,  Prev: GUI Utility Functions,  Up: GUI Development

35.5 User-Defined Preferences
=============================

 -- Function File: getpref (GROUP, PREF, DEFAULT)
     Return the preference value corresponding to the named preference
     PREF in the preference group GROUP.

     The named preference group must be a character string.

     If PREF does not exist in GROUP and DEFAULT is specified, return
     DEFAULT.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding default value DEFAULT may be
     any value, or, if PREF is a cell array of strings, 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.

 -- Function File: setpref (GROUP, PREF, VAL)
     Set a preference PREF to the given VAL in the named preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, 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.

 -- Function File: addpref (GROUP, PREF, VAL)
     Add a preference PREF and associated value VAL to the named
     preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, 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.

 -- Function File: rmpref (GROUP)
 -- Function File: rmpref (GROUP, PREF)
     Remove the named preference PREF from the preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character 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.

 -- Function File: ispref (GROUP, PREF)
     Return true if the named preference PREF exists in the preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character 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.

 -- Command: prefdir
 -- Command: DIR = prefdir
     Return the directory that contains the preferences for Octave.

     Examples:

     Display the preferences directory

          prefdir

     Change to the preferences folder

          cd (prefdir)

     See also: *note getpref: XREFgetpref, *note setpref: XREFsetpref,
     *note addpref: XREFaddpref, *note rmpref: XREFrmpref, *note ispref:
     XREFispref.

 -- Command: preferences
     Display the GUI preferences dialog window for Octave.


File: octave.info,  Node: System Utilities,  Next: Java Interface,  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 Savings Time flag.

'zone'
     Time zone.

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

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

     See also: *note strftime: 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.

 -- Function File: t = now ()
     Return the current local date/time as a serial day number (see
     'datenum').

     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.

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

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

     See also: *note asctime: XREFasctime, *note time: XREFtime, *note
     localtime: XREFlocaltime.

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

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

     See also: *note strftime: 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.

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

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

     See also: *note strftime: 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.

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

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

     See also: *note strftime: 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.

 -- Function File: asctime (TM_STRUCT)
     Convert a time structure to a string using the following format:
     "ddd mmm mm HH:MM:SS yyyy".  For example:

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

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

     See also: *note ctime: XREFctime, *note localtime: XREFlocaltime,
     *note time: XREFtime.

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

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

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

     Literal character fields:

     '%%'
          % character.

     '%n'
          Newline character.

     '%t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

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

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

     Time fields:

     '%H'
          Hour (00-23).

     '%I'
          Hour (01-12).

     '%k'
          Hour (0-23).

     '%l'
          Hour (1-12).

     '%M'
          Minute (00-59).

     '%p'
          Locale's AM or PM.

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

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

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

     '%S'
          Second (00-61).

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

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

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

     Date fields:

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

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

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

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

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

     '%C'
          Century (00-99).

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

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

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

     '%h'
          Same as %b.

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

     '%m'
          Month (01-12).

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

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

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

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

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

     '%Y'
          Year (1970-).

     See also: *note strptime: 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.

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

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

     See also: *note strftime: 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.

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

     For example:

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

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

     See also: *note now: XREFnow, *note date: XREFdate, *note datevec:
     XREFdatevec.

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

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

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

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

     See also: *note tic: XREFtic, *note toc: XREFtoc, *note clock:
     XREFclock, *note cputime: XREFcputime, *note addtodate:
     XREFaddtodate.

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

     See also: *note tic: XREFtic, *note toc: XREFtoc.

 -- Function File: is_leap_year ()
 -- Function File: 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.

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

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

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

     If called with one output argument, 'tic' returns a scalar of type
     'uint64' that may be later passed to 'toc'.

          id = tic; sleep (5); toc (id)
                => 5.0010

     Calling 'tic' and 'toc' 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.

 -- Built-in Function: pause ()
 -- Built-in Function: pause (N)
     Suspend the execution of the program for N seconds.

     N is a positive real value and may be a fraction of a second.  If
     invoked without an input arguments then the program is suspended
     until a character is typed.

     The following example prints a message and then waits 5 seconds
     before clearing the screen.

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

     See also: *note kbhit: XREFkbhit, *note sleep: XREFsleep.

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

     See also: *note usleep: XREFusleep, *note pause: XREFpause.

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

     See also: *note sleep: XREFsleep, *note pause: XREFpause.

 -- Function File: DAYS = datenum (DATEVEC)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE,
          SECOND)
 -- Function File: DAYS = datenum ("datestr")
 -- Function File: DAYS = datenum ("datestr", F)
 -- Function File: DAYS = datenum ("datestr", P)
 -- Function File: [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 (see 'datevec'), datestr (see
     'datestr'), or directly specified as input.

     When processing input datestrings, F is the format string used to
     interpret date strings (see 'datestr').  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.

     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.

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

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

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

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

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

     Code    Format                           Example
     -------------------------------------------------------------------
     0       dd-mmm-yyyy HH:MM:SS             07-Sep-2000 15:38:09
     1       dd-mmm-yyyy                      07-Sep-2000
     2       mm/dd/yy                         09/07/00
     3       mmm                              Sep
     4       m                                S
     5       mm                               09
     6       mm/dd                            09/07
     7       dd                               07
     8       ddd                              Thu
     9       d                                T
     10      yyyy                             2000
     11      yy                               00
     12      mmmyy                            Sep00
     13      HH:MM:SS                         15:38:09
     14      HH:MM:SS PM                      03:38:09 PM
     15      HH:MM                            15:38
     16      HH:MM PM                         03:38 PM
     17      QQ-YY                            Q3-00
     18      QQ                               Q3
     19      dd/mm                            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 if PM is set        09:00
             and not padded with zeros otherwise                9:00 AM
     MM      Minute of hour (padded with zeros)                 10:05
     SS      Second of minute (padded with zeros)               10:05:03
     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 nor 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.

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

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

     F is the format string used to interpret date strings (see
     'datestr').  If DATE is a string, but no format 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.

     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.

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

 -- Function File: C = calendar ()
 -- Function File: C = calendar (D)
 -- Function File: C = calendar (Y, M)
 -- Function File: 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.

 -- Function File: [N, S] = weekday (D)
 -- Function File: [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.

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

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

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr.


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

36.2 Filesystem Utilities
=========================

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

 -- Function File: movefile (F1)
 -- Function File: movefile (F1, F2)
 -- Function File: movefile (F1, F2, 'f')
 -- Function File: [STATUS, MSG, MSGID] = movefile (...)
     Move the source files or directories F1 to the destination F2.

     The name F1 may contain globbing patterns.  If F1 expands to
     multiple file names, F2 must be a directory.  If no destination F2
     is specified then the destination is the present working directory.
     If F2 is a file name then F1 is renamed to F2.

     When the force flag 'f' is given any existing files will be
     overwritten without prompting.

     If successful, STATUS is 1, and MSG, MSGID are empty character
     strings ("").  Otherwise, STATUS is 0, MSG contains a
     system-dependent error message, and MSGID contains a unique message
     identifier.  Note that the status code is exactly opposite that of
     the 'system' command.

     See also: *note rename: XREFrename, *note copyfile: XREFcopyfile,
     *note unlink: XREFunlink, *note delete: XREFdelete, *note glob:
     XREFglob.

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

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

     See also: *note movefile: XREFmovefile, *note copyfile:
     XREFcopyfile, *note ls: XREFls, *note dir: XREFdir.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, 'f')
     Copy the source files or directories F1 to the destination F2.

     The name F1 may contain globbing patterns.  If F1 expands to
     multiple file names, F2 must be a directory.

     When the force flag 'f' is given any existing files will be
     overwritten without prompting.

     If successful, STATUS is 1, and MSG, MSGID are empty character
     strings ("").  Otherwise, STATUS is 0, MSG contains a
     system-dependent error message, and MSGID contains a unique message
     identifier.  Note that the status code is exactly opposite that of
     the 'system' command.

     See also: *note movefile: XREFmovefile, *note rename: XREFrename,
     *note unlink: XREFunlink, *note delete: XREFdelete, *note glob:
     XREFglob.

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

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

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

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

     See also: *note symlink: XREFsymlink, *note unlink: XREFunlink,
     *note readlink: XREFreadlink, *note lstat: XREFlstat.

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

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

     See also: *note link: XREFlink, *note unlink: XREFunlink, *note
     readlink: XREFreadlink, *note lstat: XREFlstat.

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

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

     See also: *note lstat: XREFlstat, *note symlink: XREFsymlink, *note
     link: XREFlink, *note unlink: XREFunlink, *note delete: XREFdelete.

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

     If no PARENT directory is specified the present working directory
     is used.

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

     See also: *note rmdir: XREFrmdir, *note pwd: XREFpwd, *note cd:
     XREFcd.

 -- Built-in Function: rmdir DIR
 -- Built-in Function: rmdir (DIR, "s")
 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (...)
     Remove the directory named DIR.

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

     If the optional second parameter is supplied with value "s",
     recursively remove all subdirectories as well.

     See also: *note mkdir: XREFmkdir, *note confirm_recursive_rmdir:
     XREFconfirm_recursive_rmdir, *note pwd: XREFpwd.

 -- Built-in Function: VAL = confirm_recursive_rmdir ()
 -- Built-in Function: OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
 -- Built-in Function: confirm_recursive_rmdir (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will ask for confirmation before recursively removing a directory
     tree.

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

 -- Built-in Function: mkfifo (NAME, MODE)
 -- Built-in Function: [ERR, MSG] = mkfifo (NAME, MODE)
     Create a FIFO special file named NAME with file mode MODE

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

     See also: *note pipe: XREFpipe.

 -- Built-in Function: umask (MASK)
     Set the permission mask for file creation.

     The parameter MASK is an integer, interpreted as an octal number.
     If successful, returns the previous value of the mask (as an
     integer to be interpreted as an octal number); otherwise an error
     message is printed.

     See also: *note fopen: XREFfopen, *note mkdir: XREFmkdir.

 -- Built-in Function: [INFO, ERR, MSG] = stat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = stat (FID)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FID)
     Return a structure INFO containing the following information about
     FILE or file identifier FID.

     'dev'
          ID of device containing a directory entry for this file.

     'ino'
          File number of the file.

     'mode'
          File mode, as an integer.  Use the functions 'S_ISREG',
          'S_ISDIR', 'S_ISCHR', 'S_ISBLK', 'S_ISFIFO', 'S_ISLNK', or 'S_ISSOCK'
          to extract information from this value.

     'modestr'
          File mode, as a string of ten letters or dashes as would be
          returned by 'ls -l'.

     'nlink'
          Number of links.

     'uid'
          User ID of file's owner.

     'gid'
          Group ID of file's group.

     'rdev'
          ID of device for block or character special files.

     'size'
          Size in bytes.

     'atime'
          Time of last access in the same form as time values returned
          from 'time'.  *Note Timing Utilities::.

     'mtime'
          Time of last modification in the same form as time values
          returned from 'time'.  *Note Timing Utilities::.

     'ctime'
          Time of last file status change in the same form as time
          values returned from 'time'.  *Note Timing Utilities::.

     'blksize'
          Size of blocks in the file.

     'blocks'
          Number of blocks allocated for file.

     If the call is successful ERR is 0 and MSG is an empty string.  If
     the file does not exist, or some other error occurs, INFO is an
     empty matrix, ERR is -1, and MSG contains the corresponding system
     error message.

     If FILE is a symbolic link, 'stat' will return information about
     the actual file that is referenced by the link.  Use 'lstat' if you
     want information about the symbolic link itself.

     For example:

          [info, err, msg] = stat ("/vmlinuz")
            => info =
               {
                 atime = 855399756
                 rdev = 0
                 ctime = 847219094
                 uid = 0
                 size = 389218
                 blksize = 4096
                 mtime = 847219094
                 gid = 6
                 nlink = 1
                 blocks = 768
                 mode = -rw-r--r--
                 modestr = -rw-r--r--
                 ino = 9316
                 dev = 2049
               }
            => err = 0
            => msg =

     See also: *note lstat: XREFlstat, *note ls: XREFls, *note dir:
     XREFdir.

 -- Built-in Function: S_ISBLK (MODE)
     Return true if MODE corresponds to a block device.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISCHR (MODE)
     Return true if MODE corresponds to a character device.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISDIR (MODE)
     Return true if MODE corresponds to a directory.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISFIFO (MODE)
     Return true if MODE corresponds to a fifo.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISLNK (MODE)
     Return true if MODE corresponds to a symbolic link.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISREG (MODE)
     Return true if MODE corresponds to a regular file.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISSOCK (MODE)
     Return true if MODE corresponds to a socket.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Function File: [STATUS, RESULT, MSGID] = fileattrib (FILE)
     Return information about FILE.

     If successful, STATUS is 1, with RESULT containing a structure with
     the following fields:

     'Name'
          Full name of FILE.

     'archive'
          True if FILE is an archive (Windows).

     'system'
          True if FILE is a system file (Windows).

     'hidden'
          True if FILE is a hidden file (Windows).

     'directory'
          True if FILE is a directory.

     'UserRead'
     'GroupRead'
     'OtherRead'
          True if the user (group; other users) has read permission for
          FILE.

     'UserWrite'
     'GroupWrite'
     'OtherWrite'
          True if the user (group; other users) has write permission for
          FILE.

     'UserExecute'
     'GroupExecute'
     'OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.

     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

     With no input arguments, return information about the current
     directory.

     If FILE contains globbing characters, return information about all
     the matching files.

     See also: *note glob: XREFglob.

 -- Function File: isdir (F)
     Return true if F is a directory.

     See also: *note exist: XREFexist, *note stat: XREFstat, *note
     is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename.

 -- Built-in Function: FILES = readdir (DIR)
 -- Built-in Function: [FILES, ERR, MSG] = readdir (DIR)
     Return the names of files in the directory DIR as a cell array of
     strings.

     If an error occurs, return an empty cell array in FILES.  If
     successful, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     See also: *note ls: XREFls, *note dir: XREFdir, *note glob:
     XREFglob, *note what: XREFwhat.

 -- Built-in Function: glob (PATTERN)
     Given an array of pattern strings (as a char array or a cell array)
     in PATTERN, return a cell array of file names that match any of
     them, or an empty cell array if no patterns match.  The pattern
     strings are interpreted as filename globbing patterns (as they are
     used by Unix shells).  Within a pattern

     '*'
          matches any string, including the null string,

     '?'
          matches any single character, and

     '[...]'
          matches any of the enclosed characters.

     Tilde expansion is performed on each of the patterns before looking
     for matching file names.  For example:

          ls
             =>
                file1  file2  file3  myfile1 myfile1b
          glob ("*file1")
             =>
                {
                  [1,1] = file1
                  [2,1] = myfile1
                }
          glob ("myfile?")
             =>
                {
                  [1,1] = myfile1
                }
          glob ("file[12]")
             =>
                {
                  [1,1] = file1
                  [2,1] = file2
                }

     See also: *note ls: XREFls, *note dir: XREFdir, *note readdir:
     XREFreaddir, *note what: XREFwhat.

 -- Built-in Function: file_in_path (PATH, FILE)
 -- Built-in Function: file_in_path (PATH, FILE, "all")
     Return the absolute name of FILE if it can be found in PATH.  The
     value of PATH should be a colon-separated list of directories in
     the format described for 'path'.  If no file is found, return an
     empty character string.  For example:

          file_in_path (EXEC_PATH, "sh")
               => "/bin/sh"

     If the second argument is a cell array of strings, search each
     directory of the path for element of the cell array and return the
     first that matches.

     If the third optional argument "all" is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

     See also: *note file_in_loadpath: XREFfile_in_loadpath, *note
     dir_in_loadpath: XREFdir_in_loadpath, *note path: XREFpath.

 -- Built-in Function: filesep ()
 -- Built-in Function: filesep ("all")
     Return the system-dependent character used to separate directory
     names.

     If "all" is given, the function returns all valid file separators
     in the form of a string.  The list of file separators is
     system-dependent.  It is '/' (forward slash) under UNIX or
     Mac OS X, '/' and '\' (forward and backward slashes) under Windows.

     See also: *note pathsep: XREFpathsep.

 -- Built-in Function: VAL = filemarker ()
 -- Built-in Function: OLD_VAL = filemarker (NEW_VAL)
 -- Built-in Function: filemarker (NEW_VAL, "local")
     Query or set the character used to separate the filename from the
     subfunction names contained within the file.  By default this is
     the character '>'.  This can be used in a generic manner to
     interact with subfunctions.  For example,

          help (["myfunc", filemarker, "mysubfunc"])

     returns the help string associated with the subfunction 'mysubfunc'
     located in the file 'myfunc.m'.

     'filemarker' is also useful during debugging for placing
     breakpoints within subfunctions or nested functions.  For example,

          dbstop (["myfunc", filemarker, "mysubfunc"])

     will set a breakpoint at the first line of the subfunction
     'mysubfunc'.

     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.

 -- Function File: [DIR, NAME, EXT] = fileparts (FILENAME)
     Return the directory, name, and extension components of FILENAME.

     The input FILENAME is a string which is parsed.  There is no
     attempt to check whether the filename or directory specified
     actually exists.

     See also: *note fullfile: XREFfullfile, *note filesep: XREFfilesep.

 -- Function File: FILENAME = fullfile (DIR1, DIR2, ..., FILE)
 -- Function File: FILENAMES = fullfile (..., FILES)
     Build complete filename from separate parts.

     Joins any number of path components intelligently.  The return
     value is the concatenation of each component with exactly one file
     separator between each non empty part and at most one leading
     and/or trailing file separator.

     If the last component part is a cell array, returns a cell array of
     filepaths, one for each element in the last component, e.g.:

          fullfile ("/home/username", "data", {"f1.csv", "f2.csv", "f3.csv"})
          =>  /home/username/data/f1.csv
              /home/username/data/f2.csv
              /home/username/data/f3.csv

     On Windows systems, while forward slash file separators do work,
     they are replaced by backslashes; in addition drive letters are
     stripped of leading file separators to obtain a valid file path.

     See also: *note fileparts: XREFfileparts, *note filesep:
     XREFfilesep.

 -- Built-in Function: tilde_expand (STRING)
     Perform tilde expansion on STRING.  If STRING begins with a tilde
     character, ('~'), all of the characters preceding the first slash
     (or all characters, if there is no slash) are treated as a possible
     user name, and the tilde and the following characters up to the
     slash are replaced by the home directory of the named user.  If the
     tilde is followed immediately by a slash, the tilde is replaced by
     the home directory of the user running Octave.  For example:

          tilde_expand ("~joeuser/bin")
               => "/home/joeuser/bin"
          tilde_expand ("~/bin")
               => "/home/jwe/bin"

 -- Built-in Function: [CNAME, STATUS, MSG] = canonicalize_file_name
          (FNAME)
     Return the canonical name of file FNAME.  If the file does not
     exist the empty string ("") is returned.

     See also: *note make_absolute_filename: XREFmake_absolute_filename,
     *note is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename.

 -- Built-in Function: make_absolute_filename (FILE)
     Return the full name of FILE beginning from the root of the file
     system.  No check is done for the existence of FILE.

     See also: *note canonicalize_file_name: XREFcanonicalize_file_name,
     *note is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename, *note
     isdir: XREFisdir.

 -- Built-in Function: is_absolute_filename (FILE)
     Return true if FILE is an absolute filename.

     See also: *note is_rooted_relative_filename:
     XREFis_rooted_relative_filename, *note make_absolute_filename:
     XREFmake_absolute_filename, *note isdir: XREFisdir.

 -- Built-in Function: is_rooted_relative_filename (FILE)
     Return true if FILE is a rooted-relative filename.

     See also: *note is_absolute_filename: XREFis_absolute_filename,
     *note make_absolute_filename: XREFmake_absolute_filename, *note
     isdir: XREFisdir.

 -- Function File: CURRENT_STATE = recycle ()
 -- Function File: OLD_STATE = recycle (NEW_STATE)
     Query or set the preference for recycling deleted files.

     When recycling is enabled, commands which would permanently erase
     files instead move them to a temporary location (such as the
     directory labeled Trash).

     Programming Note: This function is provided for MATLAB
     compatibility, but recycling is not implemented in Octave.  To help
     avoid accidental data loss an error will be raised if an attempt is
     made to enable file recycling.

     See also: *note delete: XREFdelete, *note rmdir: XREFrmdir.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Valid filetype extensions:

     'bz'
     'bz2'
          bzip archive

     'gz'
          gzip archive

     'tar'
          tar archive

     'tarbz'
     'tarbz2'
     'tbz'
     'tbz2'
          tar + bzip archive

     'targz'
     'tgz'
          tar + gzip archive

     'z'
          compress archive

     'zip'
          zip archive

     The optional return value is a list of FILES unpacked.

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

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

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

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

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

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


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

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

* Menu:

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

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


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

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

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

 -- Function File: F = ftp (HOST)
 -- Function File: F = ftp (HOST, USERNAME, PASSWORD)
     Connect to the FTP server HOST with USERNAME and PASSWORD.  If
     USERNAME and PASSWORD are not specified, user "anonymous" with no
     password is used.  The returned FTP object F represents the
     established FTP connection.

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

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

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

     F is an FTP object returned by the 'ftp' function.

 -- Function File: mget (F, FILE)
 -- Function File: mget (F, DIR)
 -- Function File: mget (F, REMOTE_NAME, TARGET)
     Download a remote file FILE or directory DIR to the local directory
     on the FTP connection F.  F is an FTP object returned by the 'ftp'
     function.

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

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

 -- Function File: mput (F, FILE)
     Upload the local file FILE into the current remote directory on the
     FTP connection F.  F is an FTP object returned by the ftp function.

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

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

     F is an FTP object returned by the 'ftp' function.

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

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

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

     F is an FTP object returned by the 'ftp' function.

 -- Function File: ascii (F)
     Set the FTP connection F to use ASCII mode for transfers.  ASCII
     mode is only appropriate for text files as it will convert the
     remote host's newline representation to the local host's newline
     representation.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: binary (F)
     Set the FTP connection F to use binary mode for transfers.  In
     binary mode there is no conversion of newlines from the remote
     representation to the local representation.

     F is an FTP object returned by the 'ftp' function.

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

     F is an FTP object returned by the 'ftp' function.

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

     F is an FTP object returned by the ftp function.

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

     F is an FTP object returned by the 'ftp' function.

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

     F is an FTP object returned by the 'ftp' function.


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

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

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

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

     The variable SUCCESS is 1 if the download was successful, otherwise
     it is 0 in which case MESSAGE contains an error message.  If no
     output argument is specified and an error occurs, then the error is
     signaled through Octave's error handling mechanism.

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

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

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

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

     See also: *note urlwrite: XREFurlwrite.

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

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

     The full path of the downloaded file is returned in F.  The
     variable SUCCESS is 1 if the download was successful, otherwise it
     is 0 in which case MESSAGE contains an error message.  If no output
     argument is specified and an error occurs, then the error is
     signaled through Octave's error handling mechanism.

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

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

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

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

     See also: *note urlread: XREFurlread.


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

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

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

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

     See also: *note base64_decode: XREFbase64_decode.

 -- Built-in Function: X = base64_decode (S)
 -- Built-in Function: X = base64_decode (S, DIMS)
     Decode the double matrix or array X from the base64 encoded string
     S.  The optional input parameter DIMS should be a vector containing
     the dimensions of the decoded array.

     See also: *note base64_encode: XREFbase64_encode.


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

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

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

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

 -- Built-in Function: system ("STRING")
 -- Built-in Function: system ("STRING", RETURN_OUTPUT)
 -- Built-in Function: system ("STRING", RETURN_OUTPUT, TYPE)
 -- Built-in Function: [STATUS, OUTPUT] = system (...)
     Execute a shell command specified by STRING.  If the optional
     argument TYPE is "async", the process is started in the background
     and the process ID of the child process is returned immediately.
     Otherwise, the child process is started and Octave waits until it
     exits.  If the TYPE argument is omitted, it defaults to the value
     "sync".

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

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

     or

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Recognized file types are

     '.m'
          Open file in the editor.

     '.mat'
          Load the file in the base workspace.

     '.exe'
          Execute the program (on Windows systems only).

     Other file types are opened in the appropriate external
     application.

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

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

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

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

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

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

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.  The name of the command to run
     is given by COMMAND.  The file identifier corresponding to the
     input or output stream of the process is returned in FID.  The
     argument MODE may be

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

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

     For example:

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

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

     See also: *note popen2: XREFpopen2.

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

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

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

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.  The name of the
     process is given by COMMAND, and ARGS is an array of strings
     containing options for the command.  The file identifiers for the
     input and output streams of the subprocess are returned in IN and
     OUT.  If execution of the command is successful, PID contains the
     process ID of the subprocess.  Otherwise, PID is -1.

     For example:

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

             -| these
             -| strings
             -| some
             -| are

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

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

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
 -- Built-in Function: EXEC_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated
     list of directories to append to the shell PATH when executing
     external programs.  The initial value of is taken from the
     environment variable 'OCTAVE_EXEC_PATH', but that value can be
     overridden by the command line argument '--exec-path PATH'.

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

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

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

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

     Fork can return one of the following values:

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

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

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

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.  Calling 'exec' without
     first calling 'fork' will terminate your current Octave process and
     replace it with the program named by FILE.  For example,

          exec ("ls" "-l")

     will run 'ls' and return you to your shell prompt.

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

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

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

     See also: *note mkfifo: XREFmkfifo.

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

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

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

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

     -1
          Wait for any child process.

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

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

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

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

     'WNOHANG'
          Do not hang if status is not immediately available.

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

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

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

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

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

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

 -- Built-in Function: WCOREDUMP (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     produced a core dump.  This function should only be employed if
     'WIFSIGNALED' returned true.  The macro used to implement this
     function is not specified in POSIX.1-2001 and is not available on
     some Unix implementations (e.g., AIX, SunOS).

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

 -- Built-in Function: WEXITSTATUS (STATUS)
     Given STATUS from a call to 'waitpid', return the exit status of
     the child.  This function should only be employed if 'WIFEXITED'
     returned true.

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

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

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

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

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

 -- Built-in Function: WIFSTOPPED (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     process was stopped by delivery of a signal; this is only possible
     if the call was done using 'WUNTRACED' or when the child is being
     traced (see ptrace(2)).

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

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

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

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

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

 -- Built-in Function: WSTOPSIG (STATUS)
     Given STATUS from a call to 'waitpid', return the number of the
     signal which caused the child to stop.  This function should only
     be employed if 'WIFSTOPPED' returned true.

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

 -- Built-in Function: WTERMSIG (STATUS)
     Given STATUS from a call to 'waitpid', return the number of the
     signal that caused the child process to terminate.  This function
     should only be employed if 'WIFSIGNALED' returned true.

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

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

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

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

     The following values may be passed as REQUEST:

     'F_DUPFD'
          Return a duplicate file descriptor.

     'F_GETFD'
          Return the file descriptor flags for FID.

     'F_SETFD'
          Set the file descriptor flags for FID.

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

          'O_RDONLY'
               Open for reading only.

          'O_WRONLY'
               Open for writing only.

          'O_RDWR'
               Open for reading and writing.

          'O_APPEND'
               Append on each write.

          'O_CREAT'
               Create the file if it does not exist.

          'O_NONBLOCK'
               Non-blocking mode.

          'O_SYNC'
               Wait for writes to complete.

          'O_ASYNC'
               Asynchronous I/O.

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

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

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

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

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

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

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

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

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

     Return 0 if successful, otherwise return -1.

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

