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

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

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007
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: Orthogonal Collocation,  Prev: Functions of Multiple Variables,  Up: Numerical Integration

22.2 Orthogonal Collocation
===========================

 -- Loadable Function: [R, AMAT, BMAT, Q] = colloc (N, "left", "right")
     Compute derivative and integral weight matrices for orthogonal
     collocation using the subroutines given in J. Villadsen and M. L.
     Michelsen, `Solution of Differential Equation Models by Polynomial
     Approximation'.

   Here is an example of using `colloc' to generate weight matrices for
solving the second order differential equation U' - ALPHA * U" = 0 with
the boundary conditions U(0) = 0 and U(1) = 1.

   First, we can generate the weight matrices for N points (including
the endpoints of the interval), and incorporate the boundary conditions
in the right hand side (for a specific value of ALPHA).

     n = 7;
     alpha = 0.1;
     [r, a, b] = colloc (n-2, "left", "right");
     at = a(2:n-1,2:n-1);
     bt = b(2:n-1,2:n-1);
     rhs = alpha * b(2:n-1,n) - a(2:n-1,n);

   Then the solution at the roots R is

     u = [ 0; (at - alpha * bt) \ rhs; 1]
          => [ 0.00; 0.004; 0.01 0.00; 0.12; 0.62; 1.00 ]


File: octave.info,  Node: Functions of Multiple Variables,  Next: Orthogonal Collocation,  Prev: Functions of One Variable,  Up: Numerical Integration

22.3 Functions of Multiple Variables
====================================

Octave does not have built-in functions for computing the integral of
functions of multiple variables directly.  It is however possible to
compute the integral of a function of multiple variables using the
functions for one-dimensional integrals.

   To illustrate how the integration can be performed, we will integrate
the function
     f(x, y) = sin(pi*x*y)*sqrt(x*y)
   for x and y between 0 and 1.

   The first approach creates a function that integrates f with respect
to x, and then integrates that function with respect to y.  Since
`quad' is written in Fortran it cannot be called recursively.  This
means that `quad' cannot integrate a function that calls `quad', and
hence cannot be used to perform the double integration.  It is however
possible with `quadl', which is what the following code does.

     function I = g(y)
       I = ones(1, length(y));
       for i = 1:length(y)
         f = @(x) sin(pi.*x.*y(i)).*sqrt(x.*y(i));
         I(i) = quadl(f, 0, 1);
       endfor
     endfunction

     I = quadl("g", 0, 1)
           => 0.30022

   The above process can be simplified with the `dblquad' and
`triplequad' functions for integrals over two and three variables.  For
example

     I =  dblquad (@(x, y) sin(pi.*x.*y).*sqrt(x.*y), 0, 1, 0, 1)
           => 0.30022

 -- Function File:  dblquad (F, XA, XB, YA, YB, TOL, QUADF, ...)
     Numerically evaluate a double integral.  The function over with to
     integrate is defined by `F', and the interval for the integration
     is defined by `[XA, XB, YA, YB]'.  The function F must accept a
     vector X and a scalar Y, and return a vector of the same length as
     X.

     If defined, TOL defines the absolute tolerance to which to which
     to integrate each sub-integral.

     Additional arguments, are passed directly to F.  To use the default
     value for TOL one may pass an empty matrix.

     *See also:* *note triplequad: doc-triplequad, *note quad:
     doc-quad, *note quadv: doc-quadv, *note quadl: doc-quadl, *note
     quadgk: doc-quadgk, *note trapz: doc-trapz.

 -- Function File:  triplequad (F, XA, XB, YA, YB, ZA, ZB, TOL, QUADF,
          ...)
     Numerically evaluate a triple integral.  The function over which to
     integrate is defined by `F', and the interval for the integration
     is defined by `[XA, XB, YA, YB, ZA, ZB]'.  The function F must
     accept a vector X and a scalar Y, and return a vector of the same
     length as X.

     If defined, TOL defines the absolute tolerance to which to which
     to integrate each sub-integral.

     Additional arguments, are passed directly to F.  To use the default
     value for TOL one may pass an empty matrix.

     *See also:* *note dblquad: doc-dblquad, *note quad: doc-quad,
     *note quadv: doc-quadv, *note quadl: doc-quadl, *note quadgk:
     doc-quadgk, *note trapz: doc-trapz.

   The above mentioned approach works but is fairly slow, and that
problem increases exponentially with the dimensionality the problem.
Another possible solution is to use Orthogonal Collocation as described
in the previous section.  The integral of a function f(x,y) for x and y
between 0 and 1 can be approximated using n points by the sum over
`i=1:n' and `j=1:n' of `q(i)*q(j)*f(r(i),r(j))', where q and r is as
returned by `colloc(n)'.  The generalization to more than two variables
is straight forward.  The following code computes the studied integral
using n=7 points.

     f = @(x,y) sin(pi*x*y').*sqrt(x*y');
     n = 7;
     [t, A, B, q] = colloc(n);
     I = q'*f(t,t)*q;
           => 0.30022

It should be noted that the number of points determines the quality of
the approximation.  If the integration needs to be performed between a
and b instead of 0 and 1, a change of variables is needed.


File: octave.info,  Node: Differential Equations,  Next: Optimization,  Prev: Numerical Integration,  Up: Top

23 Differential Equations
*************************

Octave has built-in functions for solving ordinary differential
equations, and differential-algebraic equations.  All solvers are based
on reliable ODE routines written in Fortran.

* Menu:

* Ordinary Differential Equations::
* Differential-Algebraic Equations::


File: octave.info,  Node: Ordinary Differential Equations,  Next: Differential-Algebraic Equations,  Up: Differential Equations

23.1 Ordinary Differential Equations
====================================

The function `lsode' can be used to solve ODEs of the form

     dx
     -- = f (x, t)
     dt

using Hindmarsh's ODE solver LSODE.

 -- Loadable Function: [X, ISTATE, MSG] = lsode (FCN, X_0, T, T_CRIT)
     Solve the set of differential equations

          dx
          -- = f(x, t)
          dt

     with

          x(t_0) = x_0

     The solution is returned in the matrix X, with each row
     corresponding to an element of the vector T.  The first element of
     T should be t_0 and should correspond to the initial state of the
     system X_0, so that the first row of the output is X_0.

     The first argument, FCN, is a string, inline, or function handle
     that names the function f to call to compute the vector of right
     hand sides for the set of equations.  The function must have the
     form

          XDOT = f (X, T)

     in which XDOT and X are vectors and T is a scalar.

     If FCN is a two-element string array or a two-element cell array
     of strings, inline functions, or function handles, the first
     element names the function f described above, and the second
     element names a function to compute the Jacobian of f.  The
     Jacobian function must have the form

          JAC = j (X, T)

     in which JAC is the matrix of partial derivatives

                       | df_1  df_1       df_1 |
                       | ----  ----  ...  ---- |
                       | dx_1  dx_2       dx_N |
                       |                       |
                       | df_2  df_2       df_2 |
                       | ----  ----  ...  ---- |
                df_i   | dx_1  dx_2       dx_N |
          jac = ---- = |                       |
                dx_j   |  .    .     .    .    |
                       |  .    .      .   .    |
                       |  .    .       .  .    |
                       |                       |
                       | df_N  df_N       df_N |
                       | ----  ----  ...  ---- |
                       | dx_1  dx_2       dx_N |

     The second and third arguments specify the initial state of the
     system, x_0, and the initial value of the independent variable t_0.

     The fourth argument is optional, and may be used to specify a set
     of times that the ODE solver should not integrate past.  It is
     useful for avoiding difficulties with singularities and points
     where there is a discontinuity in the derivative.

     After a successful computation, the value of ISTATE will be 2
     (consistent with the Fortran version of LSODE).

     If the computation is not successful, ISTATE will be something
     other than 2 and MSG will contain additional information.

     You can use the function `lsode_options' to set optional
     parameters for `lsode'.

     *See also:* *note daspk: doc-daspk, *note dassl: doc-dassl, *note
     dasrt: doc-dasrt.

 -- Loadable Function:  lsode_options (OPT, VAL)
     When called with two arguments, this function allows you set
     options parameters for the function `lsode'.  Given one argument,
     `lsode_options' returns the value of the corresponding option.  If
     no arguments are supplied, the names of all the available options
     and their current values are displayed.

     Options include

    `"absolute tolerance"'
          Absolute tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector.

    `"relative tolerance"'
          Relative tolerance parameter.  Unlike the absolute tolerance,
          this parameter may only be a scalar.

          The local error test applied at each integration step is

                 abs (local error in x(i)) <= ...
                     rtol * abs (y(i)) + atol(i)

    `"integration method"'
          A string specifying the method of integration to use to solve
          the ODE system.  Valid values are

         "adams"
         "non-stiff"
               No Jacobian used (even if it is available).

         "bdf"

         "stiff"
               Use stiff backward differentiation formula (BDF) method.
               If a function to compute the Jacobian is not supplied,
               `lsode' will compute a finite difference approximation
               of the Jacobian matrix.

    `"initial step size"'
          The step size to be attempted on the first step (default is
          determined automatically).

    `"maximum order"'
          Restrict the maximum order of the solution method.  If using
          the Adams method, this option must be between 1 and 12.
          Otherwise, it must be between 1 and 5, inclusive.

    `"maximum step size"'
          Setting the maximum stepsize will avoid passing over very
          large regions  (default is not specified).

    `"minimum step size"'
          The minimum absolute step size allowed (default is 0).

    `"step limit"'
          Maximum number of steps allowed (default is 100000).

   Here is an example of solving a set of three differential equations
using `lsode'.  Given the function

     function xdot = f (x, t)

       xdot = zeros (3,1);

       xdot(1) = 77.27 * (x(2) - x(1)*x(2) + x(1) \
                 - 8.375e-06*x(1)^2);
       xdot(2) = (x(3) - x(1)*x(2) - x(2)) / 77.27;
       xdot(3) = 0.161*(x(1) - x(3));

     endfunction

and the initial condition `x0 = [ 4; 1.1; 4 ]', the set of equations
can be integrated using the command

     t = linspace (0, 500, 1000);

     y = lsode ("f", x0, t);

   If you try this, you will see that the value of the result changes
dramatically between T = 0 and 5, and again around T = 305.  A more
efficient set of output points might be

     t = [0, logspace (-1, log10(303), 150), \
             logspace (log10(304), log10(500), 150)];

   See Alan C. Hindmarsh, `ODEPACK, A Systematized Collection of ODE
Solvers', in Scientific Computing, R. S. Stepleman, editor, (1983) for
more information about the inner workings of `lsode'.


File: octave.info,  Node: Differential-Algebraic Equations,  Prev: Ordinary Differential Equations,  Up: Differential Equations

23.2 Differential-Algebraic Equations
=====================================

The function `daspk' can be used to solve DAEs of the form

     0 = f (x-dot, x, t),    x(t=0) = x_0, x-dot(t=0) = x-dot_0

where x-dot is the derivative of x.  The equation is solved using
Petzold's DAE solver DASPK.

 -- Loadable Function: [X, XDOT, ISTATE, MSG] = daspk (FCN, X_0,
          XDOT_0, T, T_CRIT)
     Solve the set of differential-algebraic equations

          0 = f (x, xdot, t)

     with

          x(t_0) = x_0, xdot(t_0) = xdot_0

     The solution is returned in the matrices X and XDOT, with each row
     in the result matrices corresponding to one of the elements in the
     vector T.  The first element of T should be t_0 and correspond to
     the initial state of the system X_0 and its derivative XDOT_0, so
     that the first row of the output X is X_0 and the first row of the
     output XDOT is XDOT_0.

     The first argument, FCN, is a string, inline, or function handle
     that names the function f to call to compute the vector of
     residuals for the set of equations.  It must have the form

          RES = f (X, XDOT, T)

     in which X, XDOT, and RES are vectors, and T is a scalar.

     If FCN is a two-element string array or a two-element cell array
     of strings, inline functions, or function handles, the first
     element names the function f described above, and the second
     element names a function to compute the modified Jacobian

                df       df
          jac = -- + c ------
                dx     d xdot

     The modified Jacobian function must have the form


          JAC = j (X, XDOT, T, C)

     The second and third arguments to `daspk' specify the initial
     condition of the states and their derivatives, and the fourth
     argument specifies a vector of output times at which the solution
     is desired, including the time corresponding to the initial
     condition.

     The set of initial states and derivatives are not strictly
     required to be consistent.  If they are not consistent, you must
     use the `daspk_options' function to provide additional information
     so that `daspk' can compute a consistent starting point.

     The fifth argument is optional, and may be used to specify a set of
     times that the DAE solver should not integrate past.  It is useful
     for avoiding difficulties with singularities and points where
     there is a discontinuity in the derivative.

     After a successful computation, the value of ISTATE will be
     greater than zero (consistent with the Fortran version of DASPK).

     If the computation is not successful, the value of ISTATE will be
     less than zero and MSG will contain additional information.

     You can use the function `daspk_options' to set optional
     parameters for `daspk'.

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

 -- Loadable Function:  daspk_options (OPT, VAL)
     When called with two arguments, this function allows you set
     options parameters for the function `daspk'.  Given one argument,
     `daspk_options' returns the value of the corresponding option.  If
     no arguments are supplied, the names of all the available options
     and their current values are displayed.

     Options include

    `"absolute tolerance"'
          Absolute tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the relative tolerance must also be a vector of the same
          length.

    `"relative tolerance"'
          Relative tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the absolute tolerance must also be a vector of the same
          length.

          The local error test applied at each integration step is

                 abs (local error in x(i))
                      <= rtol(i) * abs (Y(i)) + atol(i)

    `"compute consistent initial condition"'
          Denoting the differential variables in the state vector by
          `Y_d' and the algebraic variables by `Y_a', `ddaspk' can solve
          one of two initialization problems:

            1. Given Y_d, calculate Y_a and Y'_d

            2. Given Y', calculate Y.

          In either case, initial values for the given components are
          input, and initial guesses for the unknown components must
          also be provided as input.  Set this option to 1 to solve the
          first problem, or 2 to solve the second (the default is 0, so
          you must provide a set of initial conditions that are
          consistent).

          If this option is set to a nonzero value, you must also set
          the `"algebraic variables"' option to declare which variables
          in the problem are algebraic.

    `"use initial condition heuristics"'
          Set to a nonzero value to use the initial condition
          heuristics options described below.

    `"initial condition heuristics"'
          A vector of the following parameters that can be used to
          control the initial condition calculation.

         `MXNIT'
               Maximum number of Newton iterations (default is 5).

         `MXNJ'
               Maximum number of Jacobian evaluations (default is 6).

         `MXNH'
               Maximum number of values of the artificial stepsize
               parameter to be tried if the `"compute consistent
               initial condition"' option has been set to 1 (default is
               5).

               Note that the maximum total number of Newton iterations
               allowed is `MXNIT*MXNJ*MXNH' if the `"compute consistent
               initial condition"' option has been set to 1 and
               `MXNIT*MXNJ' if it is set to 2.

         `LSOFF'
               Set to a nonzero value to disable the linesearch
               algorithm (default is 0).

         `STPTOL'
               Minimum scaled step in linesearch algorithm (default is
               eps^(2/3)).

         `EPINIT'
               Swing factor in the Newton iteration convergence test.
               The test is applied to the residual vector,
               premultiplied by the approximate Jacobian.  For
               convergence, the weighted RMS norm of this vector
               (scaled by the error weights) must be less than
               `EPINIT*EPCON', where `EPCON' = 0.33 is the analogous
               test constant used in the time steps.  The default is
               `EPINIT' = 0.01.

    `"print initial condition info"'
          Set this option to a nonzero value to display detailed
          information about the initial condition calculation (default
          is 0).

    `"exclude algebraic variables from error test"'
          Set to a nonzero value to exclude algebraic variables from
          the error test.  You must also set the `"algebraic
          variables"' option to declare which variables in the problem
          are algebraic (default is 0).

    `"algebraic variables"'
          A vector of the same length as the state vector.  A nonzero
          element indicates that the corresponding element of the state
          vector is an algebraic variable (i.e., its derivative does
          not appear explicitly in the equation set.

          This option is required by the `compute consistent initial
          condition"' and `"exclude algebraic variables from error
          test"' options.

    `"enforce inequality constraints"'
          Set to one of the following values to enforce the inequality
          constraints specified by the `"inequality constraint types"'
          option (default is 0).

            1. To have constraint checking only in the initial
               condition calculation.

            2. To enforce constraint checking during the integration.

            3. To enforce both options 1 and 2.

    `"inequality constraint types"'
          A vector of the same length as the state specifying the type
          of inequality constraint.  Each element of the vector
          corresponds to an element of the state and should be assigned
          one of the following codes

         -2
               Less than zero.

         -1
               Less than or equal to zero.

         0
               Not constrained.

         1
               Greater than or equal to zero.

         2
               Greater than zero.

          This option only has an effect if the `"enforce inequality
          constraints"' option is nonzero.

    `"initial step size"'
          Differential-algebraic problems may occasionally suffer from
          severe scaling difficulties on the first step.  If you know a
          great deal about the scaling of your problem, you can help to
          alleviate this problem by specifying an initial stepsize
          (default is computed automatically).

    `"maximum order"'
          Restrict the maximum order of the solution method.  This
          option must be between 1 and 5, inclusive (default is 5).

    `"maximum step size"'
          Setting the maximum stepsize will avoid passing over very
          large regions (default is not specified).

   Octave also includes DASSL, an earlier version of DASPK, and DASRT,
which can be used to solve DAEs with constraints (stopping conditions).

 -- Loadable Function: [X, XDOT, ISTATE, MSG] = dassl (FCN, X_0,
          XDOT_0, T, T_CRIT)
     Solve the set of differential-algebraic equations

          0 = f (x, xdot, t)

     with

          x(t_0) = x_0, xdot(t_0) = xdot_0

     The solution is returned in the matrices X and XDOT, with each row
     in the result matrices corresponding to one of the elements in the
     vector T.  The first element of T should be t_0 and correspond to
     the initial state of the system X_0 and its derivative XDOT_0, so
     that the first row of the output X is X_0 and the first row of the
     output XDOT is XDOT_0.

     The first argument, FCN, is a string, inline, or function handle
     that names the function f to call to compute the vector of
     residuals for the set of equations.  It must have the form

          RES = f (X, XDOT, T)

     in which X, XDOT, and RES are vectors, and T is a scalar.

     If FCN is a two-element string array or a two-element cell array
     of strings, inline functions, or function handles, the first
     element names the function f described above, and the second
     element names a function to compute the modified Jacobian

                df       df
          jac = -- + c ------
                dx     d xdot

     The modified Jacobian function must have the form


          JAC = j (X, XDOT, T, C)

     The second and third arguments to `dassl' specify the initial
     condition of the states and their derivatives, and the fourth
     argument specifies a vector of output times at which the solution
     is desired, including the time corresponding to the initial
     condition.

     The set of initial states and derivatives are not strictly
     required to be consistent.  In practice, however, DASSL is not
     very good at determining a consistent set for you, so it is best
     if you ensure that the initial values result in the function
     evaluating to zero.

     The fifth argument is optional, and may be used to specify a set of
     times that the DAE solver should not integrate past.  It is useful
     for avoiding difficulties with singularities and points where
     there is a discontinuity in the derivative.

     After a successful computation, the value of ISTATE will be
     greater than zero (consistent with the Fortran version of DASSL).

     If the computation is not successful, the value of ISTATE will be
     less than zero and MSG will contain additional information.

     You can use the function `dassl_options' to set optional
     parameters for `dassl'.

     *See also:* *note daspk: doc-daspk, *note dasrt: doc-dasrt, *note
     lsode: doc-lsode.

 -- Loadable Function:  dassl_options (OPT, VAL)
     When called with two arguments, this function allows you set
     options parameters for the function `dassl'.  Given one argument,
     `dassl_options' returns the value of the corresponding option.  If
     no arguments are supplied, the names of all the available options
     and their current values are displayed.

     Options include

    `"absolute tolerance"'
          Absolute tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the relative tolerance must also be a vector of the same
          length.

    `"relative tolerance"'
          Relative tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the absolute tolerance must also be a vector of the same
          length.

          The local error test applied at each integration step is

                 abs (local error in x(i))
                      <= rtol(i) * abs (Y(i)) + atol(i)

    `"compute consistent initial condition"'
          If nonzero, `dassl' will attempt to compute a consistent set
          of initial conditions.  This is generally not reliable, so it
          is best to provide a consistent set and leave this option set
          to zero.

    `"enforce nonnegativity constraints"'
          If you know that the solutions to your equations will always
          be nonnegative, it may help to set this parameter to a nonzero
          value.  However, it is probably best to try leaving this
          option set to zero first, and only setting it to a nonzero
          value if that doesn't work very well.

    `"initial step size"'
          Differential-algebraic problems may occasionally suffer from
          severe scaling difficulties on the first step.  If you know a
          great deal about the scaling of your problem, you can help to
          alleviate this problem by specifying an initial stepsize.

    `"maximum order"'
          Restrict the maximum order of the solution method.  This
          option must be between 1 and 5, inclusive.

    `"maximum step size"'
          Setting the maximum stepsize will avoid passing over very
          large regions  (default is not specified).

    `"step limit"'
          Maximum number of integration steps to attempt on a single
          call to the underlying Fortran code.

 -- Loadable Function: [X, XDOT, T_OUT, ISTAT, MSG] = dasrt (FCN [, G],
          X_0, XDOT_0, T [, T_CRIT])
     Solve the set of differential-algebraic equations

          0 = f (x, xdot, t)

     with

          x(t_0) = x_0, xdot(t_0) = xdot_0

     with functional stopping criteria (root solving).

     The solution is returned in the matrices X and XDOT, with each row
     in the result matrices corresponding to one of the elements in the
     vector T_OUT.  The first element of T should be t_0 and correspond
     to the initial state of the system X_0 and its derivative XDOT_0,
     so that the first row of the output X is X_0 and the first row of
     the output XDOT is XDOT_0.

     The vector T provides an upper limit on the length of the
     integration.  If the stopping condition is met, the vector T_OUT
     will be shorter than T, and the final element of T_OUT will be the
     point at which the stopping condition was met, and may not
     correspond to any element of the vector T.

     The first argument, FCN, is a string, inline, or function handle
     that names the function f to call to compute the vector of
     residuals for the set of equations.  It must have the form

          RES = f (X, XDOT, T)

     in which X, XDOT, and RES are vectors, and T is a scalar.

     If FCN is a two-element string array or a two-element cell array
     of strings, inline functions, or function handles, the first
     element names the function f described above, and the second
     element names a function to compute the modified Jacobian

                df       df
          jac = -- + c ------
                dx     d xdot

     The modified Jacobian function must have the form


          JAC = j (X, XDOT, T, C)

     The optional second argument names a function that defines the
     constraint functions whose roots are desired during the
     integration.  This function must have the form

          G_OUT = g (X, T)

     and return a vector of the constraint function values.  If the
     value of any of the constraint functions changes sign, DASRT will
     attempt to stop the integration at the point of the sign change.

     If the name of the constraint function is omitted, `dasrt' solves
     the same problem as `daspk' or `dassl'.

     Note that because of numerical errors in the constraint functions
     due to roundoff and integration error, DASRT may return false
     roots, or return the same root at two or more nearly equal values
     of T.  If such false roots are suspected, the user should consider
     smaller error tolerances or higher precision in the evaluation of
     the constraint functions.

     If a root of some constraint function defines the end of the
     problem, the input to DASRT should nevertheless allow integration
     to a point slightly past that root, so that DASRT can locate the
     root by interpolation.

     The third and fourth arguments to `dasrt' specify the initial
     condition of the states and their derivatives, and the fourth
     argument specifies a vector of output times at which the solution
     is desired, including the time corresponding to the initial
     condition.

     The set of initial states and derivatives are not strictly
     required to be consistent.  In practice, however, DASSL is not
     very good at determining a consistent set for you, so it is best
     if you ensure that the initial values result in the function
     evaluating to zero.

     The sixth argument is optional, and may be used to specify a set of
     times that the DAE solver should not integrate past.  It is useful
     for avoiding difficulties with singularities and points where
     there is a discontinuity in the derivative.

     After a successful computation, the value of ISTATE will be
     greater than zero (consistent with the Fortran version of DASSL).

     If the computation is not successful, the value of ISTATE will be
     less than zero and MSG will contain additional information.

     You can use the function `dasrt_options' to set optional
     parameters for `dasrt'.

     *See also:* *note daspk: doc-daspk, *note dasrt: doc-dasrt, *note
     lsode: doc-lsode.

 -- Loadable Function:  dasrt_options (OPT, VAL)
     When called with two arguments, this function allows you set
     options parameters for the function `dasrt'.  Given one argument,
     `dasrt_options' returns the value of the corresponding option.  If
     no arguments are supplied, the names of all the available options
     and their current values are displayed.

     Options include

    `"absolute tolerance"'
          Absolute tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the relative tolerance must also be a vector of the same
          length.

    `"relative tolerance"'
          Relative tolerance.  May be either vector or scalar.  If a
          vector, it must match the dimension of the state vector, and
          the absolute tolerance must also be a vector of the same
          length.

          The local error test applied at each integration step is
                 abs (local error in x(i)) <= ...
                     rtol(i) * abs (Y(i)) + atol(i)

    `"initial step size"'
          Differential-algebraic problems may occasionally suffer from
          severe scaling difficulties on the first step.  If you know a
          great deal about the scaling of your problem, you can help to
          alleviate this problem by specifying an initial stepsize.

    `"maximum order"'
          Restrict the maximum order of the solution method.  This
          option must be between 1 and 5, inclusive.

    `"maximum step size"'
          Setting the maximum stepsize will avoid passing over very
          large regions.

    `"step limit"'
          Maximum number of integration steps to attempt on a single
          call to the underlying Fortran code.

   See K. E. Brenan, et al., `Numerical Solution of Initial-Value
Problems in Differential-Algebraic Equations', North-Holland (1989) for
more information about the implementation of DASSL.


File: octave.info,  Node: Optimization,  Next: Statistics,  Prev: Differential Equations,  Up: Top

24 Optimization
***************

Octave comes with support for solving various kinds of optimization
problems.  Specifically Octave can solve problems in Linear Programming,
Quadratic Programming, Nonlinear Programming, and Linear Least Squares
Minimization.

* Menu:

* Linear Programming::
* Quadratic Programming::
* Nonlinear Programming::
* Linear Least Squares::


File: octave.info,  Node: Linear Programming,  Next: Quadratic Programming,  Up: Optimization

24.1 Linear Programming
=======================

Octave can solve Linear Programming problems using the `glpk' function.
That is, Octave can solve

     min C'*x
   subject to the linear constraints A*x = b where x >= 0.

The `glpk' function also supports variations of this problem.

 -- Function File: [XOPT, FMIN, STATUS, EXTRA] = glpk (C, A, B, LB, UB,
          CTYPE, VARTYPE, SENSE, PARAM)
     Solve a linear program using the GNU GLPK library.  Given three
     arguments, `glpk' solves the following standard LP:

          min C'*x

     subject to

          A*x  = b
            x >= 0

     but may also solve problems of the form

          [ min | max ] C'*x

     subject to

          A*x [ "=" | "<=" | ">=" ] b
            x >= LB
            x <= UB

     Input arguments:

    C
          A column array containing the objective function coefficients.

    A
          A matrix containing the constraints coefficients.

    B
          A column array containing the right-hand side value for each
          constraint in the constraint matrix.

    LB
          An array containing the lower bound on each of the variables.
          If LB is not supplied, the default lower bound for the
          variables is zero.

    UB
          An array containing the upper bound on each of the variables.
          If UB is not supplied, the default upper bound is assumed to
          be infinite.

    CTYPE
          An array of characters containing the sense of each
          constraint in the constraint matrix.  Each element of the
          array may be one of the following values
         `"F"'
               A free (unbounded) constraint (the constraint is
               ignored).

         `"U"'
               An inequality constraint with an upper bound (`A(i,:)*x
               <= b(i)').

         `"S"'
               An equality constraint (`A(i,:)*x = b(i)').

         `"L"'
               An inequality with a lower bound (`A(i,:)*x >= b(i)').

         `"D"'
               An inequality constraint with both upper and lower bounds
               (`A(i,:)*x >= -b(i)' _and_ (`A(i,:)*x <= b(i)').

    VARTYPE
          A column array containing the types of the variables.
         `"C"'
               A continuous variable.

         `"I"'
               An integer variable.

    SENSE
          If SENSE is 1, the problem is a minimization.  If SENSE is
          -1, the problem is a maximization.  The default value is 1.

    PARAM
          A structure containing the following parameters used to
          define the behavior of solver.  Missing elements in the
          structure take on default values, so you only need to set the
          elements that you wish to change from the default.

          Integer parameters:

         `msglev (`LPX_K_MSGLEV', default: 1)'
               Level of messages output by solver routines:
              0
                    No output.

              1
                    Error messages only.

              2
                    Normal output .

              3
                    Full output (includes informational messages).

         `scale (`LPX_K_SCALE', default: 1)'
               Scaling option:
              0
                    No scaling.

              1
                    Equilibration scaling.

              2
                    Geometric mean scaling, then equilibration scaling.

         `dual	 (`LPX_K_DUAL', default: 0)'
               Dual simplex option:
              0
                    Do not use the dual simplex.

              1
                    If initial basic solution is dual feasible, use the
                    dual simplex.

         `price	 (`LPX_K_PRICE', default: 1)'
               Pricing option (for both primal and dual simplex):
              0
                    Textbook pricing.

              1
                    Steepest edge pricing.

         `round	 (`LPX_K_ROUND', default: 0)'
               Solution rounding option:
              0
                    Report all primal and dual values "as is".

              1
                    Replace tiny primal and dual values by exact zero.

         `itlim	 (`LPX_K_ITLIM', default: -1)'
               Simplex iterations limit.  If this value is positive, it
               is decreased by one each time when one simplex iteration
               has been performed, and reaching zero value signals the
               solver to stop the search.  Negative value means no
               iterations limit.

         `itcnt (`LPX_K_OUTFRQ', default: 200)'
               Output frequency, in iterations.  This parameter
               specifies how frequently the solver sends information
               about the solution to the standard output.

         `branch (`LPX_K_BRANCH', default: 2)'
               Branching heuristic option (for MIP only):
              0
                    Branch on the first variable.

              1
                    Branch on the last variable.

              2
                    Branch using a heuristic by Driebeck and Tomlin.

         `btrack (`LPX_K_BTRACK', default: 2)'
               Backtracking heuristic option (for MIP only):
              0
                    Depth first search.

              1
                    Breadth first search.

              2
                    Backtrack using the best projection heuristic.

         `presol (`LPX_K_PRESOL', default: 1)'
               If this flag is set, the routine lpx_simplex solves the
               problem using the built-in LP presolver.  Otherwise the
               LP presolver is not used.

         `lpsolver (default: 1)'
               Select which solver to use.  If the problem is a MIP
               problem this flag will be ignored.
              1
                    Revised simplex method.

              2
                    Interior point method.

         `save (default: 0)'
               If this parameter is nonzero, save a copy of the problem
               in CPLEX LP format to the file `"outpb.lp"'.  There is
               currently no way to change the name of the output file.

          Real parameters:

         `relax (`LPX_K_RELAX', default: 0.07)'
               Relaxation parameter used in the ratio test.  If it is
               zero, the textbook ratio test is used.  If it is
               non-zero (should be positive), Harris' two-pass ratio
               test is used.  In the latter case on the first pass of
               the ratio test basic variables (in the case of primal
               simplex) or reduced costs of non-basic variables (in the
               case of dual simplex) are allowed to slightly violate
               their bounds, but not more than `relax*tolbnd' or
               `relax*toldj (thus, `relax' is a percentage of `tolbnd'
               or `toldj''.

         `tolbnd (`LPX_K_TOLBND', default: 10e-7)'
               Relative tolerance used to check if the current basic
               solution is primal feasible.  It is not recommended that
               you change this parameter unless you have a detailed
               understanding of its purpose.

         `toldj (`LPX_K_TOLDJ', default: 10e-7)'
               Absolute tolerance used to check if the current basic
               solution is dual feasible.  It is not recommended that
               you change this parameter unless you have a detailed
               understanding of its purpose.

         `tolpiv (`LPX_K_TOLPIV', default: 10e-9)'
               Relative tolerance used to choose eligible pivotal
               elements of the simplex table.  It is not recommended
               that you change this parameter unless you have a
               detailed understanding of its purpose.

         `objll (`LPX_K_OBJLL', default: -DBL_MAX)'
               Lower limit of the objective function.  If on the phase
               II the objective function reaches this limit and
               continues decreasing, the solver stops the search.  This
               parameter is used in the dual simplex method only.

         `objul (`LPX_K_OBJUL', default: +DBL_MAX)'
               Upper limit of the objective function.  If on the phase
               II the objective function reaches this limit and
               continues increasing, the solver stops the search.  This
               parameter is used in the dual simplex only.

         `tmlim (`LPX_K_TMLIM', default: -1.0)'
               Searching time limit, in seconds.  If this value is
               positive, it is decreased each time when one simplex
               iteration has been performed by the amount of time spent
               for the iteration, and reaching zero value signals the
               solver to stop the search.  Negative value means no time
               limit.

         `outdly (`LPX_K_OUTDLY', default: 0.0)'
               Output delay, in seconds.  This parameter specifies how
               long the solver should delay sending information about
               the solution to the standard output.  Non-positive value
               means no delay.

         `tolint (`LPX_K_TOLINT', default: 10e-5)'
               Relative tolerance used to check if the current basic
               solution is integer feasible.  It is not recommended
               that you change this parameter unless you have a
               detailed understanding of its purpose.

         `tolobj (`LPX_K_TOLOBJ', default: 10e-7)'
               Relative tolerance used to check if the value of the
               objective function is not better than in the best known
               integer feasible solution.  It is not recommended that
               you change this parameter unless you have a detailed
               understanding of its purpose.

     Output values:

    XOPT
          The optimizer (the value of the decision variables at the
          optimum).

    FOPT
          The optimum value of the objective function.

    STATUS
          Status of the optimization.

          Simplex Method:
         180 (`LPX_OPT')
               Solution is optimal.

         181 (`LPX_FEAS')
               Solution is feasible.

         182 (`LPX_INFEAS')
               Solution is infeasible.

         183 (`LPX_NOFEAS')
               Problem has no feasible solution.

         184 (`LPX_UNBND')
               Problem has no unbounded solution.

         185 (`LPX_UNDEF')
               Solution status is undefined.
          Interior Point Method:
         150 (`LPX_T_UNDEF')
               The interior point method is undefined.

         151 (`LPX_T_OPT')
               The interior point method is optimal.
          Mixed Integer Method:
         170 (`LPX_I_UNDEF')
               The status is undefined.

         171 (`LPX_I_OPT')
               The solution is integer optimal.

         172 (`LPX_I_FEAS')
               Solution integer feasible but its optimality has not
               been proven

         173 (`LPX_I_NOFEAS')
               No integer feasible solution.
          If an error occurs, STATUS will contain one of the following
          codes:

         204 (`LPX_E_FAULT')
               Unable to start the search.

         205 (`LPX_E_OBJLL')
               Objective function lower limit reached.

         206 (`LPX_E_OBJUL')
               Objective function upper limit reached.

         207 (`LPX_E_ITLIM')
               Iterations limit exhausted.

         208 (`LPX_E_TMLIM')
               Time limit exhausted.

         209 (`LPX_E_NOFEAS')
               No feasible solution.

         210 (`LPX_E_INSTAB')
               Numerical instability.

         211 (`LPX_E_SING')
               Problems with basis matrix.

         212 (`LPX_E_NOCONV')
               No convergence (interior).

         213 (`LPX_E_NOPFS')
               No primal feasible solution (LP presolver).

         214 (`LPX_E_NODFS')
               No dual feasible solution (LP presolver).

    EXTRA
          A data structure containing the following fields:
         `lambda'
               Dual variables.

         `redcosts'
               Reduced Costs.

         `time'
               Time (in seconds) used for solving LP/MIP problem.

         `mem'
               Memory (in bytes) used for solving LP/MIP problem (this
               is not available if the version of GLPK is 4.15 or
               later).

     Example:

          c = [10, 6, 4]';
          a = [ 1, 1, 1;
               10, 4, 5;
                2, 2, 6];
          b = [100, 600, 300]';
          lb = [0, 0, 0]';
          ub = [];
          ctype = "UUU";
          vartype = "CCC";
          s = -1;

          param.msglev = 1;
          param.itlim = 100;

          [xmin, fmin, status, extra] = ...
             glpk (c, a, b, lb, ub, ctype, vartype, s, param);


File: octave.info,  Node: Quadratic Programming,  Next: Nonlinear Programming,  Prev: Linear Programming,  Up: Optimization

24.2 Quadratic Programming
==========================

Octave can also solve Quadratic Programming problems, this is
     min 0.5 x'*H*x + x'*q
   subject to
          A*x = b
          lb <= x <= ub
          A_lb <= A_in*x <= A_ub

 -- Function File: [X, OBJ, INFO, LAMBDA] = qp (X0, H, Q, A, B, LB, UB,
          A_LB, A_IN, A_UB)
     Solve the quadratic program

               min 0.5 x'*H*x + x'*q
                x

     subject to

               A*x = b
               lb <= x <= ub
               A_lb <= A_in*x <= A_ub

     using a null-space active-set method.

     Any bound (A, B, LB, UB, A_LB, A_UB) may be set to the empty
     matrix (`[]') if not present.  If the initial guess is feasible
     the algorithm is faster.

     The value INFO is a structure with the following fields:
    `solveiter'
          The number of iterations required to find the solution.

    `info'
          An integer indicating the status of the solution, as follows:
         0
               The problem is feasible and convex.  Global solution
               found.

         1
               The problem is not convex.  Local solution found.

         2
               The problem is not convex and unbounded.

         3
               Maximum number of iterations reached.

         6
               The problem is infeasible.


File: octave.info,  Node: Nonlinear Programming,  Next: Linear Least Squares,  Prev: Quadratic Programming,  Up: Optimization

24.3 Nonlinear Programming
==========================

Octave can also perform general nonlinear minimization using a
successive quadratic programming solver.

 -- Function File: [X, OBJ, INFO, ITER, NF, LAMBDA] = sqp (X, PHI, G,
          H, LB, UB, MAXITER, TOLERANCE)
     Solve the nonlinear program

               min phi (x)
                x

     subject to

               g(x)  = 0
               h(x) >= 0
               lb <= x <= ub

     using a successive quadratic programming method.

     The first argument is the initial guess for the vector X.

     The second argument is a function handle pointing to the objective
     function.  The objective function must be of the form

               y = phi (x)

     in which X is a vector and Y is a scalar.

     The second argument may also be a 2- or 3-element cell array of
     function handles.  The first element should point to the objective
     function, the second should point to a function that computes the
     gradient of the objective function, and the third should point to a
     function to compute the hessian of the objective function.  If the
     gradient function is not supplied, the gradient is computed by
     finite differences.  If the hessian function is not supplied, a
     BFGS update formula is used to approximate the hessian.

     If supplied, the gradient function must be of the form

          g = gradient (x)

     in which X is a vector and G is a vector.

     If supplied, the hessian function must be of the form

          h = hessian (x)

     in which X is a vector and H is a matrix.

     The third and fourth arguments are function handles pointing to
     functions that compute the equality constraints and the inequality
     constraints, respectively.

     If your problem does not have equality (or inequality) constraints,
     you may pass an empty matrix for CEF (or CIF).

     If supplied, the equality and inequality constraint functions must
     be of the form

          r = f (x)

     in which X is a vector and R is a vector.

     The third and fourth arguments may also be 2-element cell arrays of
     function handles.  The first element should point to the constraint
     function and the second should point to a function that computes
     the gradient of the constraint function:

                          [ d f(x)   d f(x)        d f(x) ]
              transpose ( [ ------   -----   ...   ------ ] )
                          [  dx_1     dx_2          dx_N  ]

     The fifth and sixth arguments are vectors containing lower and
     upper bounds on X.  These must be consistent with equality and
     inequality constraints G and H.  If the bounds are not specified,
     or are empty, they are set to -REALMAX and REALMAX by default.

     The seventh argument is max. number of iterations.  If not
     specified, the default value is 100.

     The eighth argument is tolerance for stopping criteria.  If not
     specified, the default value is EPS.

     Here is an example of calling `sqp':

          function r = g (x)
            r = [ sumsq(x)-10;
                  x(2)*x(3)-5*x(4)*x(5);
                  x(1)^3+x(2)^3+1 ];
          endfunction

          function obj = phi (x)
            obj = exp(prod(x)) - 0.5*(x(1)^3+x(2)^3+1)^2;
          endfunction

          x0 = [-1.8; 1.7; 1.9; -0.8; -0.8];

          [x, obj, info, iter, nf, lambda] = sqp (x0, @phi, @g, [])

          x =

            -1.71714
             1.59571
             1.82725
            -0.76364
            -0.76364

          obj = 0.053950
          info = 101
          iter = 8
          nf = 10
          lambda =

            -0.0401627
             0.0379578
            -0.0052227

     The value returned in INFO may be one of the following:
    101
          The algorithm terminated because the norm of the last step
          was less than `tol * norm (x))' (the value of tol is
          currently fixed at `sqrt (eps)'--edit `sqp.m' to modify this
          value.

    102
          The BFGS update failed.

    103
          The maximum number of iterations was reached (the maximum
          number of allowed iterations is currently fixed at 100--edit
          `sqp.m' to increase this value).

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


File: octave.info,  Node: Linear Least Squares,  Prev: Nonlinear Programming,  Up: Optimization

24.4 Linear Least Squares
=========================

Octave also supports linear least squares minimization.  That is,
Octave can find the parameter b such that the model y = x*b fits data
(x,y) as well as possible, assuming zero-mean Gaussian noise.  If the
noise is assumed to be isotropic the problem can be solved using the
`\' or `/' operators, or the `ols' function.  In the general case where
the noise is assumed to be anisotropic the `gls' is needed.

 -- Function File: [BETA, SIGMA, R] = ols (Y, X)
     Ordinary least squares estimation for the multivariate model y = x
     b + e with mean (e) = 0 and cov (vec (e)) = kron (s, I).   where y
     is a t by p matrix, x is a t by k matrix, b is a k by p matrix, and
     e is a t by p matrix.

     Each row of Y and X is an observation and each column a variable.

     The return values BETA, SIGMA, and R are defined as follows.

    BETA
          The OLS estimator for B, `BETA = pinv (X) * Y', where `pinv
          (X)' denotes the pseudoinverse of X.

    SIGMA
          The OLS estimator for the matrix S,

               SIGMA = (Y-X*BETA)'
                 * (Y-X*BETA)
                 / (T-rank(X))

    R
          The matrix of OLS residuals, `R = Y - X * BETA'.

 -- Function File: [BETA, V, R] = gls (Y, X, O)
     Generalized least squares estimation for the multivariate model y
     = x b + e with mean (e) = 0 and cov (vec (e)) = (s^2) o,  where y
     is a t by p matrix, x is a t by k matrix, b is a k by p matrix, e
     is a t by p matrix, and o is a t p by t p matrix.

     Each row of Y and X is an observation and each column a variable.
     The return values BETA, V, and R are defined as follows.

    BETA
          The GLS estimator for b.

    V
          The GLS estimator for s^2.

    R
          The matrix of GLS residuals, r = y - x beta.

 -- Function File: X = lsqnonneg (C, D)
 -- Function File: X = lsqnonneg (C, D, X0)
 -- Function File: [X, RESNORM] = lsqnonneg (...)
 -- Function File: [X, RESNORM, RESIDUAL] = lsqnonneg (...)
 -- Function File: [X, RESNORM, RESIDUAL, EXITFLAG] = lsqnonneg (...)
 -- Function File: [X, RESNORM, RESIDUAL, EXITFLAG, OUTPUT] = lsqnonneg
          (...)
 -- Function File: [X, RESNORM, RESIDUAL, EXITFLAG, OUTPUT, LAMBDA] =
lsqnonneg (...)
     Minimize `norm (C*X-d)' subject to `X >= 0'.  C and D must be
     real.  X0 is an optional initial guess for X.

     Outputs:
        * resnorm

          The squared 2-norm of the residual: norm(C*X-D)^2

        * residual

          The residual: D-C*X

        * exitflag

          An indicator of convergence.  0 indicates that the iteration
          count was exceeded, and therefore convergence was not
          reached; >0 indicates that the algorithm converged.  (The
          algorithm is stable and will converge given enough
          iterations.)

        * output

          A structure with two fields:
             * "algorithm": The algorithm used ("nnls")

             * "iterations": The number of iterations taken.

        * lambda

          Not implemented.

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

 -- Function File:  optimset ()
 -- Function File:  optimset (PAR, VAL, ...)
 -- Function File:  optimset (OLD, PAR, VAL, ...)
 -- Function File:  optimset (OLD, NEW)
     Create options struct for optimization functions.

 -- Function File:  optimget (OPTIONS, PARNAME)
 -- Function File:  optimget (OPTIONS, PARNAME, DEFAULT)
     Return a specific option from a structure created by `optimset'.
     If PARNAME is not a field of the OPTIONS structure, return DEFAULT
     if supplied, otherwise return an empty matrix.


File: octave.info,  Node: Statistics,  Next: Sets,  Prev: Optimization,  Up: Top

25 Statistics
*************

Octave has support for various statistical methods.  This includes
basic descriptive statistics, statistical tests, random number
generation, and much more.

   The functions that analyze data all assume that multidimensional data
is arranged in a matrix where each row is an observation, and each
column is a variable.  So, the matrix defined by

     a = [ 0.9, 0.7;
           0.1, 0.1;
           0.5, 0.4 ];

contains three observations from a two-dimensional distribution.  While
this is the default data arrangement, most functions support different
arrangements.

   It should be noted that the statistics functions don't test for data
containing NaN, NA, or Inf.  Such values need to be handled explicitly.

* Menu:

* Descriptive Statistics::
* Basic Statistical Functions::
* Statistical Plots::
* Tests::
* Models::
* Distributions::
* Random Number Generation::


File: octave.info,  Node: Descriptive Statistics,  Next: Basic Statistical Functions,  Up: Statistics

25.1 Descriptive Statistics
===========================

Octave can compute various statistics such as the moments of a data set.

 -- Function File:  mean (X, DIM, OPT)
     If X is a vector, compute the mean of the elements of X

          mean (x) = SUM_i x(i) / N
     If X is a matrix, compute the mean for each column and return them
     in a row vector.

     With the optional argument OPT, the kind of mean computed can be
     selected.  The following options are recognized:

    `"a"'
          Compute the (ordinary) arithmetic mean.  This is the default.

    `"g"'
          Compute the geometric mean.

    `"h"'
          Compute the harmonic mean.

     If the optional argument DIM is supplied, work along dimension DIM.

     Both DIM and OPT are optional.  If both are supplied, either may
     appear first.

 -- Function File:  median (X, DIM)
     If X is a vector, compute the median value of the elements of X.
     If the elements of X are sorted, the median is defined as

                      x(ceil(N/2)),             N odd
          median(x) =
                      (x(N/2) + x((N/2)+1))/2,  N even
     If X is a matrix, compute the median value for each column and
     return them in a row vector.  If the optional DIM argument is
     given, operate along this dimension.

     *See also:* *note std: doc-std, *note mean: doc-mean.

 -- Function File: Q = quantile (X, P)
 -- Function File: Q = quantile (X, P, DIM)
 -- Function File: Q = quantile (X, P, DIM, METHOD)
     For a sample, X, calculate the quantiles, Q, corresponding to the
     cumulative probability values in P.  All non-numeric values (NaNs)
     of X are ignored.

     If X is a matrix, compute the quantiles for each column and return
     them in a matrix, such that the i-th row of Q contains the P(i)th
     quantiles of each column of X.

     The optional argument DIM determines the dimension along which the
     percentiles are calculated.  If DIM is omitted, and X is a vector
     or matrix, it defaults to 1 (column wise quantiles).  In the
     instance that X is a N-d array, DIM defaults to the first
     dimension whose size greater than unity.

     The methods available to calculate sample quantiles are the nine
     methods used by R (http://www.r-project.org/).  The default value
     is METHOD = 5.

     Discontinuous sample quantile methods 1, 2, and 3

       1. Method 1: Inverse of empirical distribution function.

       2. Method 2: Similar to method 1 but with averaging at
          discontinuities.

       3. Method 3: SAS definition: nearest even order statistic.

     Continuous sample quantile methods 4 through 9, where p(k) is the
     linear interpolation function respecting each methods'
     representative cdf.

       4. Method 4: p(k) = k / n. That is, linear interpolation of the
          empirical cdf.

       5. Method 5: p(k) = (k - 0.5) / n. That is a piecewise linear
          function where the knots are the values midway through the
          steps of the empirical cdf.

       6. Method 6: p(k) = k / (n + 1).

       7. Method 7: p(k) = (k - 1) / (n - 1).

       8. Method 8: p(k) = (k - 1/3) / (n + 1/3).  The resulting
          quantile estimates are approximately median-unbiased
          regardless of the distribution of X.

       9. Method 9: p(k) = (k - 3/8) / (n + 1/4).  The resulting
          quantile estimates are approximately unbiased for the
          expected order statistics if X is normally distributed.

     Hyndman and Fan (1996) recommend method 8.  Maxima, S, and R
     (versions prior to 2.0.0) use 7 as their default.  Minitab and SPSS
     use method 6.  MATLAB uses method 5.

     References:

        * Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New
          S Language.  Wadsworth & Brooks/Cole.

        * Hyndman, R. J. and Fan, Y. (1996) Sample quantiles in
          statistical packages, American Statistician, 50, 361-365.

        * R: A Language and Environment for Statistical Computing;
          `http://cran.r-project.org/doc/manuals/fullrefman.pdf'.

 -- Function File: Y = prctile (X, P)
 -- Function File: Q = prctile (X, P, DIM)
     For a sample X, compute the quantiles, Y, corresponding to the
     cumulative probability values, P, in percent.  All non-numeric
     values (NaNs) of X are ignored.

     If X is a matrix, compute the percentiles for each column and
     return them in a matrix, such that the i-th row of Y contains the
     P(i)th percentiles of each column of X.

     The optional argument DIM determines the dimension along which the
     percentiles are calculated.  If DIM is omitted, and X is a vector
     or matrix, it defaults to 1 (column wise quantiles).  In the
     instance that X is a N-d array, DIM defaults to the first
     dimension whose size greater than unity.


 -- Function File:  meansq (X)
 -- Function File:  meansq (X, DIM)
     For vector arguments, return the mean square of the values.  For
     matrix arguments, return a row vector containing the mean square
     of each column.  With the optional DIM argument, returns the mean
     squared of the values along this dimension.

 -- Function File:  std (X)
 -- Function File:  std (X, OPT)
 -- Function File:  std (X, OPT, DIM)
     If X is a vector, compute the standard deviation of the elements
     of X.

          std (x) = sqrt (sumsq (x - mean (x)) / (n - 1))
     If X is a matrix, compute the standard deviation for each column
     and return them in a row vector.

     The argument OPT determines the type of normalization to use.
     Valid values are

    0:
          normalizes with N-1, provides the square root of best
          unbiased estimator of   the variance [default]

    1:
          normalizes with N, this provides the square root of the
          second moment around   the mean

     The third argument DIM determines the dimension along which the
     standard deviation is calculated.

     *See also:* *note mean: doc-mean, *note median: doc-median.

 -- Function File:  var (X)
     For vector arguments, return the (real) variance of the values.
     For matrix arguments, return a row vector containing the variance
     for each column.

     The argument OPT determines the type of normalization to use.
     Valid values are

    0:
          Normalizes with N-1, provides the best unbiased estimator of
          the variance [default].

    1:
          Normalizes with N, this provides the second moment around the
          mean.

     The third argument DIM determines the dimension along which the
     variance is calculated.

 -- Function File: [M, F, C] = mode (X, DIM)
     Count the most frequently appearing value.  `mode' counts the
     frequency along the first non-singleton dimension and if two or
     more values have the same frequency returns the smallest of the
     two in M.  The dimension along which to count can be specified by
     the DIM parameter.

     The variable F counts the frequency of each of the most frequently
     occurring elements.  The cell array C contains all of the elements
     with the maximum frequency .

 -- Function File:  cov (X, Y)
     Compute covariance.

     If each row of X and Y is an observation and each column is a
     variable, the (I, J)-th entry of `cov (X, Y)' is the covariance
     between the I-th variable in X and the J-th variable in Y.  If
     called with one argument, compute `cov (X, X)'.

 -- Function File:  cor (X, Y)
     Compute correlation.

     The (I, J)-th entry of `cor (X, Y)' is the correlation between the
     I-th variable in X and the J-th variable in Y.

          corrcoef(x,y) = cov(x,y)/(std(x)*std(y))

     For matrices, each row is an observation and each column a
     variable; vectors are always observations and may be row or column
     vectors.

     `cor (X)' is equivalent to `cor (X, X)'.

     Note that the `corrcoef' function does the same as `cor'.

 -- Function File:  corrcoef (X, Y)
     Compute correlation.

     If each row of X and Y is an observation and each column is a
     variable, the (I, J)-th entry of `corrcoef (X, Y)' is the
     correlation between the I-th variable in X and the J-th variable
     in Y.

          corrcoef(x,y) = cov(x,y)/(std(x)*std(y))

     If called with one argument, compute `corrcoef (X, X)'.

 -- Function File:  kurtosis (X, DIM)
     If X is a vector of length N, return the kurtosis

          kurtosis (x) = N^(-1) std(x)^(-4) sum ((x - mean(x)).^4) - 3

     of X.  If X is a matrix, return the kurtosis over the first
     non-singleton dimension.  The optional argument DIM can be given
     to force the kurtosis to be given over that dimension.

 -- Function File:  skewness (X, DIM)
     If X is a vector of length n, return the skewness

          skewness (x) = N^(-1) std(x)^(-3) sum ((x - mean(x)).^3)

     of X.  If X is a matrix, return the skewness along the first
     non-singleton dimension of the matrix.  If the optional DIM
     argument is given, operate along this dimension.

 -- Function File:  statistics (X)
     If X is a matrix, return a matrix with the minimum, first
     quartile, median, third quartile, maximum, mean, standard
     deviation, skewness and kurtosis of the columns of X as its
     columns.

     If X is a vector, calculate the statistics along the non-singleton
     dimension.

 -- Function File:  moment (X, P, OPT, DIM)
     If X is a vector, compute the P-th moment of X.

     If X is a matrix, return the row vector containing the P-th moment
     of each column.

     With the optional string opt, the kind of moment to be computed can
     be specified.  If opt contains `"c"' or `"a"', central and/or
     absolute moments are returned.  For example,

          moment (x, 3, "ac")

     computes the third central absolute moment of X.

     If the optional argument DIM is supplied, work along dimension DIM.


File: octave.info,  Node: Basic Statistical Functions,  Next: Statistical Plots,  Prev: Descriptive Statistics,  Up: Statistics

25.2 Basic Statistical Functions
================================

Octave also supports various helpful statistical functions.

 -- Function File:  mahalanobis (X, Y)
     Return the Mahalanobis' D-square distance between the multivariate
     samples X and Y, which must have the same number of components
     (columns), but may have a different number of observations (rows).

 -- Function File:  center (X)
 -- Function File:  center (X, DIM)
     If X is a vector, subtract its mean.  If X is a matrix, do the
     above for each column.  If the optional argument DIM is given,
     perform the above operation along this dimension

 -- Function File:  studentize (X, DIM)
     If X is a vector, subtract its mean and divide by its standard
     deviation.

     If X is a matrix, do the above along the first non-singleton
     dimension.  If the optional argument DIM is given then operate
     along this dimension.

 -- Function File: C = nchoosek (N, K)
     Compute the binomial coefficient or all combinations of N.  If N
     is a scalar then, calculate the binomial coefficient of N and K,
     defined as

           /   \
           | n |    n (n-1) (n-2) ... (n-k+1)       n!
           |   |  = ------------------------- =  ---------
           | k |               k!                k! (n-k)!
           \   /

     If N is a vector generate all combinations of the elements of N,
     taken K at a time, one row per combination.  The resulting C has
     size `[nchoosek (length (N), K), K]'.

     `nchoosek' works only for non-negative integer arguments; use
     `bincoeff' for non-integer scalar arguments and for using vector
     arguments to compute many coefficients at once.

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

 -- Function File: N = histc (Y, EDGES)
 -- Function File: N = histc (Y, EDGES, DIM)
 -- Function File: [N, IDX] = histc (...)
     Produce histogram counts.

     When Y is a vector, the function counts the number of elements of
     Y that fall in the histogram bins defined by EDGES.  This must be
     a vector of monotonically non-decreasing values that define the
     edges of the histogram bins.  So, `N (k)' contains the number of
     elements in Y for which `EDGES (k) <= Y < EDGES (k+1)'.  The final
     element of N contains the number of elements of Y that was equal
     to the last element of EDGES.

     When Y is a N-dimensional array, the same operation as above is
     repeated along dimension DIM.  If this argument is given, the
     operation is performed along the first non-singleton dimension.

     If a second output argument is requested an index matrix is also
     returned.  The IDX matrix has same size as Y.  Each element of IDX
     contains the index of the histogram bin in which the corresponding
     element of Y was counted.

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

 -- Function File:  perms (V)
     Generate all permutations of V, one row per permutation.  The
     result has size `factorial (N) * N', where N is the length of V.

     As an example, `perms([1, 2, 3])' returns the matrix
            1   2   3
            2   1   3
            1   3   2
            2   3   1
            3   1   2
            3   2   1

 -- Function File:  values (X)
     Return the different values in a column vector, arranged in
     ascending order.

     As an example, `values([1, 2, 3, 1])' returns the vector `[1, 2,
     3]'.

 -- Function File: [T, L_X] = table (X)
 -- Function File: [T, L_X, L_Y] = table (X, Y)
     Create a contingency table T from data vectors.  The L vectors are
     the corresponding levels.

     Currently, only 1- and 2-dimensional tables are supported.

 -- Function File:  spearman (X, Y)
     Compute Spearman's rank correlation coefficient RHO for each of
     the variables specified by the input arguments.

     For matrices, each row is an observation and each column a
     variable; vectors are always observations and may be row or column
     vectors.

     `spearman (X)' is equivalent to `spearman (X, X)'.

     For two data vectors X and Y, Spearman's RHO is the correlation of
     the ranks of X and Y.

     If X and Y are drawn from independent distributions, RHO has zero
     mean and variance `1 / (n - 1)', and is asymptotically normally
     distributed.

 -- Function File:  run_count (X, N)
     Count the upward runs along the first non-singleton dimension of X
     of length 1, 2, ..., N-1 and greater than or equal to N.  If the
     optional argument DIM is given operate along this dimension

 -- Function File:  ranks (X, DIM)
     Return the ranks of X along the first non-singleton dimension
     adjust for ties.  If the optional argument DIM is given, operate
     along this dimension.

 -- Function File:  range (X)
 -- Function File:  range (X, DIM)
     If X is a vector, return the range, i.e., the difference between
     the maximum and the minimum, of the input data.

     If X is a matrix, do the above for each column of X.

     If the optional argument DIM is supplied, work along dimension DIM.

 -- Function File:  probit (P)
     For each component of P, return the probit (the quantile of the
     standard normal distribution) of P.

 -- Function File:  logit (P)
     For each component of P, return the logit of P defined as
          logit(P) = log (P / (1-P))

 -- Function File:  cloglog (X)
     Return the complementary log-log function of X, defined as

          cloglog(x) = - log (- log (X))

 -- Function File:  kendall (X, Y)
     Compute Kendall's TAU for each of the variables specified by the
     input arguments.

     For matrices, each row is an observation and each column a
     variable; vectors are always observations and may be row or column
     vectors.

     `kendall (X)' is equivalent to `kendall (X, X)'.

     For two data vectors X, Y of common length N, Kendall's TAU is the
     correlation of the signs of all rank differences of X and Y;
     i.e., if both X and Y have distinct entries, then

                   1
          tau = -------   SUM sign (q(i) - q(j)) * sign (r(i) - r(j))
                n (n-1)   i,j

     in which the Q(I) and R(I)  are the ranks of X and Y, respectively.

     If X and Y are drawn from independent distributions, Kendall's TAU
     is asymptotically normal with mean 0 and variance `(2 * (2N+5)) /
     (9 * N * (N-1))'.

 -- Function File:  iqr (X, DIM)
     If X is a vector, return the interquartile range, i.e., the
     difference between the upper and lower quartile, of the input data.

     If X is a matrix, do the above for first non-singleton dimension
     of X.  If the option DIM argument is given, then operate along
     this dimension.

 -- Function File:  cut (X, BREAKS)
     Create categorical data out of numerical or continuous data by
     cutting into intervals.

     If BREAKS is a scalar, the data is cut into that many equal-width
     intervals.  If BREAKS is a vector of break points, the category
     has `length (BREAKS) - 1' groups.

     The returned value is a vector of the same size as X telling which
     group each point in X belongs to.  Groups are labelled from 1 to
     the number of groups; points outside the range of BREAKS are
     labelled by `NaN'.


File: octave.info,  Node: Statistical Plots,  Next: Tests,  Prev: Basic Statistical Functions,  Up: Statistics

25.3 Statistical Plots
======================

Octave can create Quantile Plots (QQ-Plots), and Probability Plots
(PP-Plots).  These are simple graphical tests for determining if a data
set comes from a certain distribution.

   Note that Octave can also show histograms of data using the `hist'
function as described in *note Two-Dimensional Plots::.

 -- Function File: [Q, S] = qqplot (X, DIST, PARAMS)
     Perform a QQ-plot (quantile plot).

     If F is the CDF of the distribution DIST with parameters PARAMS
     and G its inverse, and X a sample vector of length N, the QQ-plot
     graphs ordinate S(I) = I-th largest element of x versus abscissa
     Q(If) = G((I - 0.5)/N).

     If the sample comes from F except for a transformation of location
     and scale, the pairs will approximately follow a straight line.

     The default for DIST is the standard normal distribution.  The
     optional argument PARAMS contains a list of parameters of DIST.
     For example, for a quantile plot of the uniform distribution on
     [2,4] and X, use

          qqplot (x, "uniform", 2, 4)

     DIST can be any string for which a function DIST_INV that
     calculates the inverse CDF of distribution DIST exists.

     If no output arguments are given, the data are plotted directly.

 -- Function File: [P, Y] = ppplot (X, DIST, PARAMS)
     Perform a PP-plot (probability plot).

     If F is the CDF of the distribution DIST with parameters PARAMS
     and X a sample vector of length N, the PP-plot graphs ordinate
     Y(I) = F (I-th largest element of X) versus abscissa P(I) = (I -
     0.5)/N.  If the sample comes from F, the pairs will approximately
     follow a straight line.

     The default for DIST is the standard normal distribution.  The
     optional argument PARAMS contains a list of parameters of DIST.
     For example, for a probability plot of the uniform distribution on
     [2,4] and X, use

          ppplot (x, "uniform", 2, 4)

     DIST can be any string for which a function DIST_CDF that
     calculates the CDF of distribution DIST exists.

     If no output arguments are given, the data are plotted directly.


File: octave.info,  Node: Tests,  Next: Models,  Prev: Statistical Plots,  Up: Statistics

25.4 Tests
==========

Octave can perform several different statistical tests.  The following
table summarizes the available tests.

*Hypothesis*                  *Test Functions*
Equal mean values             `anova', `hotelling_test2',
                              `t_test_2',        `welch_test',
                              `wilcoxon_test', `z_test_2'
Equal medians                 `kruskal_wallis_test', `sign_test'
Equal variances               `bartlett_test', `manova',
                              `var_test'
Equal distributions           `chisquare_test_homogeneity',
                              `kolmogorov_smirnov_test_2',
                              `u_test'
Equal marginal frequencies    `mcnemar_test'
Equal success probabilities   `prop_test_2'
Independent observations      `chisquare_test_independence',
                              `run_test'
Uncorrelated observations     `cor_test'
Given mean value              `hotelling_test', `t_test', `z_test'
Observations from given       `kolmogorov_smirnov_test'
distribution                  
Regression                    `f_test_regression',
                              `t_test_regression'

   The tests return a p-value that describes the outcome of the test.
Assuming that the test hypothesis is true, the p-value is the
probability of obtaining a worse result than the observed one.  So
large p-values corresponds to a successful test.  Usually a test
hypothesis is accepted if the p-value exceeds 0.05.

 -- Function File: [PVAL, F, DF_B, DF_W] = anova (Y, G)
     Perform a one-way analysis of variance (ANOVA).  The goal is to
     test whether the population means of data taken from K different
     groups are all equal.

     Data may be given in a single vector Y with groups specified by a
     corresponding vector of group labels G (e.g., numbers from 1 to
     K).  This is the general form which does not impose any
     restriction on the number of data in each group or the group
     labels.

     If Y is a matrix and G is omitted, each column of Y is treated as
     a group.  This form is only appropriate for balanced ANOVA in
     which the numbers of samples from each group are all equal.

     Under the null of constant means, the statistic F follows an F
     distribution with DF_B and DF_W degrees of freedom.

     The p-value (1 minus the CDF of this distribution at F) is
     returned in PVAL.

     If no output argument is given, the standard one-way ANOVA table is
     printed.

 -- Function File: [PVAL, CHISQ, DF] = bartlett_test (X1, ...)
     Perform a Bartlett test for the homogeneity of variances in the
     data vectors X1, X2, ..., XK, where K > 1.

     Under the null of equal variances, the test statistic CHISQ
     approximately follows a chi-square distribution with DF degrees of
     freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, CHISQ, DF] = chisquare_test_homogeneity (X,
          Y, C)
     Given two samples X and Y, perform a chisquare test for
     homogeneity of the null hypothesis that X and Y come from the same
     distribution, based on the partition induced by the (strictly
     increasing) entries of C.

     For large samples, the test statistic CHISQ approximately follows a
     chisquare distribution with DF = `length (C)' degrees of freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, CHISQ, DF] = chisquare_test_independence (X)
     Perform a chi-square test for independence based on the contingency
     table X.  Under the null hypothesis of independence, CHISQ
     approximately has a chi-square distribution with DF degrees of
     freedom.

     The p-value (1 minus the CDF of this distribution at chisq) of the
     test is returned in PVAL.

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

 -- Function File:  cor_test (X, Y, ALT, METHOD)
     Test whether two samples X and Y come from uncorrelated
     populations.

     The optional argument string ALT describes the alternative
     hypothesis, and can be `"!="' or `"<>"' (non-zero), `">"' (greater
     than 0), or `"<"' (less than 0).  The default is the two-sided
     case.

     The optional argument string METHOD specifies on which correlation
     coefficient the test should be based.  If METHOD is `"pearson"'
     (default), the (usual) Pearson's product moment correlation
     coefficient is used.  In this case, the data should come from a
     bivariate normal distribution.  Otherwise, the other two methods
     offer nonparametric alternatives.  If METHOD is `"kendall"', then
     Kendall's rank correlation tau is used.  If METHOD is
     `"spearman"', then Spearman's rank correlation rho is used.  Only
     the first character is necessary.

     The output is a structure with the following elements:

    PVAL
          The p-value of the test.

    STAT
          The value of the test statistic.

    DIST
          The distribution of the test statistic.

    PARAMS
          The parameters of the null distribution of the test statistic.

    ALTERNATIVE
          The alternative hypothesis.

    METHOD
          The method used for testing.

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

 -- Function File: [PVAL, F, DF_NUM, DF_DEN] = f_test_regression (Y, X,
          RR, R)
     Perform an F test for the null hypothesis rr * b = r in a classical
     normal regression model y = X * b + e.

     Under the null, the test statistic F follows an F distribution
     with DF_NUM and DF_DEN degrees of freedom.

     The p-value (1 minus the CDF of this distribution at F) is
     returned in PVAL.

     If not given explicitly, R = 0.

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

 -- Function File: [PVAL, TSQ] = hotelling_test (X, M)
     For a sample X from a multivariate normal distribution with unknown
     mean and covariance matrix, test the null hypothesis that `mean
     (X) == M'.

     Hotelling's T^2 is returned in TSQ.  Under the null, (n-p) T^2 /
     (p(n-1)) has an F distribution with p and n-p degrees of freedom,
     where n and p are the numbers of samples and variables,
     respectively.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, TSQ] = hotelling_test_2 (X, Y)
     For two samples X from multivariate normal distributions with the
     same number of variables (columns), unknown means and unknown
     equal covariance matrices, test the null hypothesis `mean (X) ==
     mean (Y)'.

     Hotelling's two-sample T^2 is returned in TSQ.  Under the null,

          (n_x+n_y-p-1) T^2 / (p(n_x+n_y-2))

     has an F distribution with p and n_x+n_y-p-1 degrees of freedom,
     where n_x and n_y are the sample sizes and p is the number of
     variables.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, KS] = kolmogorov_smirnov_test (X, DIST,
          PARAMS, ALT)
     Perform a Kolmogorov-Smirnov test of the null hypothesis that the
     sample X comes from the (continuous) distribution dist.  I.e., if
     F and G are the CDFs corresponding to the sample and dist,
     respectively, then the null is that F == G.

     The optional argument PARAMS contains a list of parameters of
     DIST.  For example, to test whether a sample X comes from a
     uniform distribution on [2,4], use

          kolmogorov_smirnov_test(x, "uniform", 2, 4)

     DIST can be any string for which a function DIST_CDF that
     calculates the CDF of distribution DIST exists.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative F != G.  In this case, the test
     statistic KS follows a two-sided Kolmogorov-Smirnov distribution.
     If ALT is `">"', the one-sided alternative F > G is considered.
     Similarly for `"<"', the one-sided alternative F > G is
     considered.  In this case, the test statistic KS has a one-sided
     Kolmogorov-Smirnov distribution.  The default is the two-sided
     case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, KS, D] = kolmogorov_smirnov_test_2 (X, Y, ALT)
     Perform a 2-sample Kolmogorov-Smirnov test of the null hypothesis
     that the samples X and Y come from the same (continuous)
     distribution.  I.e., if F and G are the CDFs corresponding to the
     X and Y samples, respectively, then the null is that F == G.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative F != G.  In this case, the test
     statistic KS follows a two-sided Kolmogorov-Smirnov distribution.
     If ALT is `">"', the one-sided alternative F > G is considered.
     Similarly for `"<"', the one-sided alternative F < G is
     considered.  In this case, the test statistic KS has a one-sided
     Kolmogorov-Smirnov distribution.  The default is the two-sided
     case.

     The p-value of the test is returned in PVAL.

     The third returned value, D, is the test statistic, the maximum
     vertical distance between the two cumulative distribution
     functions.

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

 -- Function File: [PVAL, K, DF] = kruskal_wallis_test (X1, ...)
     Perform a Kruskal-Wallis one-factor "analysis of variance".

     Suppose a variable is observed for K > 1 different groups, and let
     X1, ..., XK be the corresponding data vectors.

     Under the null hypothesis that the ranks in the pooled sample are
     not affected by the group memberships, the test statistic K is
     approximately chi-square with DF = K - 1 degrees of freedom.

     If the data contains ties (some value appears more than once) K is
     divided by

     1 - SUM_TIES / (N^3 - N)

     where SUM_TIES is the sum of T^2 - T over each group of ties where
     T is the number of ties in the group and N is the total number of
     values in the input data.  For more info on this adjustment see
     "Use of Ranks in One-Criterion Variance Analysis" in Journal of
     the American Statistical Association, Vol. 47, No. 260 (Dec 1952)
     by William H. Kruskal and W. Allen Wallis.

     The p-value (1 minus the CDF of this distribution at K) is
     returned in PVAL.

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

 -- Function File:  manova (Y, G)
     Perform a one-way multivariate analysis of variance (MANOVA).  The
     goal is to test whether the p-dimensional population means of data
     taken from K different groups are all equal.  All data are assumed
     drawn independently from p-dimensional normal distributions with
     the same covariance matrix.

     The data matrix is given by Y.  As usual, rows are observations
     and columns are variables.  The vector G specifies the
     corresponding group labels (e.g., numbers from 1 to K).

     The LR test statistic (Wilks' Lambda) and approximate p-values are
     computed and displayed.

 -- Function File: [PVAL, CHISQ, DF] = mcnemar_test (X)
     For a square contingency table X of data cross-classified on the
     row and column variables, McNemar's test can be used for testing
     the null hypothesis of symmetry of the classification
     probabilities.

     Under the null, CHISQ is approximately distributed as chisquare
     with DF degrees of freedom.

     The p-value (1 minus the CDF of this distribution at CHISQ) is
     returned in PVAL.

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

 -- Function File: [PVAL, Z] = prop_test_2 (X1, N1, X2, N2, ALT)
     If X1 and N1 are the counts of successes and trials in one sample,
     and X2 and N2 those in a second one, test the null hypothesis that
     the success probabilities P1 and P2 are the same.  Under the null,
     the test statistic Z approximately follows a standard normal
     distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative P1 != P2.  If ALT is `">"', the
     one-sided alternative P1 > P2 is used.  Similarly for `"<"', the
     one-sided alternative P1 < P2 is used.  The default is the
     two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, CHISQ] = run_test (X)
     Perform a chi-square test with 6 degrees of freedom based on the
     upward runs in the columns of X.  Can be used to test whether X
     contains independent data.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, B, N] = sign_test (X, Y, ALT)
     For two matched-pair samples X and Y, perform a sign test of the
     null hypothesis PROB (X > Y) == PROB (X < Y) == 1/2.  Under the
     null, the test statistic B roughly follows a binomial distribution
     with parameters `N = sum (X != Y)' and P = 1/2.

     With the optional argument `alt', the alternative of interest can
     be selected.  If ALT is `"!="' or `"<>"', the null hypothesis is
     tested against the two-sided alternative PROB (X < Y) != 1/2.  If
     ALT is `">"', the one-sided alternative PROB (X > Y) > 1/2 ("x is
     stochastically greater than y") is considered.  Similarly for
     `"<"', the one-sided alternative PROB (X > Y) < 1/2 ("x is
     stochastically less than y") is considered.  The default is the
     two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test (X, M, ALT)
     For a sample X from a normal distribution with unknown mean and
     variance, perform a t-test of the null hypothesis `mean (X) == M'.
     Under the null, the test statistic T follows a Student
     distribution with `DF = length (X) - 1' degrees of freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative `mean (X) > M' is considered.
     Similarly for "<", the one-sided alternative `mean (X) < M' is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test_2 (X, Y, ALT)
     For two samples x and y from normal distributions with unknown
     means and unknown equal variances, perform a two-sample t-test of
     the null hypothesis of equal means.  Under the null, the test
     statistic T follows a Student distribution with DF degrees of
     freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != mean (Y)'.  If ALT
     is `">"', the one-sided alternative `mean (X) > mean (Y)' is used.
     Similarly for `"<"', the one-sided alternative `mean (X) < mean
     (Y)' is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = t_test_regression (Y, X, RR, R, ALT)
     Perform an t test for the null hypothesis `RR * B = R' in a
     classical normal regression model `Y = X * B + E'.  Under the
     null, the test statistic T follows a T distribution with DF
     degrees of freedom.

     If R is omitted, a value of 0 is assumed.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `RR * B != R'.  If ALT is `">"',
     the one-sided alternative `RR * B > R' is used.  Similarly for
     "<", the one-sided alternative `RR * B < R' is used.  The default
     is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = u_test (X, Y, ALT)
     For two samples X and Y, perform a Mann-Whitney U-test of the null
     hypothesis PROB (X > Y) == 1/2 == PROB (X < Y).  Under the null,
     the test statistic Z approximately follows a standard normal
     distribution.  Note that this test is equivalent to the Wilcoxon
     rank-sum test.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative PROB (X > Y) != 1/2.  If ALT is
     `">"', the one-sided alternative PROB (X > Y) > 1/2 is considered.
     Similarly for `"<"', the one-sided alternative PROB (X > Y) < 1/2
     is considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, F, DF_NUM, DF_DEN] = var_test (X, Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and unknown variances, perform an F-test of the null
     hypothesis of equal variances.  Under the null, the test statistic
     F follows an F-distribution with DF_NUM and DF_DEN degrees of
     freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `var (X) != var (Y)'.  If ALT is
     `">"', the one-sided alternative `var (X) > var (Y)' is used.
     Similarly for "<", the one-sided alternative `var (X) > var (Y)'
     is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, T, DF] = welch_test (X, Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and unknown and not necessarily equal variances, perform a
     Welch test of the null hypothesis of equal means.  Under the null,
     the test statistic T approximately follows a Student distribution
     with DF degrees of freedom.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative mean(x) > M is considered.
     Similarly for `"<"', the one-sided alternative mean(x) < M is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = wilcoxon_test (X, Y, ALT)
     For two matched-pair sample vectors X and Y, perform a Wilcoxon
     signed-rank test of the null hypothesis PROB (X > Y) == 1/2.
     Under the null, the test statistic Z approximately follows a
     standard normal distribution when N > 25.

     *Warning*: This function assumes a normal distribution for Z and
     thus is invalid for N <= 25.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative PROB (X > Y) != 1/2.  If alt is
     `">"', the one-sided alternative PROB (X > Y) > 1/2 is considered.
     Similarly for `"<"', the one-sided alternative PROB (X > Y) < 1/2
     is considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

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

 -- Function File: [PVAL, Z] = z_test (X, M, V, ALT)
     Perform a Z-test of the null hypothesis `mean (X) == M' for a
     sample X from a normal distribution with unknown mean and known
     variance V.  Under the null, the test statistic Z follows a
     standard normal distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != M'.  If ALT is
     `">"', the one-sided alternative `mean (X) > M' is considered.
     Similarly for `"<"', the one-sided alternative `mean (X) < M' is
     considered.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

     If no output argument is given, the p-value of the test is
     displayed along with some information.

 -- Function File: [PVAL, Z] = z_test_2 (X, Y, V_X, V_Y, ALT)
     For two samples X and Y from normal distributions with unknown
     means and known variances V_X and V_Y, perform a Z-test of the
     hypothesis of equal means.  Under the null, the test statistic Z
     follows a standard normal distribution.

     With the optional argument string ALT, the alternative of interest
     can be selected.  If ALT is `"!="' or `"<>"', the null is tested
     against the two-sided alternative `mean (X) != mean (Y)'.  If alt
     is `">"', the one-sided alternative `mean (X) > mean (Y)' is used.
     Similarly for `"<"', the one-sided alternative `mean (X) < mean
     (Y)' is used.  The default is the two-sided case.

     The p-value of the test is returned in PVAL.

     If no output argument is given, the p-value of the test is
     displayed along with some information.


File: octave.info,  Node: Models,  Next: Distributions,  Prev: Tests,  Up: Statistics

25.5 Models
===========

 -- Function File: [THETA, BETA, DEV, DL, D2L, P] = logistic_regression
          (Y, X, PRINT, THETA, BETA)
     Perform ordinal logistic regression.

     Suppose Y takes values in K ordered categories, and let `gamma_i
     (X)' be the cumulative probability that Y falls in one of the
     first I categories given the covariate X.  Then

          [theta, beta] = logistic_regression (y, x)

     fits the model

          logit (gamma_i (x)) = theta_i - beta' * x,   i = 1 ... k-1

     The number of ordinal categories, K, is taken to be the number of
     distinct values of `round (Y)'.  If K equals 2, Y is binary and
     the model is ordinary logistic regression.  The matrix X is
     assumed to have full column rank.

     Given Y only, `theta = logistic_regression (y)' fits the model
     with baseline logit odds only.

     The full form is

          [theta, beta, dev, dl, d2l, gamma]
             = logistic_regression (y, x, print, theta, beta)

     in which all output arguments and all input arguments except Y are
     optional.

     Setting PRINT to 1 requests summary information about the fitted
     model to be displayed.  Setting PRINT to 2 requests information
     about convergence at each iteration.  Other values request no
     information to be displayed.  The input arguments THETA and BETA
     give initial estimates for THETA and BETA.

     The returned value DEV holds minus twice the log-likelihood.

     The returned values DL and D2L are the vector of first and the
     matrix of second derivatives of the log-likelihood with respect to
     THETA and BETA.

     P holds estimates for the conditional distribution of Y given X.


File: octave.info,  Node: Distributions,  Next: Random Number Generation,  Prev: Models,  Up: Statistics

25.6 Distributions
==================

Octave has functions for computing the Probability Density Function
(PDF), the Cumulative Distribution function (CDF), and the quantile
(the inverse of the CDF) of a large number of distributions.

   The following table summarizes the supported distributions (in
alphabetical order).

*Distribution*         *PDF*             *CDF*             *Quantile*
Beta Distribution      `betapdf'         `betacdf'         `betainv'
Binomial Distribution  `binopdf'         `binocdf'         `binoinv'
Cauchy Distribution    `cauchy_pdf'      `cauchy_cdf'      `cauchy_inv'
Chi-Square             `chi2pdf'         `chi2cdf'         `chi2inv'
Distribution                                               
Univariate Discrete    `discrete_pdf'    `discrete_cdf'    `discrete_inv'
Distribution                                               
Empirical Distribution `empirical_pdf'   `empirical_cdf'   `empirical_inv'
Exponential            `exppdf'          `expcdf'          `expinv'
Distribution                                               
F Distribution         `fpdf'            `fcdf'            `finv'
Gamma Distribution     `gampdf'          `gamcdf'          `gaminv'
Geometric Distribution `geopdf'          `geocdf'          `geoinv'
Hypergeometric         `hygepdf'         `hygecdf'         `hygeinv'
Distribution                                               
Kolmogorov Smirnov     _Not Available_   `kolmogorov_smirnov_cdf'_Not Available_
Distribution                                               
Laplace Distribution   `laplace_pdf'     `laplace_cdf'     `laplace_inv'
Logistic Distribution  `logistic_pdf'    `logistic_cdf'    `logistic_inv'
Log-Normal             `lognpdf'         `logncdf'         `logninv'
Distribution                                               
Pascal Distribution    `nbinpdf'         `nbincdf'         `nbininv'
Univariate Normal      `normpdf'         `normcdf'         `norminv'
Distribution                                               
Poisson Distribution   `poisspdf'        `poisscdf'        `poissinv'
t (Student)            `tpdf'            `tcdf'            `tinv'
Distribution                                               
Univariate Discrete    `unidpdf'         `unidcdf'         `unidinv'
Distribution                                               
Uniform Distribution   `unifpdf'         `unifcdf'         `unifinv'
Weibull Distribution   `wblpdf'          `wblcdf'          `wblinv'

 -- Function File:  betacdf (X, A, B)
     For each element of X, returns the CDF at X of the beta
     distribution with parameters A and B, i.e., PROB (beta (A, B) <=
     X).

 -- Function File:  betainv (X, A, B)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the Beta distribution with parameters A and B.

 -- Function File:  betapdf (X, A, B)
     For each element of X, returns the PDF at X of the beta
     distribution with parameters A and B.

 -- Function File:  binocdf (X, N, P)
     For each element of X, compute the CDF at X of the binomial
     distribution with parameters N and P.

 -- Function File:  binoinv (X, N, P)
     For each element of X, compute the quantile at X of the binomial
     distribution with parameters N and P.

 -- Function File:  binopdf (X, N, P)
     For each element of X, compute the probability density function
     (PDF) at X of the binomial distribution with parameters N and P.

 -- Function File:  cauchy_cdf (X, LAMBDA, SIGMA)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the Cauchy distribution with location
     parameter LAMBDA and scale parameter SIGMA.  Default values are
     LAMBDA = 0, SIGMA = 1.

 -- Function File:  cauchy_inv (X, LAMBDA, SIGMA)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the Cauchy distribution with location parameter
     LAMBDA and scale parameter SIGMA.  Default values are LAMBDA = 0,
     SIGMA = 1.

 -- Function File:  cauchy_pdf (X, LAMBDA, SIGMA)
     For each element of X, compute the probability density function
     (PDF) at X of the Cauchy distribution with location parameter
     LAMBDA and scale parameter SIGMA > 0.  Default values are LAMBDA =
     0, SIGMA = 1.

 -- Function File:  chi2cdf (X, N)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the chisquare distribution with N degrees
     of freedom.

 -- Function File:  chi2inv (X, N)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the chisquare distribution with N degrees of freedom.

 -- Function File:  chisquare_pdf (X, N)
     For each element of X, compute the probability density function
     (PDF) at X of the chisquare distribution with N degrees of freedom.

 -- Function File:  discrete_cdf (X, V, P)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of a univariate discrete distribution which
     assumes the values in V with probabilities P.

 -- Function File:  discrete_inv (X, V, P)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the univariate distribution which assumes the values
     in V with probabilities P.

 -- Function File:  discrete_pdf (X, V, P)
     For each element of X, compute the probability density function
     (PDF) at X of a univariate discrete distribution which assumes the
     values in V with probabilities P.

 -- Function File:  empirical_cdf (X, DATA)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the empirical distribution obtained from
     the univariate sample DATA.

 -- Function File:  empirical_inv (X, DATA)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the empirical distribution obtained from the
     univariate sample DATA.

 -- Function File:  empirical_pdf (X, DATA)
     For each element of X, compute the probability density function
     (PDF) at X of the empirical distribution obtained from the
     univariate sample DATA.

 -- Function File:  expcdf (X, LAMBDA)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the exponential distribution with mean
     LAMBDA.

     The arguments can be of common size or scalar.

 -- Function File:  expinv (X, LAMBDA)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the exponential distribution with mean LAMBDA.

 -- Function File:  exppdf (X, LAMBDA)
     For each element of X, compute the probability density function
     (PDF) of the exponential distribution with mean LAMBDA.

 -- Function File:  fcdf (X, M, N)
     For each element of X, compute the CDF at X of the F distribution
     with M and N degrees of freedom, i.e., PROB (F (M, N) <= X).

 -- Function File:  finv (X, M, N)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the F distribution with parameters M and N.

 -- Function File:  fpdf (X, M, N)
     For each element of X, compute the probability density function
     (PDF) at X of the F distribution with M and N degrees of freedom.

 -- Function File:  gamcdf (X, A, B)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the Gamma distribution with parameters A
     and B.

     *See also:* *note gamma: doc-gamma, *note gammaln: doc-gammaln,
     *note gammainc: doc-gammainc, *note gampdf: doc-gampdf, *note
     gaminv: doc-gaminv, *note gamrnd: doc-gamrnd.

 -- Function File:  gaminv (X, A, B)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the Gamma distribution with parameters A and B.

     *See also:* *note gamma: doc-gamma, *note gammaln: doc-gammaln,
     *note gammainc: doc-gammainc, *note gampdf: doc-gampdf, *note
     gamcdf: doc-gamcdf, *note gamrnd: doc-gamrnd.

 -- Function File:  gampdf (X, A, B)
     For each element of X, return the probability density function
     (PDF) at X of the Gamma distribution with parameters A and B.

     *See also:* *note gamma: doc-gamma, *note gammaln: doc-gammaln,
     *note gammainc: doc-gammainc, *note gamcdf: doc-gamcdf, *note
     gaminv: doc-gaminv, *note gamrnd: doc-gamrnd.

 -- Function File:  geocdf (X, P)
     For each element of X, compute the CDF at X of the geometric
     distribution with parameter P.

 -- Function File:  geoinv (X, P)
     For each element of X, compute the quantile at X of the geometric
     distribution with parameter P.

 -- Function File:  geopdf (X, P)
     For each element of X, compute the probability density function
     (PDF) at X of the geometric distribution with parameter P.

 -- Function File:  hygecdf (X, T, M, N)
     Compute the cumulative distribution function (CDF) at X of the
     hypergeometric distribution with parameters T, M, and N.  This is
     the probability of obtaining not more than X marked items when
     randomly drawing a sample of size N without replacement from a
     population of total size T containing M marked items.

     The parameters T, M, and N must positive integers with M and N not
     greater than T.

 -- Function File:  hygeinv (X, T, M, N)
     For each element of X, compute the quantile at X of the
     hypergeometric distribution with parameters T, M, and N.

     The parameters T, M, and N must positive integers with M and N not
     greater than T.

 -- Function File:  hygepdf (X, T, M, N)
     Compute the probability density function (PDF) at X of the
     hypergeometric distribution with parameters T, M, and N.  This is
     the probability of obtaining X marked items when randomly drawing
     a sample of size N without replacement from a population of total
     size T containing M marked items.

     The arguments must be of common size or scalar.

 -- Function File:  kolmogorov_smirnov_cdf (X, TOL)
     Return the CDF at X of the Kolmogorov-Smirnov distribution,
                   Inf
          Q(x) =   SUM    (-1)^k exp(-2 k^2 x^2)
                 k = -Inf

     for X > 0.

     The optional parameter TOL specifies the precision up to which the
     series should be evaluated;  the default is TOL = `eps'.

 -- Function File:  laplace_cdf (X)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the Laplace distribution.

 -- Function File:  laplace_inv (X)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the Laplace distribution.

 -- Function File:  laplace_pdf (X)
     For each element of X, compute the probability density function
     (PDF) at X of the Laplace distribution.

 -- Function File:  logistic_cdf (X)
     For each component of X, compute the CDF at X of the logistic
     distribution.

 -- Function File:  logistic_inv (X)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the logistic distribution.

 -- Function File:  logistic_pdf (X)
     For each component of X, compute the PDF at X of the logistic
     distribution.

 -- Function File:  logncdf (X, MU, SIGMA)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the lognormal distribution with parameters
     MU and SIGMA.  If a random variable follows this distribution, its
     logarithm is normally distributed with mean MU and standard
     deviation SIGMA.

     Default values are MU = 1, SIGMA = 1.

 -- Function File:  logninv (X, MU, SIGMA)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the lognormal distribution with parameters MU and
     SIGMA.  If a random variable follows this distribution, its
     logarithm is normally distributed with mean `log (MU)' and
     variance SIGMA.

     Default values are MU = 1, SIGMA = 1.

 -- Function File:  lognpdf (X, MU, SIGMA)
     For each element of X, compute the probability density function
     (PDF) at X of the lognormal distribution with parameters MU and
     SIGMA.  If a random variable follows this distribution, its
     logarithm is normally distributed with mean MU and standard
     deviation SIGMA.

     Default values are MU = 1, SIGMA = 1.

 -- Function File:  nbincdf (X, N, P)
     For each element of X, compute the CDF at x of the Pascal
     (negative binomial) distribution with parameters N and P.

     The number of failures in a Bernoulli experiment with success
     probability P before the N-th success follows this distribution.

 -- Function File:  nbininv (X, N, P)
     For each element of X, compute the quantile at X of the Pascal
     (negative binomial) distribution with parameters N and P.

     The number of failures in a Bernoulli experiment with success
     probability P before the N-th success follows this distribution.

 -- Function File:  nbinpdf (X, N, P)
     For each element of X, compute the probability density function
     (PDF) at X of the Pascal (negative binomial) distribution with
     parameters N and P.

     The number of failures in a Bernoulli experiment with success
     probability P before the N-th success follows this distribution.

 -- Function File:  normcdf (X, M, S)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the normal distribution with mean M and
     standard deviation S.

     Default values are M = 0, S = 1.

 -- Function File:  norminv (X, M, S)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the normal distribution with mean M and standard
     deviation S.

     Default values are M = 0, S = 1.

 -- Function File:  normpdf (X, M, S)
     For each element of X, compute the probability density function
     (PDF) at X of the normal distribution with mean M and standard
     deviation S.

     Default values are M = 0, S = 1.

 -- Function File:  poisscdf (X, LAMBDA)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the Poisson distribution with parameter
     lambda.

 -- Function File:  poissinv (X, LAMBDA)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the Poisson distribution with parameter LAMBDA.

 -- Function File:  poisspdf (X, LAMBDA)
     For each element of X, compute the probability density function
     (PDF) at X of the poisson distribution with parameter LAMBDA.

 -- Function File:  tcdf (X, N)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the t (Student) distribution with N degrees
     of freedom, i.e., PROB (t(N) <= X).

 -- Function File:  tinv (X, N)
     For each probability value X, compute the inverse of the
     cumulative distribution function (CDF) of the t (Student)
     distribution with degrees of freedom N.  This function is
     analogous to looking in a table for the t-value of a single-tailed
     distribution.

 -- Function File:  tpdf (X, N)
     For each element of X, compute the probability density function
     (PDF) at X of the T (Student) distribution with N degrees of
     freedom.

 -- Function File:  unidcdf (X, V)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of a univariate discrete distribution which
     assumes the values in V with equal probability.

 -- Function File:  unidinv (X, V)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the univariate discrete distribution which assumes the
     values in V with equal probability

 -- Function File:  unidpdf (X, V)
     For each element of X, compute the probability density function
     (PDF) at X of a univariate discrete distribution which assumes the
     values in V with equal probability.

 -- Function File:  unifcdf (X, A, B)
     Return the CDF at X of the uniform distribution on [A, B], i.e.,
     PROB (uniform (A, B) <= x).

     Default values are A = 0, B = 1.

 -- Function File:  unifinv (X, A, B)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the uniform distribution on [A, B].

     Default values are A = 0, B = 1.

 -- Function File:  unifpdf (X, A, B)
     For each element of X, compute the PDF at X of the uniform
     distribution on [A, B].

     Default values are A = 0, B = 1.

 -- Function File:  wblcdf (X, SCALE, SHAPE)
     Compute the cumulative distribution function (CDF) at X of the
     Weibull distribution with shape parameter SCALE and scale
     parameter SHAPE, which is

          1 - exp(-(x/shape)^scale)
     for X >= 0.

 -- Function File:  wblinv (X, SCALE, SHAPE)
     Compute the quantile (the inverse of the CDF) at X of the Weibull
     distribution with shape parameter SCALE and scale parameter SHAPE.

 -- Function File:  wblpdf (X, SCALE, SHAPE)
     Compute the probability density function (PDF) at X of the Weibull
     distribution with shape parameter SCALE and scale parameter SHAPE
     which is given by

             scale * shape^(-scale) * x^(scale-1) * exp(-(x/shape)^scale)

     for X > 0.


File: octave.info,  Node: Random Number Generation,  Prev: Distributions,  Up: Statistics

25.7 Random Number Generation
=============================

Octave can generate random numbers from a large number of distributions.
The random number generators are based on the random number generators
described in *note Special Utility Matrices::.

   The following table summarizes the available random number generators
(in alphabetical order).

*Distribution*                *Function*
Beta Distribution             `betarnd'
Binomial Distribution         `binornd'
Cauchy Distribution           `cauchy_rnd'
Chi-Square Distribution       `chi2rnd'
Univariate Discrete           `discrete_rnd'
Distribution                  
Empirical Distribution        `empirical_rnd'
Exponential Distribution      `exprnd'
F Distribution                `frnd'
Gamma Distribution            `gamrnd'
Geometric Distribution        `geornd'
Hypergeometric Distribution   `hygernd'
Laplace Distribution          `laplace_rnd'
Logistic Distribution         `logistic_rnd'
Log-Normal Distribution       `lognrnd'
Pascal Distribution           `nbinrnd'
Univariate Normal             `normrnd'
Distribution                  
Poisson Distribution          `poissrnd'
t (Student) Distribution      `trnd'
Univariate Discrete           `unidrnd'
Distribution                  
Uniform Distribution          `unifrnd'
Weibull Distribution          `wblrnd'
Wiener Process                `wienrnd'

 -- Function File:  betarnd (A, B, R, C)
 -- Function File:  betarnd (A, B, SZ)
     Return an R by C or `size (SZ)' matrix of random samples from the
     Beta distribution with parameters A and B.  Both A and B must be
     scalar or of size R  by C.

     If R and C are omitted, the size of the result matrix is the
     common size of A and B.

 -- Function File:  binornd (N, P, R, C)
 -- Function File:  binornd (N, P, SZ)
     Return an R by C  or a `size (SZ)' matrix of random samples from
     the binomial distribution with parameters N and P.  Both N and P
     must be scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of N and P.

 -- Function File:  cauchy_rnd (LAMBDA, SIGMA, R, C)
 -- Function File:  cauchy_rnd (LAMBDA, SIGMA, SZ)
     Return an R by C or a `size (SZ)' matrix of random samples from
     the Cauchy distribution with parameters LAMBDA and SIGMA which
     must both be scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of LAMBDA and SIGMA.

 -- Function File:  chi2rnd (N, R, C)
 -- Function File:  chi2rnd (N, SZ)
     Return an R by C  or a `size (SZ)' matrix of random samples from
     the chisquare distribution with N degrees of freedom.  N must be a
     scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the size
     of N.

 -- Function File:  discrete_rnd (N, V, P)
 -- Function File:  discrete_rnd (V, P, R, C)
 -- Function File:  discrete_rnd (V, P, SZ)
     Generate a row vector containing a random sample of size N from
     the univariate distribution which assumes the values in V with
     probabilities P.  N must be a scalar.

     If R and C are given create a matrix with R rows and C columns.
     Or if SZ is a vector, create a matrix of size SZ.

 -- Function File:  empirical_rnd (N, DATA)
 -- Function File:  empirical_rnd (DATA, R, C)
 -- Function File:  empirical_rnd (DATA, SZ)
     Generate a bootstrap sample of size N from the empirical
     distribution obtained from the univariate sample DATA.

     If R and C are given create a matrix with R rows and C columns.
     Or if SZ is a vector, create a matrix of size SZ.

 -- Function File:  exprnd (LAMBDA, R, C)
 -- Function File:  exprnd (LAMBDA, SZ)
     Return an R by C matrix of random samples from the exponential
     distribution with mean LAMBDA, which must be a scalar or of size R
     by C.  Or if SZ is a vector, create a matrix of size SZ.

     If R and C are omitted, the size of the result matrix is the size
     of LAMBDA.

 -- Function File:  frnd (M, N, R, C)
 -- Function File:  frnd (M, N, SZ)
     Return an R by C matrix of random samples from the F distribution
     with M and N degrees of freedom.  Both M and N must be scalar or
     of size R by C.  If SZ is a vector the random samples are in a
     matrix of size SZ.

     If R and C are omitted, the size of the result matrix is the
     common size of M and N.

 -- Function File:  gamrnd (A, B, R, C)
 -- Function File:  gamrnd (A, B, SZ)
     Return an R by C or a `size (SZ)' matrix of random samples from
     the Gamma distribution with parameters A and B.  Both A and B must
     be scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of A and B.

     *See also:* *note gamma: doc-gamma, *note gammaln: doc-gammaln,
     *note gammainc: doc-gammainc, *note gampdf: doc-gampdf, *note
     gamcdf: doc-gamcdf, *note gaminv: doc-gaminv.

 -- Function File:  geornd (P, R, C)
 -- Function File:  geornd (P, SZ)
     Return an R by C matrix of random samples from the geometric
     distribution with parameter P, which must be a scalar or of size R
     by C.

     If R and C are given create a matrix with R rows and C columns.
     Or if SZ is a vector, create a matrix of size SZ.

 -- Function File:  hygernd (T, M, N, R, C)
 -- Function File:  hygernd (T, M, N, SZ)
 -- Function File:  hygernd (T, M, N)
     Return an R by C matrix of random samples from the hypergeometric
     distribution with parameters T, M, and N.

     The parameters T, M, and N must positive integers with M and N not
     greater than T.

     The parameter SZ must be scalar or a vector of matrix dimensions.
     If SZ is scalar, then a SZ by SZ matrix of random samples is
     generated.

 -- Function File:  laplace_rnd (R, C)
 -- Function File:  laplace_rnd (SZ);
     Return an R by C matrix of random numbers from the Laplace
     distribution.  Or if SZ is a vector, create a matrix of SZ.

 -- Function File:  logistic_rnd (R, C)
 -- Function File:  logistic_rnd (SZ)
     Return an R by C matrix of random numbers from the logistic
     distribution.  Or if SZ is a vector, create a matrix of SZ.

 -- Function File:  lognrnd (MU, SIGMA, R, C)
 -- Function File:  lognrnd (MU, SIGMA, SZ)
     Return an R by C matrix of random samples from the lognormal
     distribution with parameters MU and SIGMA.  Both MU and SIGMA must
     be scalar or of size R by C.  Or if SZ is a vector, create a
     matrix of size SZ.

     If R and C are omitted, the size of the result matrix is the
     common size of MU and SIGMA.

 -- Function File:  nbinrnd (N, P, R, C)
 -- Function File:  nbinrnd (N, P, SZ)
     Return an R by C matrix of random samples from the Pascal
     (negative binomial) distribution with parameters N and P.  Both N
     and P must be scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of N and P.  Or if SZ is a vector, create a matrix of
     size SZ.

 -- Function File:  normrnd (M, S, R, C)
 -- Function File:  normrnd (M, S, SZ)
     Return an R by C  or `size (SZ)' matrix of random samples from the
     normal distribution with parameters mean M and standard deviation
     S.  Both M and S must be scalar or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of M and S.

 -- Function File:  poissrnd (LAMBDA, R, C)
     Return an R by C matrix of random samples from the Poisson
     distribution with parameter LAMBDA, which must be a scalar or of
     size R by C.

     If R and C are omitted, the size of the result matrix is the size
     of LAMBDA.

 -- Function File:  trnd (N, R, C)
 -- Function File:  trnd (N, SZ)
     Return an R by C matrix of random samples from the t (Student)
     distribution with N degrees of freedom.  N must be a scalar or of
     size R by C.  Or if SZ is a vector create a matrix of size SZ.

     If R and C are omitted, the size of the result matrix is the size
     of N.

 -- Function File:  unidrnd (MX);
 -- Function File:  unidrnd (MX, V);
 -- Function File:  unidrnd (MX, M, N, ...);
     Return random values from discrete uniform distribution, with
     maximum value(s) given by the integer MX, which may be a scalar or
     multidimensional array.

     If MX is a scalar, the size of the result is specified by the
     vector V, or by the optional arguments M, N, ....  Otherwise, the
     size of the result is the same as the size of MX.

 -- Function File:  unifrnd (A, B, R, C)
 -- Function File:  unifrnd (A, B, SZ)
     Return an R by C or a `size (SZ)' matrix of random samples from
     the uniform distribution on [A, B].  Both A and B must be scalar
     or of size R by C.

     If R and C are omitted, the size of the result matrix is the
     common size of A and B.

 -- Function File:  wblrnd (SCALE, SHAPE, R, C)
 -- Function File:  wblrnd (SCALE, SHAPE, SZ)
     Return an R by C matrix of random samples from the Weibull
     distribution with parameters SCALE and SHAPE which must be scalar
     or of size R by C.  Or if SZ is a vector return a matrix of size
     SZ.

     If R and C are omitted, the size of the result matrix is the
     common size of ALPHA and SIGMA.

 -- Function File:  wienrnd (T, D, N)
     Return a simulated realization of the D-dimensional Wiener Process
     on the interval [0, T].  If D is omitted, D = 1 is used.  The
     first column of the return matrix contains time, the remaining
     columns contain the Wiener process.

     The optional parameter N gives the number of summands used for
     simulating the process over an interval of length 1.  If N is
     omitted, N = 1000 is used.


File: octave.info,  Node: Sets,  Next: Polynomial Manipulations,  Prev: Statistics,  Up: Top

26 Sets
*******

Octave has a limited number of functions for managing sets of data,
where a set is defined as a collection of unique elements.  In Octave a
set is represented as a vector of numbers.

 -- Function File:  unique (X)
 -- Function File:  unique (X, "rows")
 -- Function File:  unique (..., "first")
 -- Function File:  unique (..., "last")
 -- Function File: [Y, I, J] = unique (...)
     Return the unique elements of X, sorted in ascending order.  If X
     is a row vector, return a row vector, but if X is a column vector
     or a matrix return a column vector.

     If the optional argument `"rows"' is supplied, return the unique
     rows of X, sorted in ascending order.

     If requested, return index vectors I and J such that `x(i)==y' and
     `y(j)==x'.

     Additionally, one of `"first"' or `"last"' may be given as an
     argument.  If `"last"' is specified, return the highest possible
     indices in I, otherwise, if `"first"' is specified, return the
     lowest.  The default is `"last"'.

     *See also:* *note union: doc-union, *note intersect:
     doc-intersect, *note setdiff: doc-setdiff, *note setxor:
     doc-setxor, *note ismember: doc-ismember.

* Menu:

* Set Operations::


File: octave.info,  Node: Set Operations,  Up: Sets

26.1 Set Operations
===================

Octave supports the basic set operations.  That is, Octave can compute
the union, intersection, complement, and difference of two sets.
Octave also supports the _Exclusive Or_ set operation, and membership
determination.  The functions for set operations all work in pretty
much the same way.  As an example, assume that `x' and `y' contains two
sets, then

     union(x, y)

computes the union of the two sets.

 -- Function File: [TF = ismember (A, S)
 -- Function File: [TF, S_IDX] = ismember (A, S)
 -- Function File: [TF, S_IDX] = ismember (A, S, "rows")
     Return a matrix TF with the same shape as A which has a 1 if
     `A(i,j)' is in S and 0 if it is not.  If a second output argument
     is requested, the index into S of each of the matching elements is
     also returned.

          a = [3, 10, 1];
          s = [0:9];
          [tf, s_idx] = ismember (a, s);
               => tf = [1, 0, 1]
               => s_idx = [4, 0, 2]

     The inputs, A and S, may also be cell arrays.

          a = {'abc'};
          s = {'abc', 'def'};
          [tf, s_idx] = ismember (a, s);
               => tf = [1, 0]
               => s_idx = [1, 0]

     With the optional third argument `"rows"', and matrices A and S
     with the same number of columns, compare rows in A with the rows
     in S.

          a = [1:3; 5:7; 4:6];
          s = [0:2; 1:3; 2:4; 3:5; 4:6];
          [tf, s_idx] = ismember(a, s, 'rows');
               => tf = logical ([1; 0; 1])
               => s_idx = [2; 0; 5];

     *See also:* *note unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setxor: doc-setxor, *note
     setdiff: doc-setdiff.

 -- Function File:  union (A, B)
 -- Function File:  union (A, B, "rows")
     Return the set of elements that are in either of the sets A and B.
     For example,

          union ([1, 2, 4], [2, 3, 5])
               => [1, 2, 3, 4, 5]

     If the optional third input argument is the string "rows" each row
     of the matrices A and B will be considered an element of sets.
     For example,
          union([1, 2; 2, 3], [1, 2; 3, 4], "rows")
               =>  1   2
              2   3
              3   4

 -- Function File: [C, IA, IB] = union (A, B)
     Return index vectors IA and IB such that `a == c(ia)' and `b ==
     c(ib)'.

     *See also:* *note intersect: doc-intersect, *note complement:
     doc-complement, *note unique: doc-unique.

 -- Function File:  intersect (A, B)
 -- Function File: [C, IA, IB] = intersect (A, B)
     Return the elements in both A and B, sorted in ascending order.
     If A and B are both column vectors return a column vector,
     otherwise return a row vector.

     Return index vectors IA and IB such that `a(ia)==c' and `b(ib)==c'.


*See also:* *note unique: doc-unique, *note union: doc-union, *note
setxor: doc-setxor, *note setdiff: doc-setdiff, *note ismember:
doc-ismember.

 -- Function File:  complement (X, Y)
     Return the elements of set Y that are not in set X.  For example,

          complement ([ 1, 2, 3 ], [ 2, 3, 5 ])
               => 5

     *See also:* *note union: doc-union, *note intersect:
     doc-intersect, *note unique: doc-unique.

 -- Function File:  setdiff (A, B)
 -- Function File:  setdiff (A, B, "rows")
 -- Function File: [C, I] = setdiff (A, B)
     Return the elements in A that are not in B, sorted in ascending
     order.  If A and B are both column vectors return a column vector,
     otherwise return a row vector.

     Given the optional third argument `"rows"', return the rows in A
     that are not in B, sorted in ascending order by rows.

     If requested, return I such that `c = a(i)'.

     *See also:* *note unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setxor: doc-setxor, *note
     ismember: doc-ismember.

 -- Function File:  setxor (A, B)
 -- Function File:  setxor (A, B, 'rows')
     Return the elements exclusive to A or B, sorted in ascending
     order.  If A and B are both column vectors return a column vector,
     otherwise return a row vector.

 -- Function File: [C, IA, IB] = setxor (A, B)
     Return index vectors IA and IB such that `a == c(ia)' and `b ==
     c(ib)'.

     *See also:* *note unique: doc-unique, *note union: doc-union,
     *note intersect: doc-intersect, *note setdiff: doc-setdiff, *note
     ismember: doc-ismember.


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

27 Polynomial Manipulations
***************************

In Octave, a polynomial is represented by its coefficients (arranged in
descending order).  For example, a vector C of length N+1 corresponds
to the following polynomial of order  N

     p(x) = C(1) x^N + ... + C(N) x + C(N+1).

* Menu:

* Evaluating Polynomials::
* Finding Roots::
* Products of Polynomials::
* Derivatives and Integrals::
* Polynomial Interpolation::
* Miscellaneous Functions::


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

27.1 Evaluating Polynomials
===========================

The value of a polynomial represented by the vector C can be evaluated
at the point X very easily, as the following example shows:

     N = length(c)-1;
     val = dot( x.^(N:-1:0), c );

While the above example shows how easy it is to compute the value of a
polynomial, it isn't the most stable algorithm.  With larger polynomials
you should use more elegant algorithms, such as Horner's Method, which
is exactly what the Octave function `polyval' does.

   In the case where X is a square matrix, the polynomial given by C is
still well-defined.  As when X is a scalar the obvious implementation
is easily expressed in Octave, but also in this case more elegant
algorithms perform better.  The `polyvalm' function provides such an
algorithm.

 -- Function File: Y = polyval (P, X)
 -- Function File: Y = polyval (P, X, [], MU)
     Evaluate the polynomial at of the specified values for X.  When MU
     is present evaluate the polynomial for (X-MU(1))/MU(2).  If X is a
     vector or matrix, the polynomial is evaluated for each of the
     elements of X.

 -- Function File: [Y, DY] = polyval (P, X, S)
 -- Function File: [Y, DY] = polyval (P, X, S, MU)
     In addition to evaluating the polynomial, the second output
     represents the prediction interval, Y +/- DY, which contains at
     least 50% of the future predictions.  To calculate the prediction
     interval, the structured variable S, originating form `polyfit',
     must be present.

     *See also:* *note polyfit: doc-polyfit, *note polyvalm:
     doc-polyvalm, *note poly: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue, *note filter: doc-filter, *note polyderiv:
     doc-polyderiv, *note polyinteg: doc-polyinteg.

 -- Function File:  polyvalm (C, X)
     Evaluate a polynomial in the matrix sense.

     `polyvalm (C, X)' will evaluate the polynomial in the matrix
     sense, i.e., matrix multiplication is used instead of element by
     element multiplication as is used in polyval.

     The argument X must be a square matrix.

     *See also:* *note polyval: doc-polyval, *note poly: doc-poly,
     *note roots: doc-roots, *note conv: doc-conv, *note deconv:
     doc-deconv, *note residue: doc-residue, *note filter: doc-filter,
     *note polyderiv: doc-polyderiv, *note polyinteg: doc-polyinteg.


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

27.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 compan: doc-compan.

 -- 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 poly: doc-poly, *note roots: doc-roots, *note
     residue: doc-residue, *note conv: doc-conv, *note deconv:
     doc-deconv, *note polyval: doc-polyval, *note polyderiv:
     doc-polyderiv, *note polyinteg: doc-polyinteg.

 -- Function File: [MULTP, INDX] = mpoles (P)
 -- Function File: [MULTP, INDX] = mpoles (P, TOL)
 -- Function File: [MULTP, INDX] = mpoles (P, TOL, REORDER)
     Identify unique poles in P and associates their multiplicity,
     ordering them from largest to smallest.

     If the relative difference of the 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 value MULTP is a vector specifying the multiplicity of the
     poles.  MULTP(:) refers to multiplicity of P(INDX(:)).

     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 poly: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note polyval:
     doc-polyval, *note polyderiv: doc-polyderiv, *note polyinteg:
     doc-polyinteg, *note residue: doc-residue.


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

27.3 Products of Polynomials
============================

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

     `y = conv (a, b)' returns a vector of length equal to `length (a)
     + length (b) - 1'.  If A and B are polynomial coefficient vectors,
     `conv' returns the coefficients of the product polynomial.

     *See also:* *note deconv: doc-deconv, *note poly: doc-poly, *note
     roots: doc-roots, *note residue: doc-residue, *note polyval:
     doc-polyval, *note polyderiv: doc-polyderiv, *note polyinteg:
     doc-polyinteg.

 -- Function File: C = convn (A, B, SHAPE)
     N-dimensional convolution of matrices A and B.

     The size of the output is determined by the SHAPE argument.  This
     can be any of the following character strings:

    "full"
          The full convolution result is returned.  The size out of the
          output is `size (A) + size (B)-1'.  This is the default
          behavior.

    "same"
          The central part of the convolution result is returned.  The
          size out of the output is the same as A.

    "valid"
          The valid part of the convolution is returned.  The size of
          the result is `max (size (A) - size (B)+1, 0)'.

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

 -- 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: doc-conv, *note poly: doc-poly, *note
     roots: doc-roots, *note residue: doc-residue, *note polyval:
     doc-polyval, *note polyderiv: doc-polyderiv, *note polyinteg:
     doc-polyinteg.

 -- Loadable Function: y = conv2 (A, B, SHAPE)
 -- Loadable Function: y = conv2 (V1, V2, M, SHAPE)
     Returns 2D convolution of A and B where the size of C is given by

    SHAPE= 'full'
          returns full 2-D convolution

    SHAPE= 'same'
          same size as a. 'central' part of convolution

    SHAPE= 'valid'
          only parts which do not include zero-padded edges

     By default SHAPE is 'full'.  When the third argument is a matrix
     returns the convolution of the matrix M by the vector V1 in the
     column direction and by vector V2 in the row direction

 -- Function File: Q = polygcd (B, A, TOL)
     Find 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.  Tolerance defaults to
          sqrt(eps).
      Note that this is an unstable algorithm, so don't try it on large
     polynomials.

     Example
          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: doc-poly, *note polyinteg: doc-polyinteg,
     *note polyderiv: doc-polyderiv, *note polyreduce: doc-polyreduce,
     *note roots: doc-roots, *note conv: doc-conv, *note deconv:
     doc-deconv, *note residue: doc-residue, *note filter: doc-filter,
     *note polyval: doc-polyval, *note polyvalm: doc-polyvalm.

 -- Function File: [R, P, K, E] = residue (B, A)
     Compute 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)

 -- Function File: [B, A] = residue (R, P, K)
 -- Function File: [B, A] = residue (R, P, K, E)
     Compute 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 script mpoles.m.

     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.m 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 poly: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note mpoles:
     doc-mpoles, *note polyval: doc-polyval, *note polyderiv:
     doc-polyderiv, *note polyinteg: doc-polyinteg.


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

27.4 Derivatives and Integrals
==============================

Octave comes with functions for computing the derivative and the
integral of a polynomial.  The functions `polyderiv' 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:  polyderiv (C)
 -- Function File: [Q] = polyderiv (B, A)
 -- Function File: [Q, R] = polyderiv (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by vector C.  If a pair of polynomials is
     given B and A, the derivative of the product is returned in Q, or
     the quotient numerator in Q and the quotient denominator in R.

     *See also:* *note poly: doc-poly, *note polyinteg: doc-polyinteg,
     *note polyreduce: doc-polyreduce, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue, *note filter: doc-filter, *note polygcd: doc-polygcd,
     *note polyval: doc-polyval, *note polyvalm: doc-polyvalm.

 -- Function File:  polyder (C)
 -- Function File: [Q] = polyder (B, A)
 -- Function File: [Q, R] = polyder (B, A)
     See polyderiv.

 -- Function File:  polyinteg (C)
     Return the coefficients of the integral of the polynomial whose
     coefficients are represented by the vector C.

     The constant of integration is set to zero.

     *See also:* *note polyint: doc-polyint, *note poly: doc-poly,
     *note polyderiv: doc-polyderiv, *note polyreduce: doc-polyreduce,
     *note roots: doc-roots, *note conv: doc-conv, *note deconv:
     doc-deconv, *note residue: doc-residue, *note filter: doc-filter,
     *note polyval: doc-polyval, *note polyvalm: doc-polyvalm.

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

     *See also:* *note poly: doc-poly, *note polyderiv: doc-polyderiv,
     *note polyreduce: doc-polyreduce, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue, *note filter: doc-filter, *note polyval: doc-polyval,
     *note polyvalm: doc-polyvalm.


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

27.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 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 is what the `polyfit'
function does.

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

     The polynomial coefficients are returned in a row vector.

     The second output 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.

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

     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: doc-polyval, *note residue: doc-residue.

   In situations where a single polynomial isn't good enough, a solution
is to use several polynomials pieced together.  The function `mkpp'
creates a piece-wise polynomial, `ppval' evaluates the function created
by `mkpp', and `unmkpp' returns detailed information about the function.

   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: YI = ppval (PP, XI)
     Evaluate piece-wise polynomial PP at the points XI.  If `PP.d' is
     a scalar greater than 1, or an array, then the returned value YI
     will be an array that is `d1, d1, ..., dk, length (XI)]'.

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

 -- Function File: PP = mkpp (X, P)
 -- Function File: PP = mkpp (X, P, D)
     Construct a piece-wise polynomial structure from sample points X
     and coefficients P.  The i-th row of P, `P (I,:)', contains the
     coefficients for the polynomial over the I-th interval, ordered
     from highest to lowest.  There must be one row for each interval
     in X, so `rows (P) == length (X) - 1'.

     You can concatenate multiple polynomials of the same order over the
     same set of intervals using `P = [ P1; P2; ...; PD ]'.  In this
     case, `rows (P) == D * (length (X) - 1)'.

     D specifies the shape of the matrix P for all except the last
     dimension.  If D is not specified it will be computed as `round
     (rows (P) / (length (X) - 1))' instead.

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

 -- Function File: [X, P, N, K, D] = unmkpp (PP)
     Extract the components of a piece-wise polynomial structure PP.
     These are as follows:

    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.  However, this is stored as a 2-D
          array such that `C = reshape (P (:, J), N, D)' gives `C (I,
          R)' is the j-th coefficient of the r-th polynomial over the
          i-th interval.

    N
          Number of polynomial pieces.

    K
          Order of the polynomial plus 1.

    D
          Number of polynomials defined for each interval.

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


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

27.6 Miscellaneous Functions
============================

 -- Function File:  poly (A)
     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.  As an example we can use this to find the
     eigenvalues of A as the roots of `poly (A)'.
          roots(poly(eye(3)))
          => 1.00000 + 0.00000i
          => 1.00000 - 0.00000i
          => 1.00000 + 0.00000i
     In real-life examples you should, however, use the `eig' function
     for computing eigenvalues.

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

     *See also:* *note eig: doc-eig, *note roots: doc-roots.

 -- Function File:  polyout (C, X)
     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 polyval: doc-polyval, *note polyvalm:
     doc-polyvalm, *note poly: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue, *note filter: doc-filter, *note polyderiv:
     doc-polyderiv, *note polyinteg: doc-polyinteg.

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

     *See also:* *note poly: doc-poly, *note roots: doc-roots, *note
     conv: doc-conv, *note deconv: doc-deconv, *note residue:
     doc-residue, *note filter: doc-filter, *note polyval: doc-polyval,
     *note polyvalm: doc-polyvalm, *note polyderiv: doc-polyderiv,
     *note polyinteg: doc-polyinteg.


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

28 Interpolation
****************

* Menu:

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


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

28.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
further methods.

 -- Function File: YI = interp1 (X, Y, XI)
 -- Function File: YI = interp1 (..., METHOD)
 -- Function File: YI = interp1 (..., EXTRAP)
 -- Function File: PP = interp1 (..., 'pp')
     One-dimensional interpolation.  Interpolate Y, defined at the
     points X, at the points XI.  The sample points X must be strictly
     monotonic.  If Y is an array, treat the columns of Y separately.

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors

    'pchip'
          Piece-wise cubic hermite interpolating polynomial

    'cubic'
          Cubic interpolation from four nearest neighbors

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

     Appending '*' to the start of the above method 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.  If EXTRAP is a number, replace values beyond the
     endpoints with that number.  If EXTRAP is missing, assume NA.

     If the string argument 'pp' is specified, then XI should not be
     supplied and `interp1' returns the piece-wise polynomial that 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')'.

     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);
          spl = interp1 (xp, yp, xf, "spline");
          cub = interp1 (xp, yp, xf, "cubic");
          near = interp1 (xp, yp, xf, "nearest");
          plot (xf, yf, "r", xf, lin, "g", xf, spl, "b",
                xf, cub, "c", xf, near, "m", xp, yp, "r*");
          legend ("original", "linear", "spline", "cubic", "nearest")

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

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

   A simplified version of `interp1' that performs only linear
interpolation is available in `interp1q'.  This argument is slightly
faster than `interp1' as to performs little error checking.

 -- Function File: YI = interp1q (X, Y, XI)
     One-dimensional linear interpolation without error checking.
     Interpolates Y, defined at the points X, at the points XI.  The
     sample points X must be a strictly monotonically increasing column
     vector.  If Y is an array, treat the columns of Y separately.  If
     Y is a vector, it must be a column vector of the same length as X.

     Values of XI beyond the endpoints of the interpolation result in
     NA being returned.

     Note that the error checking is only a significant portion of the
     execution time of this `interp1' if the size of the input arguments
     is relatively small.  Therefore, the benefit of using `interp1q'
     is relatively small.

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

   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 an
     array, then operate along each column of the array separately.  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 end points of the interpolation.

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

   There are two significant limitations on Fourier interpolation.
Firstly, the function signal is assumed to be periodic, and so
non-periodic signals will be poorly represented at the edges.
Secondly, 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 additional the support function `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 Y at points X.  If called
     with two arguments, `spline' returns the piece-wise polynomial PP
     that may later be used with `ppval' to evaluate the polynomial at
     specific points.  If called with a third input argument, `spline'
     evaluates the spline at the points XI.  There is an equivalence
     between `ppval (spline (X, Y), XI)' and `spline (X, Y, XI)'.

     The variable X must be a vector of length N, and Y can be either a
     vector or array.  In the case where Y is a vector, it can 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 end-points.

     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 then
     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 the opposite
     treatment than `interp1' and is done for compatibility.

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

   The `lookup' function is used by other interpolation functions to
identify the points of the original data that are closest to the
current point of interest.

 -- Loadable Function: IDX = lookup (TABLE, Y, OPT)
     Lookup values in a sorted table.  Usually used as a prelude to
     interpolation.

     If table is strictly increasing and `idx = lookup (table, y)', then
     `table(idx(i)) <= y(i) < table(idx(i+1))' for all `y(i)' within
     the table.  If `y(i) < table (1)' then `idx(i)' is 0. If `y(i) >=
     table(end)' then `idx(i)' is `table(n)'.

     If the table is strictly decreasing, then the tests are reversed.
     There are no guarantees for tables which are non-monotonic or are
     not strictly monotonic.

     The algorithm used by lookup is standard binary search, with
     optimizations to speed up the case of partially ordered arrays
     (dense downsampling).  In particular, looking up a single entry is
     of logarithmic complexity (unless a conversion occurs due to
     non-numeric or unequal types).

     TABLE and Y can also be cell arrays of strings (or Y can be a
     single string).  In this case, string lookup is performed using
     lexicographical comparison.

     If OPTS is specified, it shall be a string with letters indicating
     additional options.  For numeric lookup, 'l' in OPTS indicates that
     the leftmost subinterval shall be extended to infinity (i.e., all
     indices at least 1), and 'r' indicates that the rightmost
     subinterval shall be extended to infinity (i.e., all indices at
     most n-1).

     For string lookup, 'i' indicates case-insensitive comparison.


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

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

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

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

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

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

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

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

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

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'pchip'
          Piece-wise cubic hermite interpolating polynomial (not
          implemented yet).

    'cubic'
          Cubic interpolation from four nearest neighbors.

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

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

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

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

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

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

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

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

     The default method is 'linear'.

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

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

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

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

     Method is one of:

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

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

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

     The default method is 'linear'.

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

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

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

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

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

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

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

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

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


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

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

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

* Menu:

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

* Menu:

* Plotting the Triangulation::
* Identifying points in Triangulation::


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

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

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

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

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

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

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

   The difference between `triplot' and `trimesh' is that the former
only plots the 2-dimensional triangulation itself, whereas the second
plots the value of some 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);

   that plot the Delaunay triangulation of a set of random points in
2-dimensions.


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

29.1.2 Identifying points in Triangulation
------------------------------------------

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

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

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

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

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

is imposed, and we can therefore write the above as

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

Solving for BETA we can then write

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

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

     0 <= BETA(I) <= 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File: IDX = dsearchn (X, TRI, XI)
 -- Function File: IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- Function File: IDX = dsearchn (X, XI)
 -- Function File: [IDX, D] = dsearchn (...)
     Returns 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 simplicies TRI are set to OUTVAL.
     Generally, TRI is returned from `delaunayn (X)'.

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

   An example of the use of `voronoi' is

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

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

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

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


   An example of the use of `polyarea' might be

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

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

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

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

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

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


   An example of the use of `inpolygon' might be

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


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

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

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

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

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

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

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

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

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

   An example of the use of `convhull' is

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


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

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

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

 -- Function File: ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- Function File: [XI, YI, ZI] = griddata (X, Y, Z, XI, YI, METHOD)
     Generate a regular mesh from irregular data using interpolation.
     The function is defined by `Z = f (X, Y)'.  The interpolation
     points are all `(XI, YI)'.  If XI, YI are vectors then they are
     made into a 2D mesh.

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

 -- Loadable Function:  fft (A, N, DIM)
     Compute the FFT of A using subroutines from FFTW.  The FFT is
     calculated along the first non-singleton dimension of the array.
     Thus if A is a matrix, `fft (A)' computes the FFT for each column
     of A.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of A 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 A is resized
     and padded with zeros.  Otherwise, if N is smaller than the
     dimension along which the FFT is calculated, then A is truncated.

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

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

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

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

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

          WISDOM = fftw ('dwisdom')

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

          fftw ('dwisdom', WISDOM)

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

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

    'estimate'
          This 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'
          This is like 'measure', but a wider range of algorithms is
          considered.

    'exhaustive'
          This is 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', and the method currently being
     used can be probed with

          METHOD = fftw ('planner')

     and the method used can be set using

          fftw ('planner', METHOD)

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

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

 -- Loadable Function:  ifft (A, N, DIM)
     Compute the inverse FFT of A using subroutines from FFTW.  The
     inverse FFT is calculated along the first non-singleton dimension
     of the array.  Thus if A is a matrix, `fft (A)' computes the
     inverse FFT for each column of A.

     If called with two arguments, N is expected to be an integer
     specifying the number of elements of A 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 A is
     resized and padded with zeros.  Otherwise, ifN is smaller than the
     dimension along which the inverse FFT is calculated, then A is
     truncated.

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

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

 -- Loadable Function:  fft2 (A, N, M)
     Compute the two-dimensional FFT of A using subroutines from FFTW.
     The optional arguments N and M may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

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

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

 -- Loadable Function:  fft2 (A, N, M)
     Compute the inverse two-dimensional FFT of A using subroutines from
     FFTW.  The optional arguments N and M may be used specify the
     number of rows and columns of A to use.  If either of these is
     larger than the size of A, A is resized and padded with zeros.

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

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

 -- Loadable Function:  fftn (A, SIZE)
     Compute the N-dimensional FFT of A using subroutines from FFTW.
     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, then the dimension is
     truncated prior to performing the FFT.  Otherwise if an element of
     SIZE is larger than the corresponding dimension A is resized and
     padded with zeros.

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

 -- Loadable Function:  ifftn (A, SIZE)
     Compute the inverse N-dimensional FFT of A using subroutines from
     FFTW.  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, then the dimension is
     truncated prior to performing the inverse FFT.  Otherwise if an
     element of SIZE is larger than the corresponding dimension A is
     resized and padded with zeros.

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

 -- Function File:  fftconv (A, B, N)
     Return the convolution of the vectors A and B, as a vector with
     length equal to the `length (a) + length (b) - 1'.  If A and B 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.

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

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

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

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

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

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

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

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

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

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

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

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

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

    'same'
          unpadded X (default)

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

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

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

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

     The output value W is a vector of the frequencies.

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

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

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

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

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

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

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

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

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

 -- Function File: B = unwrap (A, 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 unwrap along the first non-singleton dimension of A,
     unless the optional argument DIM is given, in which case the data
     will be unwrapped along this 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:  autocor (X, H)
     Return the autocorrelations from lag 0 to H of vector X.  If H is
     omitted, all autocorrelations are computed.  If X is a matrix, the
     autocorrelations of each column are computed.

 -- Function File:  autocov (X, H)
     Return the autocovariances from lag 0 to H of vector X.  If H is
     omitted, all autocovariances are computed.  If X is a matrix, the
     autocovariances of each column are computed.

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

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

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

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

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

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

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

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

     Reference: Brockwell, Peter J. & Davis, Richard A. 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 (V)
 -- Function File:  fftshift (V, DIM)
     Perform a shift of the vector V, for use with the `fft' and `ifft'
     functions, in order the move the frequency 0 to the center of the
     vector or matrix.

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

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

     If V is a matrix, the same holds for rows and columns.  If V 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 (V)
 -- Function File:  ifftshift (V, DIM)
     Undo the action of the `fftshift' function.  For even length V,
     `fftshift' is its own inverse, but odd lengths differ slightly.

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

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

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

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

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

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

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

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

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

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

 -- Function File:  periodogram (X)
     For a data matrix X from a sample of size N, return the
     periodogram.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    hanning
          w_type = 1

    hamming
          w_type = 2

    rectangle
          w_type = 3

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

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

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

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

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

     The values Y and C can be derived by

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

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

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

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

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


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

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

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

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

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

* Menu:

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


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

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

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

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

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

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

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

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

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

     If FMT is missing, the file extension (if any) of FILENAME is used
     to determine the format.

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

    `Quality'
          Sets the quality of the compression.  The corresponding value
          should be an integer between 0 and 100, with larger values
          meaning higher visual quality and less compression.

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

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

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

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

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

    `Filename'
          The full name of the image file.

    `FileSize'
          Number of bytes of the image on disk

    `FileModDate'
          Date of last modification to the file.

    `Height'
          Image height in pixels.

    `Width'
          Image Width in pixels.

    `BitDepth'
          Number of bits per channel per pixel.

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

    `LongFormat'
          Long form image format description.

    `XResolution'
          X resolution of the image.

    `YResolution'
          Y resolution of the image.

    `TotalColors'
          Number of unique colors in the image.

    `TileName'
          Tile name.

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

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

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

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

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

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

    `Quality'
          JPEG/MIFF/PNG compression level.

    `QuantizeColors'
          Preferred number of colors in the image.

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

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

    `View'
          FlashPix viewing parameters.

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


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

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

A natural part of image processing is visualization of an image.  The
most basic function for this is the `imshow' function that shows the
image given in the first input argument.  This function uses an
external program to show the image.  If gnuplot 4.2 or later is
available it will be used to display the image, otherwise the
`display', `xv', or `xloadimage' program is used.  The actual program
can be selected with the `image_viewer' function.

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

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

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

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

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

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

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

     It first tries to use `gnuplot', then `display' from
     `ImageMagick', then `xv', and then `xloadimage'.  The actual
     program used can be changed using the `image_viewer' function.

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

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

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

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

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

 -- Function File: [FCN, DEFAULT_ZOOM] = image_viewer (FCN,
          DEFAULT_ZOOM)
     Change the program or function used for viewing images and return
     the previous values.

     When the `image' or `imshow' function is called it will launch an
     external program to display the image.  The default behavior is to
     use gnuplot if the installed version supports image viewing, and
     otherwise try the programs `display', `xv', and `xloadimage'.
     Using this function it is possible to change that behavior.

     When called with one input argument images will be displayed by
     saving the image to a file and the system command COMMAND will be
     called to view the image.  The COMMAND must be a string containing
     `%s' and possibly `%f'.  The `%s' will be replaced by the filename
     of the image, and the `%f' will (if present) be replaced by the
     zoom factor given to the `image' function.  For example,
          image_viewer ("eog %s");
     changes the image viewer to the `eog' program.

     With two input arguments, images will be displayed by calling the
     function FUNCTION_HANDLE.  For example,
          image_viewer (data, @my_image_viewer);
     sets the image viewer function to `my_image_viewer'.  The image
     viewer function is called with
          my_image_viewer (X, Y, IM, ZOOM, DATA)
     where X and Y are the axis of the image, IM is the image variable,
     and DATA is extra user-supplied data to be passed to the viewer
     function.

     With three input arguments it is possible to change the zooming.
     Some programs (like `xloadimage') require the zoom factor to be
     between 0 and 100, and not 0 and 1 like Octave assumes.  This is
     solved by setting the third argument to 100.

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File:  autumn (N)
     Create color colormap.  This colormap is red through orange to
     yellow.  The argument N should be a scalar.  If it is omitted, the
     length of the current colormap or 64 is assumed.

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

 -- Function File:  bone (N)
     Create color colormap.  This colormap is a gray colormap with a
     light blue tone.  The argument N should be a scalar.  If it is
     omitted, the length of the current colormap or 64 is assumed.

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

 -- Function File:  cool (N)
     Create color colormap.  The colormap is cyan to magenta.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

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

 -- Function File:  copper (N)
     Create color colormap.  This colormap is black to a light copper
     tone.  The argument N should be a scalar.  If it is omitted, the
     length of the current colormap or 64 is assumed.

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

 -- Function File:  flag (N)
     Create color colormap.  This colormap cycles through red, white,
     blue and black.  The argument N should be a scalar.  If it is
     omitted, the length of the current colormap or 64 is assumed.

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

 -- Function File:  gray (N)
     Return a gray colormap with N entries corresponding to values from
     0 to N-1.  The argument N should be a scalar.  If it is omitted,
     the length of the current colormap or 64 is assumed.

 -- Function File:  hot (N)
     Create color colormap.  This colormap is black through dark red,
     red, orange, yellow to white.  The argument N should be a scalar.
     If it is omitted, the length of the current colormap or 64 is
     assumed.

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

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

     The argument N should be a scalar.  If it is omitted, the length
     of the current colormap or 64 is assumed.

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

 -- Function File:  jet (N)
     Create color colormap.  This colormap is dark blue through blue,
     cyan, green, yellow, red to dark red.  The argument N should be a
     scalar.  If it is omitted, the length of the current colormap or
     64 is assumed.

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

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

 -- Function File:  pink (N)
     Create color colormap.  This colormap gives a sepia tone on black
     and white images.  The argument N should be a scalar.  If it is
     omitted, the length of the current colormap or 64 is assumed.

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

 -- Function File:  prism (N)
     Create color colormap.  This colormap cycles trough red, orange,
     yellow, green, blue and violet.  The argument N should be a
     scalar.  If it is omitted, the length of the current colormap or
     64 is assumed.

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

 -- Function File:  rainbow (N)
     Create color colormap.  This colormap is red through orange,
     yellow, green, blue to violet.  The argument N should be a scalar.
     If it is omitted, the length of the current colormap or 64 is
     assumed.

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

 -- Function File:  spring (N)
     Create color colormap.  This colormap is magenta to yellow.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

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

 -- Function File:  summer (N)
     Create color colormap.  This colormap is green to yellow.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

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

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

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

 -- Function File:  winter (N)
     Create color colormap.  This colormap is blue to green.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

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

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

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

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

 -- Function File:  gmap40 (N)
     Create a color colormap.  The colormap is red, green, blue, yellow,
     magenta and cyan.  These are the colors that are allowed with patch
     objects using gnuplot 4.0, and so this colormap function is
     specially designed for users of gnuplot 4.0.  The argument N
     should be a scalar.  If it is omitted, a length of 6 is assumed.
     Larger values of N result in a repetition of the above colors

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

   You may use the `spinmap' function to cycle through the colors in
the current colormap, displaying the changes for the current figure.

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

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

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


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

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

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

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


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

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

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

 -- Function File: HSV_MAP = rgb2hsv (RGB_MAP)
     Transform a colormap or image from the rgb space to the hsv space.

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

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

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

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

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

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

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

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

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


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

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

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

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

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

 -- Function File:  lin2mu (X, N)
     Converts 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
     values in X.

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

 -- Function File:  mu2lin (X, BPS)
     Converts audio data from linear to mu-law.  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 8.

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File:  setaudio ([W_TYPE [, VALUE]])
     Execute the shell command `mixer [W_TYPE [, VALUE]]'

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

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

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

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

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

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

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

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


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

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

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

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

* Menu:

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


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

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

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

   The polynomial class is used to represent polynomials of the form

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

For example

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


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

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

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

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

          myclass (...)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   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 for
example like

     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 = myclass (struct ("a", a), "myclass");
          endfunction

     then the `subsindex' function

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

     can then be used as follows

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

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

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

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

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

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


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

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

* Menu:

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


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

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

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

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

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

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

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

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

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


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

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

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

Table 33.1: Available overloaded operators and their corresponding
class method

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

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


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

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

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

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

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

   For example with our polynomial class consider the case

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

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

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

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

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


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

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

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

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

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

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

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

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

     function f = FIRfilter (p)

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

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

   Note further that all our examples provide for the case in which no
arguments are supplied.  This is important since octave will call the
constructor with no arguments when loading ojects 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 writeable.

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

   So that

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

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

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

     function f = FIRfilter (p)

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

   For our example, the remaining class methods remain unchanged.


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

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

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

* Menu:

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


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

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

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

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

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

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

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

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

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

`year'
     Years since 1900.

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

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

`isdst'
     Daylight Savings Time flag.

`zone'
     Time zone.

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Loadable Function:  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
                     year = 97
                     mon = 1
                     mday = 17
                     sec = 6
                     zone = CST
                     min = 15
                     wday = 1
                     hour = 1
                     isdst = 0
                     yday = 47
                   }

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

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

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

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

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

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

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

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

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

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

     Literal character fields:

    `%'
          % character.

    `n'
          Newline character.

    `t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

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

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

     Time fields:

    `%H'
          Hour (00-23).

    `%I'
          Hour (01-12).

    `%k'
          Hour (0-23).

    `%l'
          Hour (1-12).

    `%M'
          Minute (00-59).

    `%p'
          Locale's AM or PM.

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

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

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

    `%S'
          Second (00-61).

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

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

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

     Date fields:

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

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

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

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

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

    `%C'
          Century (00-99).

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

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

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

    `%h'
          Same as %b.

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

    `%m'
          Month (01-12).

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

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

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

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

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

    `%Y'
          Year (1970-).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          is_leap_year (2000)
               => 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     Notes:

        * Years can be negative and/or fractional.

        * Months below 1 are considered to be January.

        * Days of the month start at 1.

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

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

        * Days can be fractional.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     D is a serial date number or a date string.

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

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

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

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

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

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

