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

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

Copyright © 1996-2023 The Octave Project Developers

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

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

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


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

24 Differential Equations
*************************

Octave has built-in functions for solving ordinary differential
equations (ODEs), and differential-algebraic equations (DAEs).

* Menu:

* Ordinary Differential Equations::
* Differential-Algebraic Equations::
* Matlab-compatible solvers::


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

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

 -- : [X, ISTATE, MSG] = lsode (FCN, X_0, T)
 -- : [X, ISTATE, MSG] = lsode (FCN, X_0, T, T_CRIT)
     Ordinary Differential Equation (ODE) solver.

     The set of differential equations to solve is

          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_M  df_M       df_M |
                       | ----  ----  ...  ---- |
                       | dx_1  dx_2       dx_N |

     The second argument specifies the initial state of the system x_0.
     The third argument is a vector, T, specifying the time values for
     which a solution is sought.

     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 Alan C. Hindmarsh, ‘ODEPACK, A Systematized Collection of ODE
     Solvers’, in Scientific Computing, R. S. Stepleman, editor, (1983)
     or <https://computing.llnl.gov/projects/odepack> for more
     information about the inner workings of ‘lsode’.

     Example: Solve the Van der Pol equation

          fvdp = @(Y,T) [Y(2); (1 - Y(1)^2) * Y(2) - Y(1)];
          T = linspace (0, 20, 100);
          Y = lsode (fvdp, [2; 0], T);

     See also: *note daspk: XREFdaspk, *note dassl: XREFdassl, *note
     dasrt: XREFdasrt.

 -- : lsode_options ()
 -- : val = lsode_options (OPT)
 -- : lsode_options (OPT, VAL)
     Query or set options for the function ‘lsode’.

     When called with no arguments, the names of all available options
     and their current values are displayed.

     Given one argument, return the value of the option OPT.

     When called with two arguments, ‘lsode_options’ sets the option OPT
     to value VAL.

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

     "jacobian type"
          A string specifying the type of Jacobian used with the stiff
          backward differentiation formula (BDF) integration method.
          Valid values are

          "full"
               The default.  All partial derivatives are approximated or
               used from the user-supplied Jacobian function.

          "banded"
               Only the diagonal and the number of lower and upper
               subdiagonals specified by the options "lower jacobian
               subdiagonals" and "upper jacobian subdiagonals",
               respectively, are approximated or used from the
               user-supplied Jacobian function.  A user-supplied
               Jacobian function may set all other partial derivatives
               to arbitrary values.

          "diagonal"
               If a Jacobian function is supplied by the user, this
               setting has no effect.  A Jacobian approximated by
               ‘lsode’ is restricted to the diagonal, where each partial
               derivative is computed by applying a finite change to all
               elements of the state together; if the real Jacobian is
               indeed always diagonal, this has the same effect as
               applying the finite change only to the respective element
               of the state, but is more efficient.

     "lower jacobian subdiagonals"
          Number of lower subdiagonals used if option "jacobian type" is
          set to "banded".  The default is zero.

     "upper jacobian subdiagonals"
          Number of upper subdiagonals used if option "jacobian type" is
          set to "banded".  The default is zero.

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

     ## oregonator differential equation
     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)];

   An m-file for the differential equation used above is included with
the Octave distribution in the examples directory under the name
‘oregonator.m’.


File: octave.info,  Node: Differential-Algebraic Equations,  Next: Matlab-compatible solvers,  Prev: Ordinary Differential Equations,  Up: Differential Equations

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

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

     ‘daspk’ solves the set of 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: XREFdassl.

 -- : daspk_options ()
 -- : val = daspk_options (OPT)
 -- : daspk_options (OPT, VAL)
     Query or set options for the function ‘daspk’.

     When called with no arguments, the names of all available options
     and their current values are displayed.

     Given one argument, return the value of the option OPT.

     When called with two arguments, ‘daspk_options’ sets the option OPT
     to value VAL.

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

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

     ‘dassl’ solves the set of 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: XREFdaspk, *note dasrt: XREFdasrt, *note
     lsode: XREFlsode.

 -- : dassl_options ()
 -- : val = dassl_options (OPT)
 -- : dassl_options (OPT, VAL)
     Query or set options for the function ‘dassl’.

     When called with no arguments, the names of all available options
     and their current values are displayed.

     Given one argument, return the value of the option OPT.

     When called with two arguments, ‘dassl_options’ sets the option OPT
     to value VAL.

     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 non-negative, 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.

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

     ‘dasrt’ solves the set of 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 round-off 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 dasrt_options: XREFdasrt_options, *note daspk:
     XREFdaspk, *note dasrt: XREFdasrt, *note lsode: XREFlsode.

 -- : dasrt_options ()
 -- : val = dasrt_options (OPT)
 -- : dasrt_options (OPT, VAL)
     Query or set options for the function ‘dasrt’.

     When called with no arguments, the names of all available options
     and their current values are displayed.

     Given one argument, return the value of the option OPT.

     When called with two arguments, ‘dasrt_options’ sets the option OPT
     to value VAL.

     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),
DOI: <https://doi.org/10.1137/1.9781611971224>, for more information
about the implementation of DASSL.


File: octave.info,  Node: Matlab-compatible solvers,  Prev: Differential-Algebraic Equations,  Up: Differential Equations

24.3 Matlab-compatible solvers
==============================

Octave also provides a set of solvers for initial value problems for
ordinary differential equations (ODEs) that have a MATLAB-compatible
interface.  The options for this class of methods are set using the
functions.

   • *note odeset: XREFodeset.

   • *note odeget: XREFodeget.

   Currently implemented solvers are:

   • Runge-Kutta methods

        • *note ode45: XREFode45. integrates a system of non-stiff ODEs
          or index-1 differential-algebraic equations (DAEs) using the
          high-order, variable-step Dormand-Prince method.  It requires
          six function evaluations per integration step, but may take
          larger steps on smooth problems than ‘ode23’: potentially
          offering improved efficiency at smaller tolerances.

        • *note ode23: XREFode23. integrates a system of non-stiff ODEs
          or (or index-1 DAEs).  It uses the third-order
          Bogacki-Shampine method and adapts the local step size in
          order to satisfy a user-specified tolerance.  The solver
          requires three function evaluations per integration step.

        • *note ode23s: XREFode23s. integrates a system of stiff ODEs
          (or index-1 DAEs) using a modified second-order Rosenbrock
          method.

   • Linear multistep methods

        • *note ode15s: XREFode15s. integrates a system of stiff ODEs
          (or index-1 DAEs) using a variable step, variable order method
          based on Backward Difference Formulas (BDF).

        • *note ode15i: XREFode15i. integrates a system of
          fully-implicit ODEs (or index-1 DAEs) using the same variable
          step, variable order method as ‘ode15s’.  *note decic:
          XREFdecic. can be used to compute consistent initial
          conditions for ‘ode15i’.

   Detailed information on the solvers are given in L. F. Shampine and
M.  W. Reichelt, ‘The MATLAB ODE Suite’, SIAM Journal on Scientific
Computing, Vol.  18, 1997, pp.  1–22, DOI:
<https://doi.org/10.1137/S1064827594276424>.

 -- : [T, Y] = ode45 (FCN, TRANGE, INIT)
 -- : [T, Y] = ode45 (FCN, TRANGE, INIT, ODE_OPT)
 -- : [T, Y, TE, YE, IE] = ode45 (...)
 -- : SOLUTION = ode45 (...)
 -- : ode45 (...)

     Solve a set of non-stiff Ordinary Differential Equations (non-stiff
     ODEs) with the well known explicit Dormand-Prince method of order
     4.

     FCN is a function handle, inline function, or string containing the
     name of the function that defines the ODE: ‘y' = f(t,y)’.  The
     function must accept two inputs where the first is time T and the
     second is a column vector of unknowns Y.

     TRANGE specifies the time interval over which the ODE will be
     evaluated.  Typically, it is a two-element vector specifying the
     initial and final times (‘[tinit, tfinal]’).  If there are more
     than two elements then the solution will also be evaluated at these
     intermediate time instances.

     By default, ‘ode45’ uses an adaptive timestep with the
     ‘integrate_adaptive’ algorithm.  The tolerance for the timestep
     computation may be changed by using the options "RelTol" and
     "AbsTol".

     INIT contains the initial value for the unknowns.  If it is a row
     vector then the solution Y will be a matrix in which each column is
     the solution for the corresponding initial value in INIT.

     The optional fourth argument ODE_OPT specifies non-default options
     to the ODE solver.  It is a structure generated by ‘odeset’.

     The function typically returns two outputs.  Variable T is a column
     vector and contains the times where the solution was found.  The
     output Y is a matrix in which each column refers to a different
     unknown of the problem and each row corresponds to a time in T.

     The output can also be returned as a structure SOLUTION which has a
     field X containing a row vector of times where the solution was
     evaluated and a field Y containing the solution matrix such that
     each column corresponds to a time in X.  Use
     ‘fieldnames (SOLUTION)’ to see the other fields and additional
     information returned.

     If no output arguments are requested, and no "OutputFcn" is
     specified in ODE_OPT, then the "OutputFcn" is set to ‘odeplot’ and
     the results of the solver are plotted immediately.

     If using the "Events" option then three additional outputs may be
     returned.  TE holds the time when an Event function returned a
     zero.  YE holds the value of the solution at time TE.  IE contains
     an index indicating which Event function was triggered in the case
     of multiple Event functions.

     Example: Solve the Van der Pol equation

          fvdp = @(T,Y) [Y(2); (1 - Y(1)^2) * Y(2) - Y(1)];
          [T,Y] = ode45 (fvdp, [0, 20], [2, 0]);

     See also: *note odeset: XREFodeset, *note odeget: XREFodeget, *note
     ode23: XREFode23, *note ode15s: XREFode15s.

 -- : [T, Y] = ode23 (FCN, TRANGE, INIT)
 -- : [T, Y] = ode23 (FCN, TRANGE, INIT, ODE_OPT)
 -- : [T, Y, TE, YE, IE] = ode23 (...)
 -- : SOLUTION = ode23 (...)
 -- : ode23 (...)

     Solve a set of non-stiff Ordinary Differential Equations (non-stiff
     ODEs) with the well known explicit Bogacki-Shampine method of order
     3.

     FCN is a function handle, inline function, or string containing the
     name of the function that defines the ODE: ‘y' = f(t,y)’.  The
     function must accept two inputs where the first is time T and the
     second is a column vector of unknowns Y.

     TRANGE specifies the time interval over which the ODE will be
     evaluated.  Typically, it is a two-element vector specifying the
     initial and final times (‘[tinit, tfinal]’).  If there are more
     than two elements then the solution will also be evaluated at these
     intermediate time instances.

     By default, ‘ode23’ uses an adaptive timestep with the
     ‘integrate_adaptive’ algorithm.  The tolerance for the timestep
     computation may be changed by using the options "RelTol" and
     "AbsTol".

     INIT contains the initial value for the unknowns.  If it is a row
     vector then the solution Y will be a matrix in which each column is
     the solution for the corresponding initial value in INIT.

     The optional fourth argument ODE_OPT specifies non-default options
     to the ODE solver.  It is a structure generated by ‘odeset’.

     The function typically returns two outputs.  Variable T is a column
     vector and contains the times where the solution was found.  The
     output Y is a matrix in which each column refers to a different
     unknown of the problem and each row corresponds to a time in T.

     The output can also be returned as a structure SOLUTION which has a
     field X containing a row vector of times where the solution was
     evaluated and a field Y containing the solution matrix such that
     each column corresponds to a time in X.  Use
     ‘fieldnames (SOLUTION)’ to see the other fields and additional
     information returned.

     If no output arguments are requested, and no "OutputFcn" is
     specified in ODE_OPT, then the "OutputFcn" is set to ‘odeplot’ and
     the results of the solver are plotted immediately.

     If using the "Events" option then three additional outputs may be
     returned.  TE holds the time when an Event function returned a
     zero.  YE holds the value of the solution at time TE.  IE contains
     an index indicating which Event function was triggered in the case
     of multiple Event functions.

     Example: Solve the Van der Pol equation

          fvdp = @(T,Y) [Y(2); (1 - Y(1)^2) * Y(2) - Y(1)];
          [T,Y] = ode23 (fvdp, [0, 20], [2, 0]);

     Reference: For the definition of this method see
     <https://en.wikipedia.org/wiki/List_of_Runge%E2%80%93Kutta_methods>.

     See also: *note odeset: XREFodeset, *note odeget: XREFodeget, *note
     ode45: XREFode45, *note ode15s: XREFode15s.

 -- : [T, Y] = ode23s (FCN, TRANGE, INIT)
 -- : [T, Y] = ode23s (FCN, TRANGE, INIT, ODE_OPT)
 -- : [T, Y] = ode23s (..., PAR1, PAR2, ...)
 -- : [T, Y, TE, YE, IE] = ode23s (...)
 -- : SOLUTION = ode23s (...)

     Solve a set of stiff Ordinary Differential Equations (stiff ODEs)
     with a Rosenbrock method of order (2,3).

     FCN is a function handle, inline function, or string containing the
     name of the function that defines the ODE: ‘M y' = f(t,y)’.  The
     function must accept two inputs where the first is time T and the
     second is a column vector of unknowns Y.  M is a constant mass
     matrix, non-singular and possibly sparse.  Set the field "Mass" in
     ODEOPTS using ODESET to specify a mass matrix.

     TRANGE specifies the time interval over which the ODE will be
     evaluated.  Typically, it is a two-element vector specifying the
     initial and final times (‘[tinit, tfinal]’).  If there are more
     than two elements then the solution will also be evaluated at these
     intermediate time instances using an interpolation procedure of the
     same order as the one of the solver.

     By default, ‘ode23s’ uses an adaptive timestep with the
     ‘integrate_adaptive’ algorithm.  The tolerance for the timestep
     computation may be changed by using the options "RelTol" and
     "AbsTol".

     INIT contains the initial value for the unknowns.  If it is a row
     vector then the solution Y will be a matrix in which each column is
     the solution for the corresponding initial value in INIT.

     The optional fourth argument ODE_OPT specifies non-default options
     to the ODE solver.  It is a structure generated by ‘odeset’.
     ‘ode23s’ will ignore the following options: "BDF", "InitialSlope",
     "MassSingular", "MStateDependence", "MvPattern", "MaxOrder",
     "Non-negative".

     The function typically returns two outputs.  Variable T is a column
     vector and contains the times where the solution was found.  The
     output Y is a matrix in which each column refers to a different
     unknown of the problem and each row corresponds to a time in T.  If
     TRANGE specifies intermediate time steps, only those will be
     returned.

     The output can also be returned as a structure SOLUTION which has a
     field X containing a row vector of times where the solution was
     evaluated and a field Y containing the solution matrix such that
     each column corresponds to a time in X.  Use
     ‘fieldnames (SOLUTION)’ to see the other fields and additional
     information returned.

     If using the "Events" option then three additional outputs may be
     returned.  TE holds the time when an Event function returned a
     zero.  YE holds the value of the solution at time TE.  IE contains
     an index indicating which Event function was triggered in the case
     of multiple Event functions.

     Example: Solve the stiff Van der Pol equation

          f = @(T,Y) [Y(2); 1000*(1 - Y(1)^2) * Y(2) - Y(1)];
          opt = odeset ('Mass', [1 0; 0 1], 'MaxStep', 1e-1);
          [vt, vy] = ode23s (f, [0 2000], [2 0], opt);

     See also: *note odeset: XREFodeset, *note daspk: XREFdaspk, *note
     dassl: XREFdassl.

 -- : [T, Y] = ode15s (FCN, TRANGE, Y0)
 -- : [T, Y] = ode15s (FCN, TRANGE, Y0, ODE_OPT)
 -- : [T, Y, TE, YE, IE] = ode15s (...)
 -- : SOLUTION = ode15s (...)
 -- : ode15s (...)
     Solve a set of stiff Ordinary Differential Equations (ODEs) or
     stiff semi-explicit index 1 Differential Algebraic Equations
     (DAEs).

     ‘ode15s’ uses a variable step, variable order BDF (Backward
     Differentiation Formula) method that ranges from order 1 to 5.

     FCN is a function handle, inline function, or string containing the
     name of the function that defines the ODE: ‘y' = f(t,y)’.  The
     function must accept two inputs where the first is time T and the
     second is a column vector of unknowns Y.

     TRANGE specifies the time interval over which the ODE will be
     evaluated.  Typically, it is a two-element vector specifying the
     initial and final times (‘[tinit, tfinal]’).  If there are more
     than two elements then the solution will also be evaluated at these
     intermediate time instances.

     INIT contains the initial value for the unknowns.  If it is a row
     vector then the solution Y will be a matrix in which each column is
     the solution for the corresponding initial value in INIT.

     The optional fourth argument ODE_OPT specifies non-default options
     to the ODE solver.  It is a structure generated by ‘odeset’.

     The function typically returns two outputs.  Variable T is a column
     vector and contains the times where the solution was found.  The
     output Y is a matrix in which each column refers to a different
     unknown of the problem and each row corresponds to a time in T.

     The output can also be returned as a structure SOLUTION which has a
     field X containing a row vector of times where the solution was
     evaluated and a field Y containing the solution matrix such that
     each column corresponds to a time in X.  Use
     ‘fieldnames (SOLUTION)’ to see the other fields and additional
     information returned.

     If no output arguments are requested, and no "OutputFcn" is
     specified in ODE_OPT, then the "OutputFcn" is set to ‘odeplot’ and
     the results of the solver are plotted immediately.

     If using the "Events" option then three additional outputs may be
     returned.  TE holds the time when an Event function returned a
     zero.  YE holds the value of the solution at time TE.  IE contains
     an index indicating which Event function was triggered in the case
     of multiple Event functions.

     Example: Solve Robertson's equations:

          function r = robertson_dae (T, Y)
            r = [ -0.04*Y(1) + 1e4*Y(2)*Y(3)
                   0.04*Y(1) - 1e4*Y(2)*Y(3) - 3e7*Y(2)^2
          Y(1) + Y(2) + Y(3) - 1 ];
          endfunction
          opt = odeset ("Mass", [1 0 0; 0 1 0; 0 0 0], "MStateDependence", "none");
          [T,Y] = ode15s (@robertson_dae, [0, 1e3], [1; 0; 0], opt);

     See also: *note decic: XREFdecic, *note odeset: XREFodeset, *note
     odeget: XREFodeget, *note ode23: XREFode23, *note ode45: XREFode45.

 -- : [T, Y] = ode15i (FCN, TRANGE, Y0, YP0)
 -- : [T, Y] = ode15i (FCN, TRANGE, Y0, YP0, ODE_OPT)
 -- : [T, Y, TE, YE, IE] = ode15i (...)
 -- : SOLUTION = ode15i (...)
 -- : ode15i (...)
     Solve a set of fully-implicit Ordinary Differential Equations
     (ODEs) or index 1 Differential Algebraic Equations (DAEs).

     ‘ode15i’ uses a variable step, variable order BDF (Backward
     Differentiation Formula) method that ranges from order 1 to 5.

     FCN is a function handle, inline function, or string containing the
     name of the function that defines the ODE: ‘0 = f(t,y,yp)’.  The
     function must accept three inputs where the first is time T, the
     second is the function value Y (a column vector), and the third is
     the derivative value YP (a column vector).

     TRANGE specifies the time interval over which the ODE will be
     evaluated.  Typically, it is a two-element vector specifying the
     initial and final times (‘[tinit, tfinal]’).  If there are more
     than two elements then the solution will also be evaluated at these
     intermediate time instances.

     Y0 and YP0 contain the initial values for the unknowns Y and YP.
     If they are row vectors then the solution Y will be a matrix in
     which each column is the solution for the corresponding initial
     value in Y0 and YP0.

     Y0 and YP0 must be consistent initial conditions, meaning that
     ‘f(t,y0,yp0) = 0’ is satisfied.  The function ‘decic’ may be used
     to compute consistent initial conditions given initial guesses.

     The optional fifth argument ODE_OPT specifies non-default options
     to the ODE solver.  It is a structure generated by ‘odeset’.

     The function typically returns two outputs.  Variable T is a column
     vector and contains the times where the solution was found.  The
     output Y is a matrix in which each column refers to a different
     unknown of the problem and each row corresponds to a time in T.

     The output can also be returned as a structure SOLUTION which has a
     field X containing a row vector of times where the solution was
     evaluated and a field Y containing the solution matrix such that
     each column corresponds to a time in X.  Use
     ‘fieldnames (SOLUTION)’ to see the other fields and additional
     information returned.

     If no output arguments are requested, and no "OutputFcn" is
     specified in ODE_OPT, then the "OutputFcn" is set to ‘odeplot’ and
     the results of the solver are plotted immediately.

     If using the "Events" option then three additional outputs may be
     returned.  TE holds the time when an Event function returned a
     zero.  YE holds the value of the solution at time TE.  IE contains
     an index indicating which Event function was triggered in the case
     of multiple Event functions.

     Example: Solve Robertson's equations:

          function r = robertson_dae (T, Y, YP)
            r = [ -(YP(1) + 0.04*Y(1) - 1e4*Y(2)*Y(3))
                  -(YP(2) - 0.04*Y(1) + 1e4*Y(2)*Y(3) + 3e7*Y(2)^2)
          Y(1) + Y(2) + Y(3) - 1 ];
          endfunction
          [T,Y] = ode15i (@robertson_dae, [0, 1e3], [1; 0; 0], [-1e-4; 1e-4; 0]);

     See also: *note decic: XREFdecic, *note odeset: XREFodeset, *note
     odeget: XREFodeget.

 -- : [Y0_NEW, YP0_NEW] = decic (FCN, T0, Y0, FIXED_Y0, YP0, FIXED_YP0)
 -- : [Y0_NEW, YP0_NEW] = decic (FCN, T0, Y0, FIXED_Y0, YP0, FIXED_YP0,
          OPTIONS)
 -- : [Y0_NEW, YP0_NEW, RESNORM] = decic (...)

     Compute consistent implicit ODE initial conditions Y0_NEW and
     YP0_NEW given initial guesses Y0 and YP0.

     A maximum of ‘length (Y0)’ components between FIXED_Y0 and
     FIXED_YP0 may be chosen as fixed values.

     FCN is a function handle.  The function must accept three inputs
     where the first is time T, the second is a column vector of
     unknowns Y, and the third is a column vector of unknowns YP.

     T0 is the initial time such that ‘FCN(T0, Y0_NEW, YP0_NEW) = 0’,
     specified as a scalar.

     Y0 is a vector used as the initial guess for Y.

     FIXED_Y0 is a vector which specifies the components of Y0 to hold
     fixed.  Choose a maximum of ‘length (Y0)’ components between
     FIXED_Y0 and FIXED_YP0 as fixed values.  Set FIXED_Y0(i) component
     to 1 if you want to fix the value of Y0(i).  Set FIXED_Y0(i)
     component to 0 if you want to allow the value of Y0(i) to change.

     YP0 is a vector used as the initial guess for YP.

     FIXED_YP0 is a vector which specifies the components of YP0 to hold
     fixed.  Choose a maximum of ‘length (YP0)’ components between
     FIXED_Y0 and FIXED_YP0 as fixed values.  Set FIXED_YP0(i) component
     to 1 if you want to fix the value of YP0(i).  Set FIXED_YP0(i)
     component to 0 if you want to allow the value of YP0(i) to change.

     The optional seventh argument OPTIONS is a structure array.  Use
     ‘odeset’ to generate this structure.  The relevant options are
     ‘RelTol’ and ‘AbsTol’ which specify the error thresholds used to
     compute the initial conditions.

     The function typically returns two outputs.  Variable Y0_NEW is a
     column vector and contains the consistent initial value of Y.  The
     output YP0_NEW is a column vector and contains the consistent
     initial value of YP.

     The optional third output RESNORM is the norm of the vector of
     residuals.  If RESNORM is small, ‘decic’ has successfully computed
     the initial conditions.  If the value of RESNORM is large, use
     ‘RelTol’ and ‘AbsTol’ to adjust it.

     Example: Compute initial conditions for Robertson's equations:

          function r = robertson_dae (T, Y, YP)
            r = [ -(YP(1) + 0.04*Y(1) - 1e4*Y(2)*Y(3))
                  -(YP(2) - 0.04*Y(1) + 1e4*Y(2)*Y(3) + 3e7*Y(2)^2)
          Y(1) + Y(2) + Y(3) - 1 ];
          endfunction
          [Y0_NEW,YP0_NEW] = decic (@robertson_dae, 0, [1; 0; 0], [1; 1; 0],
          [-1e-4; 1; 0], [0; 0; 0]);

     See also: *note ode15i: XREFode15i, *note odeset: XREFodeset.

 -- : ODESTRUCT = odeset ()
 -- : ODESTRUCT = odeset ("FIELD1", VALUE1, "FIELD2", VALUE2, ...)
 -- : ODESTRUCT = odeset (OLDSTRUCT, "FIELD1", VALUE1, "FIELD2", VALUE2,
          ...)
 -- : ODESTRUCT = odeset (OLDSTRUCT, NEWSTRUCT)
 -- : odeset ()

     Create or modify an ODE options structure.

     When called with no input argument and one output argument, return
     a new ODE options structure that contains all possible fields
     initialized to their default values.  If no output argument is
     requested, display a list of the common ODE solver options along
     with their default value.

     If called with name-value input argument pairs "FIELD1", "VALUE1",
     "FIELD2", "VALUE2", ... return a new ODE options structure with all
     the most common option fields initialized, *and* set the values of
     the fields "FIELD1", "FIELD2", ... to the values VALUE1, VALUE2,
     ....

     If called with an input structure OLDSTRUCT then overwrite the
     values of the options "FIELD1", "FIELD2", ... with new values
     VALUE1, VALUE2, ... and return the modified structure.

     When called with two input ODE options structures OLDSTRUCT and
     NEWSTRUCT overwrite all values from the structure OLDSTRUCT with
     new values from the structure NEWSTRUCT.  Empty values in NEWSTRUCT
     will not overwrite values in OLDSTRUCT.

     The most commonly used ODE options, which are always assigned a
     value by ‘odeset’, are the following:

     ‘AbsTol’: positive scalar | vector, def. ‘1e-6’
          Absolute error tolerance.

     ‘BDF’: {"off"} | "on"
          Use BDF formulas in implicit multistep methods.  _Note_: This
          option is not yet implemented.

     ‘Events’: function_handle
          Event function.  An event function must have the form ‘[value,
          isterminal, direction] = my_events_f (t, y)’

     ‘InitialSlope’: vector
          Consistent initial slope vector for DAE solvers.

     ‘InitialStep’: positive scalar
          Initial time step size.

     ‘Jacobian’: matrix | function_handle
          Jacobian matrix, specified as a constant matrix or a function
          of time and state.

     ‘JConstant’: {"off"} | "on"
          Specify whether the Jacobian is a constant matrix or depends
          on the state.

     ‘JPattern’: sparse matrix
          If the Jacobian matrix is sparse and non-constant but
          maintains a constant sparsity pattern, specify the sparsity
          pattern.

     ‘Mass’: matrix | function_handle
          Mass matrix, specified as a constant matrix or a function of
          time and state.

     ‘MassSingular’: {"maybe"} | "yes" | "on"
          Specify whether the mass matrix is singular.

     ‘MaxOrder’: {5} | 4 | 3 | 2 | 1
          Maximum order of formula.

     ‘MaxStep’: positive scalar
          Maximum time step value.

     ‘MStateDependence’: {"weak"} | "none" | "strong"
          Specify whether the mass matrix depends on the state or only
          on time.

     ‘MvPattern’: sparse matrix
          If the mass matrix is sparse and non-constant but maintains a
          constant sparsity pattern, specify the sparsity pattern.
          _Note_: This option is not yet implemented.

     ‘NonNegative’: scalar | vector
          Specify elements of the state vector that are expected to
          remain non-negative during the simulation.

     ‘NormControl’: {"off"} | "on"
          Control error relative to the 2-norm of the solution, rather
          than its absolute value.

     ‘OutputFcn’: function_handle
          Function to monitor the state during the simulation.  For the
          form of the function to use *note ‘odeplot’: XREFodeplot.

     ‘OutputSel’: scalar | vector
          Indices of elements of the state vector to be passed to the
          output monitoring function.

     ‘Refine’: positive scalar
          Specify whether output should be returned only at the end of
          each time step or also at intermediate time instances.  The
          value should be a scalar indicating the number of equally
          spaced time points to use within each timestep at which to
          return output.

     ‘RelTol’: positive scalar
          Relative error tolerance.

     ‘Stats’: {"off"} | "on"
          Print solver statistics after simulation.

     ‘Vectorized’: {"off"} | "on"
          Specify whether ‘odefcn’ can be passed multiple values of the
          state at once.

     Field names that are not in the above list are also accepted and
     added to the result structure.

     See also: *note odeget: XREFodeget.

 -- : VAL = odeget (ODE_OPT, FIELD)
 -- : VAL = odeget (ODE_OPT, FIELD, DEFAULT)

     Query the value of the property FIELD in the ODE options structure
     ODE_OPT.

     If called with two input arguments and the first input argument
     ODE_OPT is an ODE option structure and the second input argument
     FIELD is a string specifying an option name, then return the option
     value VAL corresponding to FIELD from ODE_OPT.

     If called with an optional third input argument, and FIELD is not
     set in the structure ODE_OPT, then return the default value DEFAULT
     instead.

     See also: *note odeset: XREFodeset.

 -- : STOP_SOLVE = odeplot (T, Y, FLAG)

     Open a new figure window and plot the solution of an ode problem at
     each time step during the integration.

     The types and values of the input parameters T and Y depend on the
     input FLAG that is of type string.  Valid values of FLAG are:

     ‘"init"’
          The input T must be a column vector of length 2 with the first
          and last time step (‘[TFIRST TLAST]’.  The input Y contains
          the initial conditions for the ode problem (Y0).

     ‘""’
          The input T must be a scalar double or vector specifying the
          time(s) for which the solution in input Y was calculated.

     ‘"done"’
          The inputs should be empty, but are ignored if they are
          present.

     ‘odeplot’ always returns false, i.e., don't stop the ode solver.

     Example: solve an anonymous implementation of the "Van der Pol"
     equation and display the results while solving.

          fvdp = @(t,y) [y(2); (1 - y(1)^2) * y(2) - y(1)];

          opt = odeset ("OutputFcn", @odeplot, "RelTol", 1e-6);
          sol = ode45 (fvdp, [0 20], [2 0], opt);

     Background Information: This function is called by an ode solver
     function if it was specified in the "OutputFcn" property of an
     options structure created with ‘odeset’.  The ode solver will
     initially call the function with the syntax ‘odeplot ([TFIRST,
     TLAST], Y0, "init")’.  The function initializes internal variables,
     creates a new figure window, and sets the x limits of the plot.
     Subsequently, at each time step during the integration the ode
     solver calls ‘odeplot (T, Y, [])’.  At the end of the solution the
     ode solver calls ‘odeplot ([], [], "done")’ so that odeplot can
     perform any clean-up actions required.

     See also: *note odeset: XREFodeset, *note odeget: XREFodeget, *note
     ode23: XREFode23, *note ode45: XREFode45.


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

25 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

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

 -- : [XOPT, FMIN, ERRNUM, 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 (default: 1)’
               Level of messages output by solver routines:

               0 (‘GLP_MSG_OFF’)
                    No output.

               1 (‘GLP_MSG_ERR’)
                    Error and warning messages only.

               2 (‘GLP_MSG_ON’)
                    Normal output.

               3 (‘GLP_MSG_ALL’)
                    Full output (includes informational messages).

          ‘scale (default: 16)’
               Scaling option.  The values can be combined with the
               bitwise OR operator and may be the following:

               1 (‘GLP_SF_GM’)
                    Geometric mean scaling.

               16 (‘GLP_SF_EQ’)
                    Equilibration scaling.

               32 (‘GLP_SF_2N’)
                    Round scale factors to power of two.

               64 (‘GLP_SF_SKIP’)
                    Skip if problem is well scaled.

               Alternatively, a value of 128 (‘GLP_SF_AUTO’) may be also
               specified, in which case the routine chooses the scaling
               options automatically.

          ‘dual (default: 1)’
               Simplex method option:

               1 (‘GLP_PRIMAL’)
                    Use two-phase primal simplex.

               2 (‘GLP_DUALP’)
                    Use two-phase dual simplex, and if it fails, switch
                    to the primal simplex.

               3 (‘GLP_DUAL’)
                    Use two-phase dual simplex.

          ‘price (default: 34)’
               Pricing option (for both primal and dual simplex):

               17 (‘GLP_PT_STD’)
                    Textbook pricing.

               34 (‘GLP_PT_PSE’)
                    Steepest edge pricing.

          ‘itlim (default: intmax)’
               Simplex iterations limit.  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.

          ‘outfrq (default: 200)’
               Output frequency, in iterations.  This parameter
               specifies how frequently the solver sends information
               about the solution to the standard output.

          ‘branch (default: 4)’
               Branching technique option (for MIP only):

               1 (‘GLP_BR_FFV’)
                    First fractional variable.

               2 (‘GLP_BR_LFV’)
                    Last fractional variable.

               3 (‘GLP_BR_MFV’)
                    Most fractional variable.

               4 (‘GLP_BR_DTH’)
                    Heuristic by Driebeck and Tomlin.

               5 (‘GLP_BR_PCH’)
                    Hybrid pseudocost heuristic.

          ‘btrack (default: 4)’
               Backtracking technique option (for MIP only):

               1 (‘GLP_BT_DFS’)
                    Depth first search.

               2 (‘GLP_BT_BFS’)
                    Breadth first search.

               3 (‘GLP_BT_BLB’)
                    Best local bound.

               4 (‘GLP_BT_BPH’)
                    Best projection heuristic.

          ‘presol (default: 1)’
               If this flag is set, the simplex solver uses 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.

          ‘rtest (default: 34)’
               Ratio test technique:

               17 (‘GLP_RT_STD’)
                    Standard ("textbook").

               34 (‘GLP_RT_HAR’)
                    Harris' two-pass ratio test.

          ‘tmlim (default: intmax)’
               Searching time limit, in milliseconds.

          ‘outdly (default: 0)’
               Output delay, in seconds.  This parameter specifies how
               long the solver should delay sending information about
               the solution to the standard output.

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

          ‘tolbnd (default: 1e-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 (default: 1e-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 (default: 1e-10)’
               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 (default: -DBL_MAX)’
               Lower limit of the objective function.  If 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 (default: +DBL_MAX)’
               Upper limit of the objective function.  If the objective
               function reaches this limit and continues increasing, the
               solver stops the search.  This parameter is used in the
               dual simplex only.

          ‘tolint (default: 1e-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 (default: 1e-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.

     ERRNUM
          Error code.

          0
               No error.

          1 (‘GLP_EBADB’)
               Invalid basis.

          2 (‘GLP_ESING’)
               Singular matrix.

          3 (‘GLP_ECOND’)
               Ill-conditioned matrix.

          4 (‘GLP_EBOUND’)
               Invalid bounds.

          5 (‘GLP_EFAIL’)
               Solver failed.

          6 (‘GLP_EOBJLL’)
               Objective function lower limit reached.

          7 (‘GLP_EOBJUL’)
               Objective function upper limit reached.

          8 (‘GLP_EITLIM’)
               Iterations limit exhausted.

          9 (‘GLP_ETMLIM’)
               Time limit exhausted.

          10 (‘GLP_ENOPFS’)
               No primal feasible solution.

          11 (‘GLP_ENODFS’)
               No dual feasible solution.

          12 (‘GLP_EROOT’)
               Root LP optimum not provided.

          13 (‘GLP_ESTOP’)
               Search terminated by application.

          14 (‘GLP_EMIPGAP’)
               Relative MIP gap tolerance reached.

          15 (‘GLP_ENOFEAS’)
               No primal/dual feasible solution.

          16 (‘GLP_ENOCVG’)
               No convergence.

          17 (‘GLP_EINSTAB’)
               Numerical instability.

          18 (‘GLP_EDATA’)
               Invalid data.

          19 (‘GLP_ERANGE’)
               Result out of range.

     EXTRA
          A data structure containing the following fields:

          ‘lambda’
               Dual variables.

          ‘redcosts’
               Reduced Costs.

          ‘time’
               Time (in seconds) used for solving LP/MIP problem.

          ‘status’
               Status of the optimization.

               1 (‘GLP_UNDEF’)
                    Solution status is undefined.

               2 (‘GLP_FEAS’)
                    Solution is feasible.

               3 (‘GLP_INFEAS’)
                    Solution is infeasible.

               4 (‘GLP_NOFEAS’)
                    Problem has no feasible solution.

               5 (‘GLP_OPT’)
                    Solution is optimal.

               6 (‘GLP_UNBND’)
                    Problem has no unbounded solution.

     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

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

 -- : [X, OBJ, INFO, LAMBDA] = qp (X0, H)
 -- : [X, OBJ, INFO, LAMBDA] = qp (X0, H, Q)
 -- : [X, OBJ, INFO, LAMBDA] = qp (X0, H, Q, A, B)
 -- : [X, OBJ, INFO, LAMBDA] = qp (X0, H, Q, A, B, LB, UB)
 -- : [X, OBJ, INFO, LAMBDA] = qp (X0, H, Q, A, B, LB, UB, A_LB, A_IN,
          A_UB)
 -- : [X, OBJ, INFO, LAMBDA] = qp (..., OPTIONS)
     Solve a quadratic program (QP).

     Solve the quadratic program defined by

          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_IN, A_LB, A_UB) may be set to the empty
     matrix (‘[]’) if not present.  The constraints A and A_IN are
     matrices with each row representing a single constraint.  The other
     bounds are scalars or vectors depending on the number of
     constraints.  The algorithm is faster if the initial guess is
     feasible.

     OPTIONS is a structure specifying additional parameters which
     control the algorithm.  Currently, ‘qp’ recognizes these options:
     "MaxIter", "TolX".

     "MaxIter" proscribes the maximum number of algorithm iterations
     before optimization is halted.  The default value is 200.  The
     value must be a positive integer.

     "TolX" specifies the termination tolerance for the unknown
     variables X.  The default is ‘sqrt (eps)’ or approximately 1e-8.

     On return, X is the location of the minimum and FVAL contains the
     value of the objective function at X.

     INFO
          Structure containing run-time information about the algorithm.
          The following fields are defined:

          ‘solveiter’
               The number of iterations required to find the solution.

          ‘info’
               An integer indicating the status of the solution.

               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.

     See also: *note sqp: XREFsqp.

 -- : X = pqpnonneg (C, D)
 -- : X = pqpnonneg (C, D, X0)
 -- : X = pqpnonneg (C, D, X0, OPTIONS)
 -- : [X, MINVAL] = pqpnonneg (...)
 -- : [X, MINVAL, EXITFLAG] = pqpnonneg (...)
 -- : [X, MINVAL, EXITFLAG, OUTPUT] = pqpnonneg (...)
 -- : [X, MINVAL, EXITFLAG, OUTPUT, LAMBDA] = pqpnonneg (...)

     Minimize ‘ (1/2 * X' * C * X + D' * X) ’ subject to ‘X >= 0’.

     C and D must be real matrices, and C must be symmetric and positive
     definite.

     X0 is an optional initial guess for the solution X.

     OPTIONS is an options structure to change the behavior of the
     algorithm (*note ‘optimset’: XREFoptimset.).  ‘pqpnonneg’
     recognizes one option: "MaxIter".

     Outputs:

     X
          The solution matrix

     MINVAL
          The minimum attained model value, ‘1/2*XMIN'*C*XMIN + D'*XMIN’

     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
          Lagrange multipliers.  If these are nonzero, the corresponding
          X values should be zero, indicating the solution is pressed up
          against a coordinate plane.  The magnitude indicates how much
          the residual would improve if the ‘X >= 0’ constraints were
          relaxed in that direction.

     See also: *note lsqnonneg: XREFlsqnonneg, *note qp: XREFqp, *note
     optimset: XREFoptimset.


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

25.3 Nonlinear Programming
==========================

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

 -- : [X, OBJ, INFO, ITER, NF, LAMBDA] = sqp (X0, PHI)
 -- : [...] = sqp (X0, PHI, G)
 -- : [...] = sqp (X0, PHI, G, H)
 -- : [...] = sqp (X0, PHI, G, H, LB, UB)
 -- : [...] = sqp (X0, PHI, G, H, LB, UB, MAXITER)
 -- : [...] = sqp (X0, PHI, G, H, LB, UB, MAXITER, TOLERANCE)
     Minimize an objective function using sequential quadratic
     programming (SQP).

     Solve the nonlinear program

          min phi (x)
           x

     subject to

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

     using a sequential quadratic programming method.

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

     The second argument is a function handle pointing to the objective
     function PHI.  The objective function must accept one vector
     argument and return 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 that computes 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.

     When supplied, the gradient function ‘PHI{2}’ must accept one
     vector argument and return a vector.  When supplied, the Hessian
     function ‘PHI{3}’ must accept one vector argument and return a
     matrix.

     The third and fourth arguments G and H are function handles
     pointing to functions that compute the equality constraints and the
     inequality constraints, respectively.  If the problem does not have
     equality (or inequality) constraints, then use an empty matrix ([])
     for G (or H).  When supplied, these equality and inequality
     constraint functions must accept one vector argument and return 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, LB and UB, contain lower and upper
     bounds on X.  These must be consistent with the equality and
     inequality constraints G and H.  If the arguments are vectors then
     X(i) is bound by LB(i) and UB(i).  A bound can also be a scalar in
     which case all elements of X will share the same bound.

     The seventh argument MAXITER specifies the maximum number of
     iterations.  The default value is 100.

     The eighth argument TOLERANCE specifies the tolerance for the
     stopping criteria.  The default value is ‘sqrt (eps)’.

     The value returned in INFO may be one of the following:

     101
          The algorithm terminated normally.  All constraints meet the
          specified tolerance.

     102
          The BFGS update failed.

     103
          The maximum number of iterations was reached.

     104
          The stepsize has become too small, i.e., delta X, is less than
          ‘TOL * norm (x)’.

     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

     See also: *note qp: XREFqp.


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

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

 -- : [BETA, SIGMA, R] = ols (Y, X)
     Ordinary least squares (OLS) estimation.

     OLS applies to the multivariate model Y = X*B + E 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 is a p-variate observation in which each column
     represents a variable.  Likewise, the rows of X represent k-variate
     observations or possibly designed values.  Furthermore, the
     collection of observations X must be of adequate rank, k, otherwise
     B cannot be uniquely estimated.

     The observation errors, E, are assumed to originate from an
     underlying p-variate distribution with zero mean and p-by-p
     covariance matrix S, both constant conditioned on X.  Furthermore,
     the matrix S is constant with respect to each observation such that
     ‘mean (E) = 0’ and ‘cov (vec (E)) = kron (S, I)’.  (For cases that
     don't meet this criteria, such as autocorrelated errors, see
     generalized least squares, gls, for more efficient estimations.)

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

     BETA
          The OLS estimator for matrix B.  BETA is calculated directly
          via ‘inv (X'*X) * X' * Y’ if the matrix ‘X'*X’ is of full
          rank.  Otherwise, ‘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’.

     See also: *note gls: XREFgls, *note pinv: XREFpinv.

 -- : [BETA, V, R] = gls (Y, X, O)
     Generalized least squares (GLS) model.

     Perform a generalized least squares estimation for the multivariate
     model Y = X*B + E 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 is a p-variate observation in which each column
     represents a variable.  Likewise, the rows of X represent k-variate
     observations or possibly designed values.  Furthermore, the
     collection of observations X must be of adequate rank, k, otherwise
     B cannot be uniquely estimated.

     The observation errors, E, are assumed to originate from an
     underlying p-variate distribution with zero mean but possibly
     heteroscedastic observations.  That is, in general, ‘mean (E) = 0’
     and ‘cov (vec (E)) = (s^2)*O’ in which s is a scalar and O is a
     t*p-by-t*p matrix.

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

     BETA
          The GLS estimator for matrix B.

     V
          The GLS estimator for scalar s^2.

     R
          The matrix of GLS residuals, R = Y - X*BETA.

     See also: *note ols: XREFols.

 -- : X = lsqnonneg (C, D)
 -- : X = lsqnonneg (C, D, X0)
 -- : X = lsqnonneg (C, D, X0, OPTIONS)
 -- : [X, RESNORM] = lsqnonneg (...)
 -- : [X, RESNORM, RESIDUAL] = lsqnonneg (...)
 -- : [X, RESNORM, RESIDUAL, EXITFLAG] = lsqnonneg (...)
 -- : [X, RESNORM, RESIDUAL, EXITFLAG, OUTPUT] = lsqnonneg (...)
 -- : [X, RESNORM, RESIDUAL, EXITFLAG, OUTPUT, LAMBDA] = lsqnonneg (...)

     Minimize ‘norm (C*X - D)’ subject to ‘X >= 0’.

     C and D must be real matrices.

     X0 is an optional initial guess for the solution X.

     OPTIONS is an options structure to change the behavior of the
     algorithm (*note ‘optimset’: XREFoptimset.).  ‘lsqnonneg’
     recognizes these options: "MaxIter", "TolX".

     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
          Lagrange multipliers.  If these are nonzero, the corresponding
          X values should be zero, indicating the solution is pressed up
          against a coordinate plane.  The magnitude indicates how much
          the residual would improve if the ‘X >= 0’ constraints were
          relaxed in that direction.

     See also: *note pqpnonneg: XREFpqpnonneg, *note lscov: XREFlscov,
     *note optimset: XREFoptimset.

 -- : X = lscov (A, B)
 -- : X = lscov (A, B, V)
 -- : X = lscov (A, B, V, ALG)
 -- : [X, STDX, MSE, S] = lscov (...)

     Compute a generalized linear least squares fit.

     Estimate X under the model B = AX + W, where the noise W is assumed
     to follow a normal distribution with covariance matrix {\sigma^2}
     V.

     If the size of the coefficient matrix A is n-by-p, the size of the
     vector/array of constant terms B must be n-by-k.

     The optional input argument V may be an n-element vector of
     positive weights (inverse variances), or an n-by-n symmetric
     positive semi-definite matrix representing the covariance of B.  If
     V is not supplied, the ordinary least squares solution is returned.

     The ALG input argument, a guidance on solution method to use, is
     currently ignored.

     Besides the least-squares estimate matrix X (p-by-k), the function
     also returns STDX (p-by-k), the error standard deviation of
     estimated X; MSE (k-by-1), the estimated data error covariance
     scale factors (\sigma^2); and S (p-by-p, or p-by-p-by-k if k > 1),
     the error covariance of X.

     Reference: Golub and Van Loan (1996), ‘Matrix Computations (3rd
     Ed.)’, Johns Hopkins, Section 5.6.3

     See also: *note ols: XREFols, *note gls: XREFgls, *note lsqnonneg:
     XREFlsqnonneg.

 -- : optimset ()
 -- : OPTIONS = optimset ()
 -- : OPTIONS = optimset (PAR, VAL, ...)
 -- : OPTIONS = optimset (OLD, PAR, VAL, ...)
 -- : OPTIONS = optimset (OLD, NEW)
     Create options structure for optimization functions.

     When called without any input or output arguments, ‘optimset’
     prints a list of all valid optimization parameters.

     When called with one output and no inputs, return an options
     structure with all valid option parameters initialized to ‘[]’.

     When called with a list of parameter/value pairs, return an options
     structure with only the named parameters initialized.

     When the first input is an existing options structure OLD, the
     values are updated from either the PAR/VAL list or from the options
     structure NEW.

     If PAR does not exactly match the name of a standard parameter,
     ‘optimset’ will attempt to match PAR to a standard parameter and
     will set the value of that parameter if a match is found.  Matching
     is case insensitive and is based on character matching at the start
     of the parameter name.  ‘optimset’ produces an error if it finds
     multiple ambiguous matches.  If no standard parameter matches are
     found a warning is issued and the non-standard parameter is
     created.

     Standard list of valid parameters:

     AutoScaling

     ComplexEqn

     Display
          Request verbose display of results from optimizations.  Values
          are:

          "off" [default]
               No display.

          "iter"
               Display intermediate results for every loop iteration.

          "final"
               Display the result of the final loop iteration.

          "notify"
               Display the result of the final loop iteration if the
               function has failed to converge.

     FinDiffType

     FunValCheck
          When enabled, display an error if the objective function
          returns an invalid value (a complex number, NaN, or Inf).
          Must be set to "on" or "off" [default].  Note: the functions
          ‘fzero’ and ‘fminbnd’ correctly handle Inf values and only
          complex values or NaN will cause an error in this case.

     GradObj
          When set to "on", the function to be minimized must return a
          second argument which is the gradient, or first derivative, of
          the function at the point X.  If set to "off" [default], the
          gradient is computed via finite differences.

     Jacobian
          When set to "on", the function to be minimized must return a
          second argument which is the Jacobian, or first derivative, of
          the function at the point X.  If set to "off" [default], the
          Jacobian is computed via finite differences.

     MaxFunEvals
          Maximum number of function evaluations before optimization
          stops.  Must be a positive integer.

     MaxIter
          Maximum number of algorithm iterations before optimization
          stops.  Must be a positive integer.

     OutputFcn
          A user-defined function executed once per algorithm iteration.

     TolFun
          Termination criterion for the function output.  If the
          difference in the calculated objective function between one
          algorithm iteration and the next is less than ‘TolFun’ the
          optimization stops.  Must be a positive scalar.

     TolX
          Termination criterion for the function input.  If the
          difference in X, the current search point, between one
          algorithm iteration and the next is less than ‘TolX’ the
          optimization stops.  Must be a positive scalar.

     TypicalX

     Updating

     This list can be extended by the user or other loaded Octave
     packages.  An updated valid parameters list can be queried using
     the no-argument form of ‘optimset’.

     Note 1: Only parameter names from the standard list are considered
     when matching short parameter names, and PAR will always be
     expanded to match a standard parameter even if an exact
     non-standard match exists.  The value of a non-standard parameter
     that is ambiguous with one or more standard parameters cannot be
     set by ‘optimset’ and can only be set using ‘setfield’ or dot
     notation for structs.

     Note 2: The optimization options structure is primarily intended
     for manipulation of known parameters by ‘optimset’ and ‘optimget’.
     Unpredictable behavior on future calls to ‘optimset’ or ‘optimget’
     can result from creating non-standard or ambiguous parameters or
     from loading/unloading packages that change the known parameter
     list after creation of an optimization options structure.

     See also: *note optimget: XREFoptimget.

 -- : VAL = optimget (OPTIONS, PAR)
 -- : VAL = optimget (OPTIONS, PAR, DEFAULT)
     Return the value of the specific parameter PAR from the
     optimization options structure OPTIONS created by ‘optimset’.

     If PAR is not defined then return the DEFAULT value if supplied,
     otherwise return an empty matrix.

     If PAR does not exactly match the name of a standard parameter,
     ‘optimget’ will attempt to match PAR to a standard parameter and
     will return that parameter's value if a match is found.  Matching
     is case insensitive and is based on character matching at the start
     of the parameter name.  ‘optimget’ produces an error if it finds
     multiple ambiguous matches.  If no standard parameter matches are
     found a warning is issued.  See ‘optimset’ for information about
     the standard options list.

     Note: Only parameter names from the standard list are considered
     when matching short parameter names, and PAR will always be
     expanded to match a standard parameter even if an exact
     non-standard match exists.  The value of a non-standard parameter
     that is ambiguous with one or more standard parameters cannot be
     returned by ‘optimget’ and can only be accessed using ‘getfield’ or
     dot notation for structs.

     See also: *note optimset: XREFoptimset.


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

26 Statistics
*************

Octave has support for various statistical methods.  The emphasis is on
basic descriptive statistics, but the Octave Forge statistics package
includes probability distributions, statistical tests, random number
generation, and much more.

   The functions that analyze data all assume that multi-dimensional
data is arranged in a matrix where each row is an observation, and each
column is a variable.  Thus, 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.  These values need to be detected and dealt
with explicitly.  See *note isnan: XREFisnan, *note isna: XREFisna,
*note isinf: XREFisinf, *note isfinite: XREFisfinite.

* Menu:

* Descriptive Statistics::
* Statistics on Sliding Windows of Data::
* Basic Statistical Functions::
* Correlation and Regression Analysis::
* Distributions::
* Random Number Generation::


File: octave.info,  Node: Descriptive Statistics,  Next: Statistics on Sliding Windows of Data,  Up: Statistics

26.1 Descriptive Statistics
===========================

One principal goal of descriptive statistics is to represent the essence
of a large data set concisely.  Octave provides the mean, median, and
mode functions which all summarize a data set with just a single number
corresponding to the central tendency of the data.

 -- : M = mean (X)
 -- : M = mean (X, DIM)
 -- : M = mean (X, VECDIM)
 -- : M = mean (X, "all")
 -- : M = mean (..., NANFLAG)
 -- : M = mean (..., OUTTYPE)
     Compute the mean of the elements of X.

     If X is a vector, then ‘mean (X)’ returns the mean of the elements
     in X defined as

          mean (X) = SUM_i X(i) / N

     where N is the number of elements in X.

     If X is an array, then ‘mean(X)’ computes the mean along the first
     non-singleton dimension of X.

     The optional variable DIM forces ‘mean’ to operate over the
     specified dimension, which must be a positive integer-valued
     number.  Specifying any singleton dimension in X, including any
     dimension exceeding ‘ndims (X)’, will result in a mean equal to X.

     Specifying the dimensions as VECDIM, a vector of non-repeating
     dimensions, will return the mean over the array slice defined by
     VECDIM.  If VECDIM indexes all dimensions of X, then it is
     equivalent to the option "all".  Any dimension in VECDIM greater
     than ‘ndims (X)’ is ignored.

     Specifying the dimension as "all" will force ‘mean’ to operate on
     all elements of X, and is equivalent to ‘mean (X(:))’.

     The optional input OUTTYPE specifies the data type that is
     returned.  OUTTYPE can take the following values:

     'default' : Output is of type double, unless the input is
          single in which case the output is of type single.

     'double' : Output is of type double.

     'native' : Output is of the same type as the input as reported
          by (‘class (X)’), unless the input is logical in which case
          the output is of type double.

     The optional variable NANFLAG specifies whether to include or
     exclude NaN values from the calculation using any of the previously
     specified input argument combinations.  The default value for
     NANFLAG is "includenan" which keeps NaN values in the calculation.
     To exclude NaN values set the value of NANFLAG to "omitnan".  The
     output will still contain NaN values if X consists of all NaN
     values in the operating dimension.

     See also: *note median: XREFmedian, *note mode: XREFmode, *note
     movmean: XREFmovmean.

 -- : M = median (X)
 -- : M = median (X, DIM)
 -- : M = median (X, VECDIM)
 -- : M = median (X, "all")
 -- : M = median (..., NANFLAG)
 -- : M = median (..., OUTTYPE)
     Compute the median value of the elements of X.

     When the elements of X are sorted, say ‘S = sort (X)’, the median
     is defined as

                       |  S(ceil (N/2))          N odd
          median (X) = |
                       | (S(N/2) + S(N/2+1))/2   N even

     If X is an array, then ‘median (X)’ operates along the first
     non-singleton dimension of X.

     The optional variable DIM forces ‘median’ to operate over the
     specified dimension, which must be a positive integer-valued
     number.  Specifying any singleton dimension in X, including any
     dimension exceeding ‘ndims (X)’, will result in a median equal to
     X.

     Specifying the dimensions as VECDIM, a vector of non-repeating
     dimensions, will return the median over the array slice defined by
     VECDIM.  If VECDIM indexes all dimensions of X, then it is
     equivalent to the option "all".  Any dimension in VECDIM greater
     than ‘ndims (X)’ is ignored.

     Specifying the dimension as "all" will force ‘median’ to operate on
     all elements of X, and is equivalent to ‘median (X(:))’.

     ‘median (..., OUTTYPE)’ returns the median with a specified data
     type, using any of the input arguments in the previous syntaxes.
     OUTTYPE can take the following values:

     "default"
          Output is of type double, unless the input is single in which
          case the output is of type single.

     "double"
          Output is of type double.

     "native".
          Output is of the same type as the input (‘class (X)’), unless
          the input is logical in which case the output is of type
          double.

     The optional variable NANFLAG specifies whether to include or
     exclude NaN values from the calculation using any of the previously
     specified input argument combinations.  The default value for
     NANFLAG is "includenan" which keeps NaN values in the calculation.
     To exclude NaN values set the value of NANFLAG to "omitnan".  The
     output will still contain NaN values if X consists of all NaN
     values in the operating dimension.

     See also: *note mean: XREFmean, *note mode: XREFmode, *note
     movmedian: XREFmovmedian.

 -- : M = mode (X)
 -- : M = mode (X, DIM)
 -- : [M, F, C] = mode (...)
     Compute the most frequently occurring value in a dataset (mode).

     ‘mode’ determines the frequency of values along the first
     non-singleton dimension and returns the value with the highest
     frequency.  If two, or more, values have the same frequency ‘mode’
     returns the smallest.

     If the optional argument DIM is given, operate along this
     dimension.

     The return variable F is the number of occurrences of the mode in
     the dataset.

     The cell array C contains all of the elements with the maximum
     frequency.

     See also: *note mean: XREFmean, *note median: XREFmedian.

   Using just one number, such as the mean, to represent an entire data
set may not give an accurate picture of the data.  One way to
characterize the fit is to measure the dispersion of the data.  Octave
provides several functions for measuring dispersion.

 -- : [S, L] = bounds (X)
 -- : [S, L] = bounds (X, DIM)
 -- : [S, L] = bounds (..., "nanflag")
     Return the smallest and largest values of the input data X.

     If X is a vector, the bounds are calculated over the elements of X.
     If X is a matrix, the bounds are calculated for each column.  For a
     multi-dimensional array, the bounds are calculated over the first
     non-singleton dimension.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional argument "nanflag" defaults to "omitnan" which does
     not include NaN values in the result.  If the argument "includenan"
     is given, and there is a NaN present, then the result for both
     smallest (S) and largest (L) elements will be NaN.

     The bounds are a quickly computed measure of the dispersion of a
     data set, but are less accurate than ‘iqr’ if there are outlying
     data points.

     See also: *note range: XREFrange, *note iqr: XREFiqr, *note mad:
     XREFmad, *note std: XREFstd.

 -- : Y = range (X)
 -- : Y = range (X, DIM)
     Return the range, i.e., the difference between the maximum and the
     minimum of the input data.

     If X is a vector, the range is calculated over the elements of X.
     If X is a matrix, the range is calculated over each column of X.

     If the optional argument DIM is given, operate along this
     dimension.

     The range is a quickly computed measure of the dispersion of a data
     set, but is less accurate than ‘iqr’ if there are outlying data
     points.

     See also: *note bounds: XREFbounds, *note iqr: XREFiqr, *note mad:
     XREFmad, *note std: XREFstd.

 -- : Z = iqr (X)
 -- : Z = iqr (X, DIM)
 -- : Z = iqr (X, "ALL")
     Return the interquartile range of X, defined as the distance
     between the 25th and 75th percentile values of X calculated using:
     quantile (x, [0.25 0.75])

     If X is a vector, ‘iqr (X)’ will operate on the data in X.

     If X is a matrix, ‘iqr (X)’ will operate independently on each
     column in X returning a row vector Z.

     If X is a n-dimensional array, ‘iqr (X)’ will operate independently
     on the first non-singleton dimension in X, returning an array Z the
     same shape as X with the non-singleton dimenion reduced to 1.

     The optional variable DIM can be used to force ‘iqr’ to operate
     over the specified dimension.  DIM can either be a scalar dimension
     or a vector of non-repeating dimensions over which to operate.  In
     either case DIM must be positive integers.  A vector DIM
     concatenates all specified dimensions for independent operation by
     ‘iqr’.

     Specifying dimension "ALL" will force ‘iqr’ to operate on all
     elements of X, and is equivalent to ‘iqr (X(:))’.  Similarly,
     specifying a vector dimension including all non-singleton
     dimensions of X is equivalent to ‘iqr (X, "ALL")’.

     If X is a scalar, or only singleton dimensions are specified for
     DIM, the output will be ‘zeros (size (X))’.

     As a measure of dispersion, the interquartile range is less
     affected by outliers than either ‘range’ or ‘std’.

     See also: *note bounds: XREFbounds, *note mad: XREFmad, *note
     range: XREFrange, *note std: XREFstd, *note prctile: XREFprctile,
     *note quantile: XREFquantile.

 -- : M = mad (X)
 -- : M = mad (X, OPT)
 -- : M = mad (X, OPT, DIM)
 -- : M = mad (X, OPT, VECDIM)
 -- : M = mad (X, OPT, "all")
     Compute the mean or median absolute deviation (MAD) of the elements
     of X.

     The mean absolute deviation is defined as

          MAD = mean (abs (X - mean (X)))

     The median absolute deviation is defined as

          MAD = median (abs (X - median (X)))

     If X is a vector, compute ‘mad’ for each element in X.  If X is an
     array the calculation is performed over the first non-singleton
     dimension.

     ‘mad’ excludes NaN values from calculation similar to using the
     ‘omitnan’ option in ‘var’, ‘mean’, and ‘median’.

     The optional argument OPT determines whether mean or median
     absolute deviation is calculated.  The default is 0 which
     corresponds to mean absolute deviation; a value of 1 corresponds to
     median absolute deviation.  Passing an empty input [] defaults to
     mean absolute deviation (OPT = 0).

     The optional argument DIM forces ‘mad’ to operate along the
     specified dimension.  Specifying any singleton dimension in X,
     including any dimension exceeding ‘ndims (X)’, will result in an
     output of 0.

     Specifying the dimension as VECDIM, a vector of non-repeating
     dimensions, will return the ‘mad’ over the array slice defined by
     VECDIM.  If VECDIM indexes all dimensions of X, then it is
     equivalent to the option "all".  Any dimension included in VECDIM
     greater than ‘ndims (X)’ is ignored.

     Specifying the dimension as "all" will force ‘mad’ to operate on
     all elements of X, and is equivalent to ‘mad (X(:))’.

     As a measure of dispersion, ‘mad’ is less affected by outliers than
     ‘std’.

     See also: *note bounds: XREFbounds, *note range: XREFrange, *note
     iqr: XREFiqr, *note std: XREFstd, *note mean: XREFmean, *note
     median: XREFmedian.

 -- : Y = meansq (X)
 -- : Y = meansq (X, DIM)
     Compute the mean square of the elements of the vector X.

     The mean square is defined as

          meansq (X) = 1/N SUM_i X(i)^2

     where N is the length of the X vector.

     If X is a matrix, return a row vector containing the mean square of
     each column.

     If the optional argument DIM is given, operate along this
     dimension.

     See also: *note var: XREFvar, *note std: XREFstd, *note moment:
     XREFmoment.

 -- : S = std (X)
 -- : S = std (X, W)
 -- : S = std (X, W, DIM)
 -- : S = std (X, W, VECDIM)
 -- : S = std (X, W, "ALL")
 -- : S = std (..., NANFLAG)
 -- : [S, M] = std (...)
     Compute the standard deviation of the elements of the vector X.

     The standard deviation is defined as

          std (X) = sqrt ((1 / (N-1)) * SUM_i ((X(i) - mean(X))^2))

     where N is the number of elements of X.

     If X is an array, compute the standard deviation along the first
     non-singleton dimensions of X.

     The optional argument W determines the weighting scheme to use.
     Valid values are:

     0 [default]:
          Normalize with N-1 (population standard deviation).  This
          provides the square root of the best unbiased estimator of the
          standard deviation.

     1:
          Normalize with N (sample standard deviation).  This provides
          the square root of the second moment around the mean.

     a vector:
          Compute the weighted standard deviation with non-negative
          weights.  The length of W must equal the size of X in the
          operating dimension.  NaN values are permitted in W, will be
          multiplied with the associated values in X, and can be
          excluded by the NANFLAG option.

     an array:
          Similar to vector weights, but W must be the same size as X.
          If the operating dimension is supplied as VECDIM or "all" and
          W is not a scalar, W must be an same-sized array.

     Note: W must always be specified before specifying any of the
     following dimension options.  To use the default value for W you
     may pass an empty input argument [].

     The optional variable DIM forces ‘std’ to operate over the
     specified dimension, which must be a positive integer-valued
     number.  Specifying any singleton dimension in X, including any
     dimension exceeding ‘ndims (X)’, will result in a standard
     deviation of 0.

     Specifying the dimensions as VECDIM, a vector of non-repeating
     dimensions, will return the standard deviation calculated over the
     array slice defined by VECDIM.  If VECDIM indexes all dimensions of
     X, then it is equivalent to the option "all".  Any dimension in
     VECDIM greater than ‘ndims (X)’ is ignored.

     Specifying the dimension as "all" will force ‘std’ to operate on
     all elements of X, and is equivalent to ‘std (X(:))’.

     The optional variable NANFLAG specifies whether to include or
     exclude NaN values from the calculation using any of the previously
     specified input argument combinations.  The default value for
     NANFLAG is "includenan" which keeps NaN values in the calculation.
     To exclude NaN values set the value of NANFLAG to "omitnan".  The
     output will still contain NaN values if X consists of all NaN
     values in the operating dimension.

     The optional second output variable M contains the mean of the
     elements of X used to calculate the standard deviation.  If V is
     the weighted standard deviation, then M is also the weighted mean.

     See also: *note var: XREFvar, *note bounds: XREFbounds, *note mad:
     XREFmad, *note range: XREFrange, *note iqr: XREFiqr, *note mean:
     XREFmean, *note median: XREFmedian.

   In addition to knowing the size of a dispersion it is useful to know
the shape of the data set.  For example, are data points massed to the
left or right of the mean?  Octave provides several common measures to
describe the shape of the data set.  Octave can also calculate moments
allowing arbitrary shape measures to be developed.

 -- : V = var (X)
 -- : V = var (X, W)
 -- : V = var (X, W, DIM)
 -- : V = var (X, W, VECDIM)
 -- : V = var (X, W, "all")
 -- : V = var (..., NANFLAG)
 -- : [V, M] = var (...)
     Compute the variance of the elements of the vector X.

     The variance is defined as

          var (X) = (1 / (N-1)) * SUM_i ((X(i) - mean(X))^2)

     where N is the number of elements of X.

     If X is an array, compute the variance along the first
     non-singleton dimensions of X.

     The optional argument W determines the weighting scheme to use.
     Valid values are:

     0 [default]:
          Normalize with N-1 (population variance).  This provides the
          square root of the best unbiased estimator of the variance.

     1:
          Normalize with N (sample variance).  This provides the square
          root of the second moment around the mean.

     a vector:
          Compute the weighted variance with non-negative weights.  The
          length of W must equal the size of X in the operating
          dimension.  NaN values are permitted in W, will be multiplied
          with the associated values in X, and can be excluded by the
          NANFLAG option.

     an array:
          Similar to vector weights, but W must be the same size as X.
          If the operating dimension is supplied as VECDIM or "all" and
          W is not a scalar, W must be an same-sized array.

     Note: W must always be specified before specifying any of the
     following dimension options.  To use the default value for W you
     may pass an empty input argument [].

     The optional variable DIM forces ‘var’ to operate over the
     specified dimension, which must be a positive integer-valued
     number.  Specifying any singleton dimension in X, including any
     dimension exceeding ‘ndims (X)’, will result in a variance of 0.

     Specifying the dimensions as VECDIM, a vector of non-repeating
     dimensions, will return the variance calculated over the array
     slice defined by VECDIM.  If VECDIM indexes all dimensions of X,
     then it is equivalent to the option "all".  Any dimension in VECDIM
     greater than ‘ndims (X)’ is ignored.

     Specifying the dimension as "all" will force ‘var’ to operate on
     all elements of X, and is equivalent to ‘var (X(:))’.

     The optional variable NANFLAG specifies whether to include or
     exclude NaN values from the calculation using any of the previously
     specified input argument combinations.  The default value for
     NANFLAG is "includenan" which keeps NaN values in the calculation.
     To exclude NaN values set the value of NANFLAG to "omitnan".  The
     output will still contain NaN values if X consists of all NaN
     values in the operating dimension.

     The optional second output variable M contains the mean of the
     elements of X used to calculate the variance.  If V is the weighted
     variance, then M is also the weighted mean.

     See also: *note std: XREFstd, *note mean: XREFmean, *note cov:
     XREFcov, *note skewness: XREFskewness, *note kurtosis:
     XREFkurtosis, *note moment: XREFmoment.

 -- : Y = skewness (X)
 -- : Y = skewness (X, FLAG)
 -- : Y = skewness (X, FLAG, DIM)
     Compute the sample skewness of the elements of X.

     The sample skewness is defined as

                         mean ((X - mean (X)).^3)
          skewness (X) = ------------------------.
                                std (X).^3

     The optional argument FLAG controls which normalization is used.
     If FLAG is equal to 1 (default value, used when FLAG is omitted or
     empty), return the sample skewness as defined above.  If FLAG is
     equal to 0, return the adjusted skewness coefficient instead:

                            sqrt (N*(N-1))   mean ((X - mean (X)).^3)
          skewness (X, 0) = -------------- * ------------------------.
                                (N - 2)             std (X).^3

     where N is the length of the X vector.

     The adjusted skewness coefficient is obtained by replacing the
     sample second and third central moments by their bias-corrected
     versions.

     If X is a matrix, or more generally a multi-dimensional array,
     return the skewness along the first non-singleton dimension.  If
     the optional DIM argument is given, operate along this dimension.

     See also: *note var: XREFvar, *note kurtosis: XREFkurtosis, *note
     moment: XREFmoment.

 -- : Y = kurtosis (X)
 -- : Y = kurtosis (X, FLAG)
 -- : Y = kurtosis (X, FLAG, DIM)
     Compute the sample kurtosis of the elements of X.

     The sample kurtosis is defined as

               mean ((X - mean (X)).^4)
          k1 = ------------------------
                      std (X).^4

     The optional argument FLAG controls which normalization is used.
     If FLAG is equal to 1 (default value, used when FLAG is omitted or
     empty), return the sample kurtosis as defined above.  If FLAG is
     equal to 0, return the "bias-corrected" kurtosis coefficient
     instead:

                        N - 1
          k0 = 3 + -------------- * ((N + 1) * k1 - 3 * (N - 1))
                   (N - 2)(N - 3)

     where N is the length of the X vector.

     The bias-corrected kurtosis coefficient is obtained by replacing
     the sample second and fourth central moments by their unbiased
     versions.  It is an unbiased estimate of the population kurtosis
     for normal populations.

     If X is a matrix, or more generally a multi-dimensional array,
     return the kurtosis along the first non-singleton dimension.  If
     the optional DIM argument is given, operate along this dimension.

     See also: *note var: XREFvar, *note skewness: XREFskewness, *note
     moment: XREFmoment.

 -- : M = moment (X, P)
 -- : M = moment (X, P, TYPE)
 -- : M = moment (X, P, DIM)
 -- : M = moment (X, P, TYPE, DIM)
 -- : M = moment (X, P, DIM, TYPE)
     Compute the P-th central moment of the vector X.

     The P-th central moment of X is defined as:

          1/N SUM_i (X(i) - mean(X))^P

     where N is the length of the X vector.

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

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string TYPE specifies the type of moment to be
     computed.  Valid options are:

     "c"
          Central Moment (default).

     "a"
     "ac"
          Absolute Central Moment.  The moment about the mean ignoring
          sign defined as

               1/N SUM_i (abs (X(i) - mean(X)))^P

     "r"
          Raw Moment.  The moment about zero defined as

               moment (X) = 1/N SUM_i X(i)^P

     "ar"
          Absolute Raw Moment.  The moment about zero ignoring sign
          defined as

               1/N SUM_i ( abs (X(i)) )^P

     If both TYPE and DIM are given they may appear in any order.

     See also: *note var: XREFvar, *note skewness: XREFskewness, *note
     kurtosis: XREFkurtosis.

 -- : Q = quantile (X)
 -- : Q = quantile (X, P)
 -- : Q = quantile (X, P, DIM)
 -- : 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.

     If P is unspecified, return the quantiles for ‘[0.00 0.25 0.50 0.75
     1.00]’.  The optional argument DIM determines the dimension along
     which the quantiles are calculated.  If DIM is omitted it defaults
     to the first non-singleton dimension.

     The methods available to calculate sample quantiles are the nine
     methods used by R (<https://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 method's
     representative cdf.

       4. Method 4: P(k) = k / N. That is, linear interpolation of the
          empirical cdf, where N is the length of P.

       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;
          <https://cran.r-project.org/doc/manuals/fullrefman.pdf>.

     Examples:

          x = randi (1000, [10, 1]);  # Create empirical data in range 1-1000
          q = quantile (x, [0, 1]);   # Return minimum, maximum of distribution
          q = quantile (x, [0.25 0.5 0.75]); # Return quartiles of distribution

     See also: *note prctile: XREFprctile.

 -- : Q = prctile (X)
 -- : Q = prctile (X, P)
 -- : Q = prctile (X, P, DIM)
     For a sample X, compute the quantiles, Q, corresponding to the
     cumulative probability values, P, in percent.

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

     If P is unspecified, return the quantiles for ‘[0 25 50 75 100]’.

     The optional argument DIM determines the dimension along which the
     percentiles are calculated.  If DIM is omitted it defaults to the
     first non-singleton dimension.

     Programming Note: All non-numeric values (NaNs) of X are ignored.

     See also: *note quantile: XREFquantile.

   A summary view of a data set can be generated quickly with the
‘statistics’ function.

 -- : STATS = statistics (X)
 -- : STATS = statistics (X, DIM)
     Return a vector with the minimum, first quartile, median, third
     quartile, maximum, mean, standard deviation, skewness, and kurtosis
     of the elements of the vector X.

     If X is a matrix, calculate statistics over the first non-singleton
     dimension.

     If the optional argument DIM is given, operate along this
     dimension.

     See also: *note min: XREFmin, *note max: XREFmax, *note median:
     XREFmedian, *note mean: XREFmean, *note std: XREFstd, *note
     skewness: XREFskewness, *note kurtosis: XREFkurtosis.


File: octave.info,  Node: Statistics on Sliding Windows of Data,  Next: Basic Statistical Functions,  Prev: Descriptive Statistics,  Up: Statistics

26.2 Statistics on Sliding Windows of Data
==========================================

It is often useful to calculate descriptive statistics over a subsection
(i.e., window) of a full dataset.  Octave provides the function ‘movfun’
which will call an arbitrary function handle with windows of data and
accumulate the results.  Many of the most commonly desired functions,
such as the moving average over a window of data (‘movmean’), are
already provided.

 -- : Y = movfun (FCN, X, WLEN)
 -- : Y = movfun (FCN, X, [NB, NA])
 -- : Y = movfun (..., "PROPERTY", VALUE)

     Apply function FCN to a moving window of length WLEN on data X.

     If WLEN is a scalar, the function FCN is applied to a moving window
     of length WLEN.  When WLEN is an odd number the window is symmetric
     and includes ‘(WLEN - 1) / 2’ elements on either side of the
     central element.  For example, when calculating the output at index
     5 with a window length of 3, ‘movfun’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movfun’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     During calculations the data input X is reshaped into a
     2-dimensional WLEN-by-N matrix and FCN is called on this new
     matrix.  Therefore, FCN must accept an array input argument and
     apply the computation along dimension 1, i.e., down the columns of
     the array.

     When applied to an array (possibly multi-dimensional) with N
     columns, FCN may return a result in either of two formats:
     Format 1) an array of size 1-by-N-by-DIM3-by-...-by-DIMN.  This is
     the typical output format from Octave core functions.  Type ‘demo
     ("movfun", 5)’ for an example of this use case.  Format 2) a row
     vector of length ‘N * NUMEL_HIGHER_DIMS’ where NUMEL_HIGHER_DIMS is
     ‘prod (size (X)(3:end))’.  The output of FCN for the i-th input
     column must be found in the output at indices
     ‘i:N:(N*NUMEL_HIGHER_DIMS)’.  This format is useful when
     concatenating functions into arrays, or when using ‘nthargout’.
     Type ‘demo ("movfun", 6)’ for an example of this case.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "dim"
          Operate along the dimension specified, rather than the default
          of the first non-singleton dimension.

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               FCN (X(1:2))’, and ‘Y(end) = FCN (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = FCN ([NaN, X(1:2)])’, and ‘Y(end) = FCN ([X(end-1:end),
               NaN])’.  This option usually results in Y having ‘NaN’
               values at the boundaries, although it is influenced by
               how FCN handles ‘NaN’, and also by the property
               "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               FCN ([USER_VALUE, X(1:2)])’, and ‘Y(end) = FCN
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = FCN ([X(1), X(1:2)])’, and
               ‘Y(end) = FCN ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = FCN ([X(end),
               X(1:2)])’, and ‘Y(end) = FCN ([X(end-1:end), X(1)])’.

          Note that for some of these choices, the window size at the
          boundaries is not the same as for the central part, and FCN
          must work in these cases.

     "nancond"
          Controls whether ‘NaN’ and ‘NA’ values should be included
          (value: "includenan"), or excluded (value: "omitnan"), from
          the data passed to FCN.  The default is "includenan".
          Caution: The "omitnan" option is not yet implemented.

     "outdim"
          A row vector that selects which dimensions of the calculation
          will appear in the output Y.  This is only useful when FCN
          returns an N-dimensional array in Format 1.  The default is to
          return all output dimensions.

     Programming Note: The property "outdim" can be used to save memory
     when the output of FCN has many dimensions, or when a wrapper to
     the base function that selects the desired outputs is too costly.
     When memory is not an issue, the easiest way to select output
     dimensions is to first calculate the complete result with ‘movfun’
     and then filter that result with indexing.  If code complexity is
     not an issue then a wrapper can be created using anonymous
     functions.  For example, if ‘basefcn’ is a function returning a
     K-dimensional row output, and only dimension D is desired, then the
     following wrapper could be used.

          FCN = @(x) basefcn (x)(:,columns(x) * (D-1) + (1:columns(x)));
          Y = movfun (@fcn, ...);

     See also: *note movslice: XREFmovslice, *note prepad: XREFprepad,
     *note postpad: XREFpostpad, *note permute: XREFpermute, *note
     reshape: XREFreshape.

 -- : SLCIDX = movslice (N, WLEN)
 -- : [SLCIDX, C, CPRE, CPOST, WIN] = movslice (...)
     Generate indices to slice a vector of length N into windows of
     length WLEN.

     The input N must be a positive integer.

     The moving window length input WLEN can either be a scalar not
     equal to 1 or a 2-element array of integers.  For scalar values, if
     odd the window is symmetric and includes ‘(WLEN - 1) / 2’ elements
     on either side of the central element.  If WLEN is even the window
     is asymmetric and has ‘WLEN/2’ elements to the left of the central
     element and ‘WLEN/2 - 1’ elements to the right of the central
     element.  When WLEN is a 2-element array, ‘[NB, NA]’, the window
     includes NB elements to the left of the current element and NA
     elements to the right of the current element.

     The output SLCIDX is an array of indices of the slices that fit
     fully within the vector, where each column is an individual slice
     as the window moves from left to right.  The slices have WLEN
     elements for scalar WLEN, or ‘NB + NA + 1’ elements for array
     valued WLEN.

     Optional output C is an row vector of window center positions where
     the window stays fully within the vector.

     Optional outputs CPRE and CPOST contain the vector elements at the
     start and end of the vector, respectively, that result in the
     window extending beyond the ends of the vector.

     Optional output WIN is a column vector with the same number of rows
     as SLCIDX that contains the moving window defined as a center
     relative position stencil.

     See also: *note movfun: XREFmovfun.

 -- : Y = movmad (X, WLEN)
 -- : Y = movmad (X, [NB, NA])
 -- : Y = movmad (..., DIM)
 -- : Y = movmad (..., "NANCOND")
 -- : Y = movmad (..., PROPERTY, VALUE)
     Calculate the moving mean absolute deviation over a sliding window
     of length WLEN on data X.

     If WLEN is a scalar, the function ‘mad’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movmad’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movmad’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘mad’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               mad (X(1:2))’, and ‘Y(end) = mad (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = mad ([NaN, X(1:2)])’, and ‘Y(end) = mad ([X(end-1:end),
               NaN])’.  This option usually results in Y having ‘NaN’
               values at the boundaries, although it is influenced by
               how ‘mad’ handles ‘NaN’, and also by the property
               "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               mad ([USER_VALUE, X(1:2)])’, and ‘Y(end) = mad
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = mad ([X(1), X(1:2)])’, and
               ‘Y(end) = mad ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = mad ([X(end),
               X(1:2)])’, and ‘Y(end) = mad ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmax: XREFmovmax, *note movmean: XREFmovmean, *note
     movmedian: XREFmovmedian, *note movmin: XREFmovmin, *note movprod:
     XREFmovprod, *note movstd: XREFmovstd, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movmax (X, WLEN)
 -- : Y = movmax (X, [NB, NA])
 -- : Y = movmax (..., DIM)
 -- : Y = movmax (..., "NANCOND")
 -- : Y = movmax (..., PROPERTY, VALUE)
     Calculate the moving maximum over a sliding window of length WLEN
     on data X.

     If WLEN is a scalar, the function ‘max’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movmax’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movmax’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘max’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               max (X(1:2))’, and ‘Y(end) = max (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = max ([NaN, X(1:2)])’, and ‘Y(end) = max ([X(end-1:end),
               NaN])’.  This option usually results in Y having ‘NaN’
               values at the boundaries, although it is influenced by
               how ‘max’ handles ‘NaN’, and also by the property
               "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               max ([USER_VALUE, X(1:2)])’, and ‘Y(end) = max
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = max ([X(1), X(1:2)])’, and
               ‘Y(end) = max ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = max ([X(end),
               X(1:2)])’, and ‘Y(end) = max ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmean: XREFmovmean, *note
     movmedian: XREFmovmedian, *note movmin: XREFmovmin, *note movprod:
     XREFmovprod, *note movstd: XREFmovstd, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movmean (X, WLEN)
 -- : Y = movmean (X, [NB, NA])
 -- : Y = movmean (..., DIM)
 -- : Y = movmean (..., "NANCOND")
 -- : Y = movmean (..., PROPERTY, VALUE)
     Calculate the moving average over a sliding window of length WLEN
     on data X.

     If WLEN is a scalar, the function ‘mean’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movmean’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movmean’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘mean’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               mean (X(1:2))’, and ‘Y(end) = mean (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = mean ([NaN, X(1:2)])’, and ‘Y(end) = mean
               ([X(end-1:end), NaN])’.  This option usually results in Y
               having ‘NaN’ values at the boundaries, although it is
               influenced by how ‘mean’ handles ‘NaN’, and also by the
               property "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               mean ([USER_VALUE, X(1:2)])’, and ‘Y(end) = mean
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = mean ([X(1), X(1:2)])’, and
               ‘Y(end) = mean ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = mean ([X(end),
               X(1:2)])’, and ‘Y(end) = mean ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note
     movmedian: XREFmovmedian, *note movmin: XREFmovmin, *note movprod:
     XREFmovprod, *note movstd: XREFmovstd, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movmedian (X, WLEN)
 -- : Y = movmedian (X, [NB, NA])
 -- : Y = movmedian (..., DIM)
 -- : Y = movmedian (..., "NANCOND")
 -- : Y = movmedian (..., PROPERTY, VALUE)
     Calculate the moving median over a sliding window of length WLEN on
     data X.

     If WLEN is a scalar, the function ‘movmedian’ is applied to a
     moving window of length WLEN.  When WLEN is an odd number the
     window is symmetric and includes ‘(WLEN - 1) / 2’ elements on
     either side of the central element.  For example, when calculating
     the output at index 5 with a window length of 3, ‘movmedian’ uses
     data elements ‘[4, 5, 6]’.  If WLEN is an even number, the window
     is asymmetric and has ‘WLEN/2’ elements to the left of the central
     element and ‘WLEN/2 - 1’ elements to the right of the central
     element.  For example, when calculating the output at index 5 with
     a window length of 4, ‘movmedian’ uses data elements
     ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘movmedian’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               movmedian (X(1:2))’, and ‘Y(end) = movmedian
               (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = movmedian ([NaN, X(1:2)])’, and ‘Y(end) = movmedian
               ([X(end-1:end), NaN])’.  This option usually results in Y
               having ‘NaN’ values at the boundaries, although it is
               influenced by how ‘movmedian’ handles ‘NaN’, and also by
               the property "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               movmedian ([USER_VALUE, X(1:2)])’, and ‘Y(end) =
               movmedian ([X(end-1:end), USER_VALUE])’.  A common choice
               for USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = movmedian ([X(1), X(1:2)])’,
               and ‘Y(end) = movmedian ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = movmedian ([X(end),
               X(1:2)])’, and ‘Y(end) = movmedian ([X(end-1:end),
               X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmin: XREFmovmin, *note movprod: XREFmovprod,
     *note movstd: XREFmovstd, *note movsum: XREFmovsum, *note movvar:
     XREFmovvar.

 -- : Y = movmin (X, WLEN)
 -- : Y = movmin (X, [NB, NA])
 -- : Y = movmin (..., DIM)
 -- : Y = movmin (..., "NANCOND")
 -- : Y = movmin (..., PROPERTY, VALUE)
     Calculate the moving minimum over a sliding window of length WLEN
     on data X.

     If WLEN is a scalar, the function ‘min’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movmin’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movmin’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘min’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               min (X(1:2))’, and ‘Y(end) = min (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = min ([NaN, X(1:2)])’, and ‘Y(end) = min ([X(end-1:end),
               NaN])’.  This option usually results in Y having ‘NaN’
               values at the boundaries, although it is influenced by
               how ‘min’ handles ‘NaN’, and also by the property
               "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               min ([USER_VALUE, X(1:2)])’, and ‘Y(end) = min
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = min ([X(1), X(1:2)])’, and
               ‘Y(end) = min ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = min ([X(end),
               X(1:2)])’, and ‘Y(end) = min ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmedian: XREFmovmedian, *note movprod:
     XREFmovprod, *note movstd: XREFmovstd, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movprod (X, WLEN)
 -- : Y = movprod (X, [NB, NA])
 -- : Y = movprod (..., DIM)
 -- : Y = movprod (..., "NANCOND")
 -- : Y = movprod (..., PROPERTY, VALUE)
     Calculate the moving product over a sliding window of length WLEN
     on data X.

     If WLEN is a scalar, the function ‘movprod’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movprod’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movprod’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘movprod’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               movprod (X(1:2))’, and ‘Y(end) = movprod (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = movprod ([NaN, X(1:2)])’, and ‘Y(end) = movprod
               ([X(end-1:end), NaN])’.  This option usually results in Y
               having ‘NaN’ values at the boundaries, although it is
               influenced by how ‘movprod’ handles ‘NaN’, and also by
               the property "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               movprod ([USER_VALUE, X(1:2)])’, and ‘Y(end) = movprod
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = movprod ([X(1), X(1:2)])’,
               and ‘Y(end) = movprod ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = movprod ([X(end),
               X(1:2)])’, and ‘Y(end) = movprod ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmedian: XREFmovmedian, *note movmin:
     XREFmovmin, *note movstd: XREFmovstd, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movstd (X, WLEN)
 -- : Y = movstd (X, [NB, NA])
 -- : Y = movstd (..., OPT)
 -- : Y = movstd (..., OPT, DIM)
 -- : Y = movstd (..., "NANCOND")
 -- : Y = movstd (..., PROPERTY, VALUE)
     Calculate the moving standard deviation over a sliding window of
     length WLEN on data X.

     If WLEN is a scalar, the function ‘movstd’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movstd’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movstd’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

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

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

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

     If the optional argument DIM is given, operate along this
     dimension.  The normalization argument OPT must be given before the
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘movstd’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               movstd (X(1:2))’, and ‘Y(end) = movstd (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = movstd ([NaN, X(1:2)])’, and ‘Y(end) = movstd
               ([X(end-1:end), NaN])’.  This option usually results in Y
               having ‘NaN’ values at the boundaries, although it is
               influenced by how ‘movstd’ handles ‘NaN’, and also by the
               property "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               movstd ([USER_VALUE, X(1:2)])’, and ‘Y(end) = movstd
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = movstd ([X(1), X(1:2)])’, and
               ‘Y(end) = movstd ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = movstd ([X(end),
               X(1:2)])’, and ‘Y(end) = movstd ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmedian: XREFmovmedian, *note movmin:
     XREFmovmin, *note movprod: XREFmovprod, *note movsum: XREFmovsum,
     *note movvar: XREFmovvar.

 -- : Y = movsum (X, WLEN)
 -- : Y = movsum (X, [NB, NA])
 -- : Y = movsum (..., DIM)
 -- : Y = movsum (..., "NANCOND")
 -- : Y = movsum (..., PROPERTY, VALUE)
     Calculate the moving sum over a sliding window of length WLEN on
     data X.

     If WLEN is a scalar, the function ‘movsum’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movsum’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movsum’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

     If the optional argument DIM is given, operate along this
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘movsum’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               movsum (X(1:2))’, and ‘Y(end) = movsum (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = movsum ([NaN, X(1:2)])’, and ‘Y(end) = movsum
               ([X(end-1:end), NaN])’.  This option usually results in Y
               having ‘NaN’ values at the boundaries, although it is
               influenced by how ‘movsum’ handles ‘NaN’, and also by the
               property "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               movsum ([USER_VALUE, X(1:2)])’, and ‘Y(end) = movsum
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = movsum ([X(1), X(1:2)])’, and
               ‘Y(end) = movsum ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = movsum ([X(end),
               X(1:2)])’, and ‘Y(end) = movsum ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmedian: XREFmovmedian, *note movmin:
     XREFmovmin, *note movprod: XREFmovprod, *note movstd: XREFmovstd,
     *note movvar: XREFmovvar.

 -- : Y = movvar (X, WLEN)
 -- : Y = movvar (X, [NB, NA])
 -- : Y = movvar (..., OPT)
 -- : Y = movvar (..., OPT, DIM)
 -- : Y = movvar (..., "NANCOND")
 -- : Y = movvar (..., PROPERTY, VALUE)
     Calculate the moving variance over a sliding window of length WLEN
     on data X.

     If WLEN is a scalar, the function ‘var’ is applied to a moving
     window of length WLEN.  When WLEN is an odd number the window is
     symmetric and includes ‘(WLEN - 1) / 2’ elements on either side of
     the central element.  For example, when calculating the output at
     index 5 with a window length of 3, ‘movvar’ uses data elements
     ‘[4, 5, 6]’.  If WLEN is an even number, the window is asymmetric
     and has ‘WLEN/2’ elements to the left of the central element and
     ‘WLEN/2 - 1’ elements to the right of the central element.  For
     example, when calculating the output at index 5 with a window
     length of 4, ‘movvar’ uses data elements ‘[3, 4, 5, 6]’.

     If WLEN is an array with two elements ‘[NB, NA]’, the function is
     applied to a moving window ‘-NB:NA’.  This window includes NB
     number of elements _before_ the current element and NA number of
     elements _after_ the current element.  The current element is
     always included.  For example, given ‘WLEN = [3, 0]’, the data used
     to calculate index 5 is ‘[2, 3, 4, 5]’.

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

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

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

     If the optional argument DIM is given, operate along this
     dimension.  The normalization argument OPT must be given before the
     dimension.

     The optional string argument "NANCOND" controls whether ‘NaN’ and
     ‘NA’ values should be included ("includenan"), or excluded
     ("omitnan"), from the data passed to ‘var’.  The default is
     "includenan".  Caution: the "omitnan" option is not yet
     implemented.

     The calculation can be controlled by specifying PROPERTY/VALUE
     pairs.  Valid properties are

     "Endpoints"

          This property controls how results are calculated at the
          boundaries (endpoints) of the window.  Possible values are:

          "shrink" (default)
               The window is truncated at the beginning and end of the
               array to exclude elements for which there is no source
               data.  For example, with a window of length 3, ‘Y(1) =
               var (X(1:2))’, and ‘Y(end) = var (X(end-1:end))’.

          "discard"
               Any Y values that use a window extending beyond the
               original data array are deleted.  For example, with a
               10-element data vector and a window of length 3, the
               output will contain only 8 elements.  The first element
               would require calculating the function over indices
               ‘[0, 1, 2]’ and is therefore discarded.  The last element
               would require calculating the function over indices
               ‘[9, 10, 11]’ and is therefore discarded.

          "fill"
               Any window elements outside the data array are replaced
               by ‘NaN’.  For example, with a window of length 3, ‘Y(1)
               = var ([NaN, X(1:2)])’, and ‘Y(end) = var ([X(end-1:end),
               NaN])’.  This option usually results in Y having ‘NaN’
               values at the boundaries, although it is influenced by
               how ‘var’ handles ‘NaN’, and also by the property
               "nancond".

          USER_VALUE
               Any window elements outside the data array are replaced
               by the specified value USER_VALUE which must be a numeric
               scalar.  For example, with a window of length 3, ‘Y(1) =
               var ([USER_VALUE, X(1:2)])’, and ‘Y(end) = var
               ([X(end-1:end), USER_VALUE])’.  A common choice for
               USER_VALUE is 0.

          "same"
               Any window elements outside the data array are replaced
               by the value of X at the boundary.  For example, with a
               window of length 3, ‘Y(1) = var ([X(1), X(1:2)])’, and
               ‘Y(end) = var ([X(end-1:end), X(end)])’.

          "periodic"
               The window is wrapped so that any missing data elements
               are taken from the other side of the data.  For example,
               with a window of length 3, ‘Y(1) = var ([X(end),
               X(1:2)])’, and ‘Y(end) = var ([X(end-1:end), X(1)])’.

     "SamplePoints"
          Caution: This option is not yet implemented.

     Programming Note: This function is a wrapper which calls ‘movfun’.
     For additional options and documentation, *note ‘movfun’:
     XREFmovfun.

     See also: *note movfun: XREFmovfun, *note movslice: XREFmovslice,
     *note movmad: XREFmovmad, *note movmax: XREFmovmax, *note movmean:
     XREFmovmean, *note movmedian: XREFmovmedian, *note movmin:
     XREFmovmin, *note movprod: XREFmovprod, *note movstd: XREFmovstd,
     *note movsum: XREFmovsum.


File: octave.info,  Node: Basic Statistical Functions,  Next: Correlation and Regression Analysis,  Prev: Statistics on Sliding Windows of Data,  Up: Statistics

26.3 Basic Statistical Functions
================================

Octave supports various helpful statistical functions.  Many are useful
as initial steps to prepare a data set for further analysis.  Others
provide different measures from those of the basic descriptive
statistics.

 -- : Y = center (X)
 -- : Y = center (X, DIM)
     Center data by subtracting its mean.

     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, operate along this
     dimension.

     Programming Note: ‘center’ has obvious application for normalizing
     statistical data.  It is also useful for improving the precision of
     general numerical calculations.  Whenever there is a large value
     that is common to a batch of data, the mean can be subtracted off,
     the calculation performed, and then the mean added back to obtain
     the final answer.

     See also: *note zscore: XREFzscore.

 -- : Z = zscore (X)
 -- : Z = zscore (X, OPT)
 -- : Z = zscore (X, OPT, DIM)
 -- : [Z, MU, SIGMA] = zscore (...)
     Compute the Z score of X.

     If X is a vector, subtract its mean and divide by its standard
     deviation.  If the standard deviation is zero, divide by 1 instead.

     The optional parameter OPT determines the normalization to use when
     computing the standard deviation and has the same definition as the
     corresponding parameter for ‘std’.

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

     The optional outputs MU and SIGMA contain the mean and standard
     deviation.

     See also: *note mean: XREFmean, *note std: XREFstd, *note center:
     XREFcenter.

 -- : Z = normalize (X)
 -- : Z = normalize (X, DIM)
 -- : Z = normalize (..., METHOD)
 -- : Z = normalize (..., METHOD, OPTION)
 -- : Z = normalize (..., SCALE, SCALEOPTION, CENTER, CENTEROPTION)
 -- : [Z, C, S] = normalize (...)
     Return a normalization of the data in X using one of several
     available scaling and centering methods.

     ‘normalize’ by default will return the ‘zscore’ of X, defined as
     the number of standard deviations each element is from the mean of
     X.  This is equivalent to centering at the mean of the data and
     scaling by the standard deviation.

     The returned value Z will have the same size as X.  The optional
     return variables C and S are the centering and scaling factors used
     in the normalization such that:

            Z = (X - C) ./ S

     If X is a vector, ‘normalize’ will operate on the data in X.

     If X is a matrix, ‘normalize’ will operate independently on each
     column in X.

     If X is an N-dimensional array, ‘normalize’ will operate
     independently on the first non-singleton dimension in X.

     If the optional second argument DIM is given, operate along this
     dimension.

     ‘normalize’ ignores NaN values is X similar to the behavior of the
     omitnan option in ‘std’, ‘mean’, and ‘median’.

     The optional inputs METHOD and OPTION can be used to specify the
     type of normalization performed on X.  Note that only the ‘scale’
     and ‘center’ options may be specified together using any of the
     methods defined below.  Valid normalization methods are:

     ‘zscore’
          (Default) Normalizes the elements in X to the scaled distance
          from a central value.  Valid Options:

          ‘std’
               (Default) Data is centered at ‘mean (X)’ and scaled by
               the standard deviation.

          ‘robust’
               Data is centered at ‘median (X)’ and scaled by the median
               absolute deviation.

     ‘norm’
          Z is the general vector norm of X, with OPTION being the
          normalization factor P that determines the vector norm type
          according to:

                 Z = [sum (abs (X) .^ P)] ^ (1/P)

          P can be any positive scalar, specific values being:

          ‘P = 1’
               X is normalized by ‘sum (abs (X))’.

          ‘P = 2’
               (Default) X is normalized by the Euclidian norm, or
               vector magnitude, of the elements.

          ‘P = Inf’
               X is normalized by ‘max (abs (X))’.

     ‘scale’
          X is scaled by a factor determined by OPTION, which can be a
          numeric scalar or one of the following:

          ‘std’
               (Default) X is scaled by its standard deviation.

          ‘mad’
               X is scaled by its median absolute deviation.

          ‘first’
               X is scaled by its first element.

          ‘iqr’
               X is scaled by its interquartile range.

     ‘range’
          X is scaled to fit the range specified by OPTION as a two
          element scalar row vector.  The default range is [0, 1].

     ‘center’
          X is shifted by an amount determined by OPTION, which can be a
          numeric scalar or one of the following:

          ‘mean’
               (Default) X is shifted by ‘mean (X)’.

          ‘median’
               X is shifted by ‘median (X)’.

     ‘medianiqr’
          X is shifted by ‘median (X)’ and scaled by the interquartile
          range.

     Known MATLAB incompatibilities:

       1. The option ‘DataVariables’ is not yet implemented for Table
          class X inputs.

     See also: *note zscore: XREFzscore, *note iqr: XREFiqr, *note norm:
     XREFnorm, *note rescale: XREFrescale, *note std: XREFstd, *note
     median: XREFmedian, *note mean: XREFmean, *note mad: XREFmad.

 -- : N = histc (X, EDGES)
 -- : N = histc (X, EDGES, DIM)
 -- : [N, IDX] = histc (...)
     Compute histogram counts.

     When X is a vector, the function counts the number of elements of X
     that fall in the histogram bins defined by EDGES.  This must be a
     vector of monotonically increasing values that define the edges of
     the histogram bins.  ‘N(k)’ contains the number of elements in X
     for which ‘EDGES(k) <= X < EDGES(k+1)’.  The final element of N
     contains the number of elements of X exactly equal to the last
     element of EDGES.

     When X is an N-dimensional array, the computation is carried out
     along dimension DIM.  If not specified DIM defaults to the first
     non-singleton dimension.

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

     See also: *note hist: XREFhist.

‘unique’ function documented at *note unique: XREFunique. is often
useful for statistics.

 -- : C = nchoosek (N, K)
 -- : C = nchoosek (SET, K)

     Compute the binomial coefficient of N or list all possible
     combinations of a SET of items.

     If N is a scalar then calculate the binomial coefficient of N and K
     which is defined as

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

     This is the number of combinations of N items taken in groups of
     size K.

     If the first argument is a vector, SET, then generate all
     combinations of the elements of SET, taken K at a time, with one
     row per combination.  The result C has K columns and
     ‘nchoosek (length (SET), K)’ rows.

     For example:

     How many ways can three items be grouped into pairs?

          nchoosek (3, 2)
             ⇒ 3

     What are the possible pairs?

          nchoosek (1:3, 2)
             ⇒  1   2
                 1   3
                 2   3

     Programming Note: When calculating the binomial coefficient
     ‘nchoosek’ works only for non-negative, integer arguments.  Use
     ‘bincoeff’ for non-integer and negative scalar arguments, or for
     computing many binomial coefficients at once with vector inputs for
     N or K.

     See also: *note bincoeff: XREFbincoeff, *note perms: XREFperms.

 -- : P = perms (V)
 -- : P = perms (V, "unique")
     Generate all permutations of vector V with one row per permutation.

     Results are returned in reverse lexicographic order if V is in
     ascending order.  If V is in a different permutation, then the
     result is permuted that way too.  Consequently, an input in
     descending order yields a result in normal lexicographic order.
     The result has size ‘factorial (N) * N’, where N is the length of
     V.  Any repeated elements are included in the output.

     If the optional argument "unique" is given then only unique
     permutations are returned, using less memory and taking less time
     than calling ‘unique (perms (V), "rows")’.

     Example 1

          perms ([1, 2, 3])
          ⇒
          3   2   1
          3   1   2
          2   3   1
          2   1   3
          1   3   2
          1   2   3

     Example 2

          perms ([1, 1, 2, 2], "unique")
          ⇒
          2   2   1   1
          2   1   2   1
          2   1   1   2
          1   2   2   1
          1   2   1   2
          1   1   2   2

     Programming Note: If the "unique" option is not used, the length of
     V should be no more than 10-12 to limit memory consumption.  Even
     with "unique", there should be no more than 10-12 unique elements
     in V.

     See also: *note permute: XREFpermute, *note randperm: XREFrandperm,
     *note nchoosek: XREFnchoosek.

 -- : Y = ranks (X)
 -- : Y = ranks (X, DIM)
 -- : Y = ranks (X, DIM, RTYPE)
     Return the ranks (in the sense of order statistics) of X along the
     first non-singleton dimension adjusted for ties.

     If the optional DIM argument is given, operate along this
     dimension.

     The optional parameter RTYPE determines how ties are handled.  All
     examples below assume an input of ‘[ 1, 2, 2, 4 ]’.

     0 or "fractional" (default) for fractional ranking (1, 2.5,
          2.5, 4);

     1 or "competition" for competition ranking (1, 2, 2, 4);

     2 or "modified" for modified competition ranking (1, 3, 3, 4);

     3 or "ordinal" for ordinal ranking (1, 2, 3, 4);

     4 or "dense" for dense ranking (1, 2, 2, 3).

     See also: *note spearman: XREFspearman, *note kendall: XREFkendall.

 -- : CNT = run_count (X, N)
 -- : CNT = run_count (X, N, DIM)
     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 then operate along this
     dimension.

     See also: *note runlength: XREFrunlength.

 -- : count = runlength (X)
 -- : [count, value] = runlength (X)
     Find the lengths of all sequences of common values.

     COUNT is a vector with the lengths of each repeated value.

     The optional output VALUE contains the value that was repeated in
     the sequence.

          runlength ([2, 2, 0, 4, 4, 4, 0, 1, 1, 1, 1])
          ⇒   2   1   3   1   4

     See also: *note run_count: XREFrun_count.


File: octave.info,  Node: Correlation and Regression Analysis,  Next: Distributions,  Prev: Basic Statistical Functions,  Up: Statistics

26.4 Correlation and Regression Analysis
========================================

 -- : C = cov (X)
 -- : C = cov (X, Y)
 -- : C = cov (..., OPT)
 -- : C = cov (..., NANFLAG)
     Compute the covariance matrix.

     The covariance between two variable vectors A and B is calculated
     as:

          cov (A,B) = 1/(N-1) * SUM_i (A(i) - mean (A)) * (B(i) - mean (B))

     where N is the length of the vectors A and B.

     If called with one argument, compute ‘cov (X, X)’.  If X is a
     vector, this is the scalar variance of X.  If X is a matrix, each
     row of X is treated as an observation, and each column as a
     variable, and the (I, J)-th entry of ‘cov (X)’ is the covariance
     between the I-th and J-th columns in X.  If X has dimensions n x m,
     the output C will be a m x m square covariance matrix.

     If called with two arguments, compute ‘cov (X, Y)’, the covariance
     between two random variables X and Y.  X and Y must have the same
     number of elements, and will be treated as vectors with the
     covariance computed as ‘cov (X(:), Y(:))’.  The output will be a 2
     x 2 covariance matrix.

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

     0 [default]:
          Normalize with N-1.  This provides the best unbiased estimator
          of the covariance.

     1:
          Normalize with N. This provides the second moment around the
          mean.  OPT is set to 1 for N = 1.

     The optional argument NANFLAG must appear last in the argument list
     and controls how NaN values are handled by ‘cov’.  The three valid
     values are:

     includenan [default]:
          Leave NaN values in X and Y.  Output will follow the normal
          rules for handling NaN values in arithmetic operations.

     omitrows:
          Rows containing NaN values are trimmed from both X and Y prior
          to calculating the covariance.  A NaN in one variable will
          remove that row from both X and Y.

     partialrows:
          Rows containing NaN values are ignored from both X and Y
          independently for each I-th and J-th covariance calculation.
          This may result in a different number of observations, N,
          being used to calculated each element of the covariance
          matrix.

     Compatibility Note: Previous versions of ‘cov’ treated rows X and Y
     as multivariate random variables.  This version attempts to
     maintain full compatibility with MATLAB by treating X and Y as two
     univariate distributions regardless of shape, resulting in a 2x2
     output matrix.  Code relying on Octave's previous definition will
     need to be modified when running this newer version of ‘cov’.  The
     previous behavior can be obtained by using the NaN package's ‘covm’
     function as ‘covm (X, Y, "D")’.

     See also: *note corr: XREFcorr.

 -- : R = corr (X)
 -- : R = corr (X, Y)
     Compute matrix of correlation coefficients.

     If each row of X and Y is an observation and each column is a
     variable, then the (I, J)-th entry of ‘corr (X, Y)’ is the
     correlation between the I-th variable in X and the J-th variable in
     Y.  X and Y must have the same number of rows (observations).

          corr (X,Y) = cov (X,Y) / (std (X) * std (Y))

     If called with one argument, compute ‘corr (X, X)’, the correlation
     between the columns of X.

     See also: *note cov: XREFcov.

 -- : R = corrcoef (X)
 -- : R = corrcoef (X, Y)
 -- : R = corrcoef (..., PARAM, VALUE, ...)
 -- : [R, P] = corrcoef (...)
 -- : [R, P, LCI, HCI] = corrcoef (...)
     Compute a matrix of correlation coefficients.

     X is an array where each column contains a variable and each row is
     an observation.

     If a second input Y (of the same size as X) is given then calculate
     the correlation coefficients between X and Y.

     PARAM, VALUE are optional pairs of parameters and values which
     modify the calculation.  Valid options are:

     "alpha"
          Confidence level used for the bounds of the confidence
          interval, LCI and HCI.  Default is 0.05, i.e., 95% confidence
          interval.

     "rows"
          Determine processing of NaN values.  Acceptable values are
          "all", "complete", and "pairwise".  Default is "all".  With
          "complete", only the rows without NaN values are considered.
          With "pairwise", the selection of NaN-free rows is made for
          each pair of variables.

     Output R is a matrix of Pearson's product moment correlation
     coefficients for each pair of variables.

     Output P is a matrix of pair-wise p-values testing for the null
     hypothesis of a correlation coefficient of zero.

     Outputs LCI and HCI are matrices containing, respectively, the
     lower and higher bounds of the 95% confidence interval of each
     correlation coefficient.

     See also: *note corr: XREFcorr, *note cov: XREFcov, *note std:
     XREFstd.

 -- : RHO = spearman (X)
 -- : RHO = spearman (X, Y)
     Compute Spearman's rank correlation coefficient RHO.

     For two data vectors X and Y, Spearman's RHO is the correlation
     coefficient 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)’, where N is the length of the X and
     Y vectors, and is asymptotically normally distributed.

     ‘spearman (X)’ is equivalent to ‘spearman (X, X)’.

     See also: *note ranks: XREFranks, *note kendall: XREFkendall.

 -- : TAU = kendall (X)
 -- : TAU = kendall (X, Y)
     Compute Kendall's TAU.

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

     ‘kendall (X)’ is equivalent to ‘kendall (X, X)’.

     See also: *note ranks: XREFranks, *note spearman: XREFspearman.


File: octave.info,  Node: Distributions,  Next: Random Number Generation,  Prev: Correlation and Regression Analysis,  Up: Statistics

26.5 Distributions
==================

Octave has functions for computing the Probability Density Function
(PDF), the Cumulative Distribution function (CDF), and the quantile (the
inverse of the CDF) for arbitrary user-defined distributions (discrete)
and for experimental data (empirical).

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

Distribution           PDF               CDF               Quantile
-----------------------------------------------------------------------------
Univariate Discrete    ‘discrete_pdf’    ‘discrete_cdf’    ‘discrete_inv’
Distribution
Empirical              ‘empirical_pdf’   ‘empirical_cdf’   ‘empirical_inv’
Distribution

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

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

 -- : Q = discrete_inv (X, V, P)
     For each element 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.

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

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

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


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

26.6 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
-----------------------------------------------------
Univariate Discrete           ‘discrete_rnd’
Distribution
Empirical Distribution        ‘empirical_rnd’
Exponential Distribution      ‘rande’
Gamma Distribution            ‘randg’
Poisson Distribution          ‘randp’
Standard Normal               ‘randn’
Distribution
Uniform Distribution          ‘rand’
Uniform Distribution          ‘randi’
(integers)

 -- : RND = discrete_rnd (V, P)
 -- : RND = discrete_rnd (V, P, R)
 -- : RND = discrete_rnd (V, P, R, C, ...)
 -- : RND = discrete_rnd (V, P, [SZ])
     Return a matrix of random samples from the univariate distribution
     which assumes the values in V with probabilities P.

     When called with a single size argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The size may also be specified with a vector of
     dimensions SZ.

     If no size arguments are given then the result matrix is the common
     size of V and P.

 -- : RND = empirical_rnd (DATA)
 -- : RND = empirical_rnd (DATA, R)
 -- : RND = empirical_rnd (DATA, R, C, ...)
 -- : RND = empirical_rnd (DATA, [SZ])
     Return a matrix of random samples from the empirical distribution
     obtained from the univariate sample DATA.

     When called with a single size argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The size may also be specified with a vector of
     dimensions SZ.

     If no size arguments are given then the result matrix is a random
     ordering of the sample DATA.


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

27 Sets
*******

Octave has a number of functions for managing sets of data.  A set is
defined as a collection of unique elements and is typically represented
by a vector of numbers sorted in ascending order.  Any vector or matrix
can be converted to a set by removing duplicates through the use of the
‘unique’ function.  However, it isn't necessary to explicitly create a
set as all of the functions which operate on sets will convert their
input to a set before proceeding.

 -- : Y = unique (X)
 -- : Y = unique (X, "rows")
 -- : Y = unique (..., "sorted")
 -- : Y = unique (..., "stable")
 -- : [Y, I, J] = unique (...)
 -- : [Y, I, J] = unique (..., "first")
 -- : [Y, I, J] = unique (..., "last")
 -- : [Y, I, J] = unique (..., "legacy")
     Return the unique elements of X.

     If the input X is a column vector then return a column vector;
     Otherwise, return a row vector.  X may also be a cell array of
     strings.

     If the optional argument "rows" is given then return the unique
     rows of X.  The input must be a 2-D numeric matrix to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input X.

     If requested, return column index vectors I and J such that ‘Y =
     X(I)’ and ‘X = Y(J)’.

     Additionally, if I is a requested output then one of the flags
     "first" or "last" may be given.  If "last" is specified, return the
     highest possible indices in I, otherwise, if "first" is specified,
     return the lowest.  The default is "first".

     Example 1 : sort order

          unique ([3, 1, 1, 2])
          ⇒ [1, 2, 3]
          unique ([3, 1, 1, 2], "stable")
          ⇒ [3, 1, 2]

     Example 2 : index selection

          [~, I] = unique ([3, 1, 1, 2], "first")
          ⇒ I = [2; 4; 1]
          [~, I] = unique ([3, 1, 1, 2], "last")
          ⇒ I = [3; 4; 1]

     Programming Notes: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.  Specifically,
     The index ordering flag is changed to "last", and the shape of the
     outputs I, J will follow the shape of the input X rather than
     always being column vectors.

     The third output, J, has not been implemented yet when the sort
     order is "stable".

     See also: *note uniquetol: XREFuniquetol, *note union: XREFunion,
     *note intersect: XREFintersect, *note setdiff: XREFsetdiff, *note
     setxor: XREFsetxor, *note ismember: XREFismember.

 -- : C = uniquetol (A)
 -- : C = uniquetol (A, TOL)
 -- : C = uniquetol (..., PROPERTY, VALUE)
 -- : [C, IA, IC] = uniquetol (...)
     Return the unique elements of A within tolerance TOL.

     Two values, X and Y, are within relative tolerance if ‘abs (X - Y)
     <= TOL * max (abs (A(:)))’.

     The input A must be a real (non-complex) floating point type
     (double or single).

     If TOL is unspecified, the default tolerance is 1e-12 for double
     precision input or 1e-6 for single precision input.

     The function may also be called with the following optional
     property/value pairs.  Property/value pairs must be passed after
     other input arguments:

     "ByRows" (default: ‘false’)
          When true, return the unique rows of A.  A must be a 2-D array
          to use this option.  For rows, the criteria for uniqueness is
          changed to ‘all (abs (X - Y) <= TOL*max (abs (A),[],1))’ which
          compares each column component of a row against a
          column-specific tolerance.

     "DataScale"
          The tolerance test is changed to ‘abs (X - Y) <= TOL*DS’ where
          DS is a scalar unless the property "ByRows" is true.  In that
          case, DS can either be a scalar or a vector with a length
          equal to the number of columns in A.  Using a value of ‘1.0’
          for DS will change the tolerance from a relative one to an
          absolute tolerance.  Using a value of ‘Inf’ will disable
          testing.

     "OutputAllIndices" (default: ‘false’)
          When true, IA is a cell array (not a vector) that contains the
          indices for _all_ elements in A that are within tolerance of a
          value in C.  That is, each cell in IA corresponds to a single
          unique value in C, and the values in each cell correspond to
          locations in A.

     The output C is a row vector if the input A is a row vector.  For
     all other cases, a column vector is returned.

     The optional output IA is a column index vector such that ‘C =
     A(IA)’.  If the "ByRows" property is true, the condition is ‘C =
     A(IA, :)’.  If the "OutputAllIndices" property is true, then the
     values ‘A(IA{I})’ are all within tolerance of the unique value
     ‘C(I)’.

     The optional output IC is a column index vector such that ‘A =
     C(IC)’ when A is a vector.  When A is a matrix, ‘A(:) = C(IC)’.  If
     the "ByRows" property is true then ‘A = C(IC,:)’.

     Example: small round-off errors require ‘uniquetol’, not ‘unique’

          x = [1:5];
          ## Inverse_Function (Function (x)) should return exactly x
          y = exp (log (x));
          D = unique ([x, y])
          ⇒ [1   2   3   3   4   5   5]
          C = uniquetol ([x, y])
          ⇒ [1   2   3   4   5]

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setdiff: XREFsetdiff, *note setxor:
     XREFsetxor, *note ismember: XREFismember.

* Menu:

* Set Operations::


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

27.1 Set Operations
===================

Octave supports several basic set operations.  Octave can compute the
union, intersection, and difference of two sets.  Octave also supports
the _Exclusive Or_ set operation.

   The functions for set operations all work in the same way by
accepting two input sets and returning a third set.  As an example,
assume that ‘a’ and ‘b’ contains two sets, then

     union (a, b)

computes the union of the two sets.

   Finally, determining whether elements belong to a set can be done
with the ‘ismember’ function.  Because sets are ordered this operation
is very efficient and is of order O(log2(n)) which is preferable to the
‘find’ function which is of order O(n).

 -- : C = intersect (A, B)
 -- : C = intersect (A, B, "rows")
 -- : C = intersect (..., "sorted")
 -- : C = intersect (..., "stable")
 -- : C = intersect (..., "legacy")
 -- : [C, IA, IB] = intersect (...)

     Return the unique elements common to both A and B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return the common rows
     of A and B.  The inputs must be 2-D numeric matrices to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     If requested, return column index vectors IA and IB such that ‘C =
     A(IA)’ and ‘C = B(IB)’.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     setdiff: XREFsetdiff, *note setxor: XREFsetxor, *note ismember:
     XREFismember.

 -- : C = union (A, B)
 -- : C = union (A, B, "rows")
 -- : C = union (..., "sorted")
 -- : C = union (..., "stable")
 -- : C = union (..., "legacy")
 -- : [C, IA, IB] = union (...)

     Return the unique elements that are in either A or B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return rows that are in
     either A or B.  The inputs must be 2-D numeric matrices to use this
     option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     The optional outputs IA and IB are column index vectors such that
     ‘A(IA)’ and ‘B(IB)’ are disjoint sets whose union is C.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note intersect: XREFintersect,
     *note setdiff: XREFsetdiff, *note setxor: XREFsetxor, *note
     ismember: XREFismember.

 -- : C = setdiff (A, B)
 -- : C = setdiff (A, B, "rows")
 -- : C = setdiff (..., "sorted")
 -- : C = setdiff (..., "stable")
 -- : C = setdiff (..., "legacy")
 -- : [C, IA] = setdiff (...)
     Return the unique elements in A that are not in B.

     If A is a row vector return a row vector; Otherwise, return a
     column vector.  The inputs may also be cell arrays of strings.

     If the optional input "rows" is given then return the rows in A
     that are not in B.  The inputs must be 2-D numeric matrices to use
     this option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     If requested, return the index vector IA such that ‘C = A(IA)’.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setxor: XREFsetxor, *note ismember:
     XREFismember.

 -- : C = setxor (A, B)
 -- : C = setxor (A, B, "rows")
 -- : C = setxor (..., "sorted")
 -- : C = setxor (..., "stable")
 -- : C = setxor (..., "legacy")
 -- : [C, IA, IB] = setxor (...)

     Return the unique elements exclusive to sets A or B.

     If A and B are both row vectors then return a row vector;
     Otherwise, return a column vector.  The inputs may also be cell
     arrays of strings.

     If the optional input "rows" is given then return the rows
     exclusive to sets A and B.  The inputs must be 2-D numeric matrices
     to use this option.

     The optional argument "sorted"/"stable" controls the order in which
     unique values appear in the output.  The default is "sorted" and
     values in the output are placed in ascending order.  The
     alternative "stable" preserves the order found in the input.

     The optional outputs IA and IB are column index vectors such that
     ‘A(IA)’ and ‘B(IB)’ are disjoint sets whose union is C.

     Programming Note: The input flag "legacy" changes the algorithm to
     be compatible with MATLAB releases prior to R2012b.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setdiff: XREFsetdiff, *note
     ismember: XREFismember.

 -- : TF = ismember (A, S)
 -- : TF = ismember (A, S, "rows")
 -- : [TF, S_IDX] = ismember (...)

     Return a logical matrix TF with the same shape as A which is true
     (1) if the element in A is found in S and false (0) if it is not.

     If a second output argument is requested then the index into S of
     each matching element 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
               ⇒ s_idx = 1

     If the optional third argument "rows" is given then compare rows in
     A with rows in S.  The inputs must be 2-D matrices with the same
     number of columns to use this option.

          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 lookup: XREFlookup, *note unique: XREFunique, *note
     union: XREFunion, *note intersect: XREFintersect, *note setdiff:
     XREFsetdiff, *note setxor: XREFsetxor, *note ismembertol:
     XREFismembertol.

 -- : TF = ismembertol (A, S)
 -- : TF = ismembertol (A, S, TOL)
 -- : TF = ismembertol (A, S, NAME, VALUE)
 -- : [TF, S_IDX] = ismembertol (...)
     Check if values are members of a set within a tolerance.

     This functions returns a logical matrix TF with the same shape as A
     which is true (1) where the element in A is close to S within a
     tolerance TOL and false (0) if it is not.  If TOL is not specified,
     a default tolerance of ‘1e-6’ is used.

     If a second output argument is requested then the index into S of
     each matching element is also returned.

     The inputs A and S must be numeric values.

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

     Optional property/value pairs may be given to change the function's
     behavior.  The property may be one of following strings:

     "ByRows"
          If set to ‘false’ (default), all elements in A and S are
          treated separately.  If set to ‘true’, TF will be ‘true’ for
          each row in A that matches a row in S within the given
          tolerance.  Two rows, U and V, are within tolerance if they
          fulfill the condition ‘all (abs (u-v) <= tol*max (abs
          ([a;s])))’.

     "OutputAllIndices"
          If set to ‘false’ (default), S_IDX contains indices for one of
          the matches.  If set to ‘true’, S_IDX is a cell array
          containing the indices for all elements in S that are within
          tolerance of the corresponding value in A.

     "DataScale"
          The provided value DS is used to change the scale factor in
          the tolerance test to ‘abs (u-v) <= tol*DS’.  By default, the
          maximum absolute value in A and S is used as the scale factor.

     Example:

          s = [1:6].' * pi;
          a = 10.^log10 (x);
          [tf, s_idx] = ismembertol (a, s);

     See also: *note ismember: XREFismember, *note lookup: XREFlookup,
     *note unique: XREFunique, *note union: XREFunion, *note intersect:
     XREFintersect, *note setdiff: XREFsetdiff, *note setxor:
     XREFsetxor.

 -- : P = powerset (A)
 -- : P = powerset (A, "rows")
     Compute the powerset (all subsets) of the set A.

     The set A must be a numerical matrix or a cell array of strings.
     The output will always be a cell array of either vectors or
     strings.

     With the optional argument "rows", each row of the set A is
     considered one element of the set.  The input must be a 2-D numeric
     matrix to use this argument.

     See also: *note unique: XREFunique, *note union: XREFunion, *note
     intersect: XREFintersect, *note setdiff: XREFsetdiff, *note setxor:
     XREFsetxor, *note ismember: XREFismember.


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

28 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 / Integrals / Transforms::
* Polynomial Interpolation::
* Miscellaneous Functions::


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

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

 -- : Y = polyval (P, X)
 -- : Y = polyval (P, X, [], MU)
 -- : [Y, DY] = polyval (P, X, S)
 -- : [Y, DY] = polyval (P, X, S, MU)

     Evaluate the polynomial P at the specified values of X.

     If X is a vector or matrix, the polynomial is evaluated for each of
     the elements of X.

     When MU is present, evaluate the polynomial for
     (X - MU(1)) / MU(2).

     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 from ‘polyfit’,
     must be supplied.

     See also: *note polyvalm: XREFpolyvalm, *note polyaffine:
     XREFpolyaffine, *note polyfit: XREFpolyfit, *note roots: XREFroots,
     *note poly: XREFpoly.

 -- : Y = 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 used in ‘polyval’.

     The argument X must be a square matrix.

     See also: *note polyval: XREFpolyval, *note roots: XREFroots, *note
     poly: XREFpoly.


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

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

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

 -- : R = roots (C)

     Compute the roots of the polynomial C.

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

          c(1) * x^(N-1) + ... + c(N-1) * x + c(N)

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

          p(x) = x^2 - 5.

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

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

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

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

     Solve the polynomial eigenvalue problem of degree L.

     Given an NxN matrix polynomial

     ‘C(S) = C0 + C1 S + ... + CL S^L’

     ‘polyeig’ solves the eigenvalue problem

     ‘(C0 + C1 Z + ... + CL Z^L) V = 0’.

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

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

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

     The companion matrix is

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

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

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

 -- : [MULTP, IDXP] = mpoles (P)
 -- : [MULTP, IDXP] = mpoles (P, TOL)
 -- : [MULTP, IDXP] = mpoles (P, TOL, REORDER)
     Identify unique poles in P and their associated multiplicity.

     By default, the output is ordered from the pole with the largest
     magnitude to the smallest magnitude.

     Two poles are considered to be multiples if the difference between
     them is less than the relative tolerance TOL.

          abs (P1 - P0) / abs (P0) < TOL

     If the pole is 0 then no scaling is done and TOL is interpreted as
     an absolute tolerance.  The default value for TOL is 0.001.

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

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

     For example:

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

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


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

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

 -- : Y = conv (A, B)
 -- : Y = conv (A, B, SHAPE)
     Convolve two vectors A and B.

     When A and B are the coefficient vectors of two polynomials, the
     convolution represents the coefficient vector of the product
     polynomial.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

     SHAPE = "full"
          Return the full convolution.  (default) The result is a vector
          with length equal to ‘length (A) + length (B) - 1’.

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

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

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

 -- : C = convn (A, B)
 -- : C = convn (A, B, SHAPE)
     Return the n-D convolution of A and B.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

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

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

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

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

 -- : B = deconv (Y, A)
 -- : [B, R] = deconv (Y, A)
     Deconvolve two vectors (polynomial division).

     ‘[B, R] = deconv (Y, A)’ solves for B and R such that ‘Y = conv (A,
     B) + R’.

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

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

 -- : C = conv2 (A, B)
 -- : C = conv2 (V1, V2, M)
 -- : C = conv2 (..., SHAPE)
     Return the 2-D convolution of A and B.

     The size of the result is determined by the optional SHAPE argument
     which takes the following values

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

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

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

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

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

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

     Find the greatest common divisor of two polynomials.

     This is equivalent to the polynomial found by multiplying together
     all the common roots.  Together with deconv, you can reduce a ratio
     of two polynomials.

     The tolerance TOL defaults to ‘sqrt (eps)’.

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

     Example code:

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

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

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

     The quotient is defined as

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

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

     For example,

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

     which represents the following partial fraction expansion

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

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

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

     For example:

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

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

     Alternatively the multiplicity may be defined explicitly, for
     example,

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

     which represents the following partial fraction expansion

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

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


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

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

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

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

 -- : K = polyder (P)
 -- : K = polyder (A, B)
 -- : [Q, D] = polyder (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by the vector P.

     If a pair of polynomials is given, return the derivative of the
     product A*B.

     If two inputs and two outputs are given, return the derivative of
     the polynomial quotient B/A.  The quotient numerator is in Q and
     the denominator in D.

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

 -- : Q = polyint (P)
 -- : Q = polyint (P, K)
     Return the coefficients of the integral of the polynomial whose
     coefficients are represented by the vector P.

     The variable K is the constant of integration, which by default is
     set to zero.

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

 -- : G = polyaffine (F, MU)
     Return the coefficients of the polynomial vector F after an affine
     transformation.

     If F is the vector representing the polynomial f(x), then ‘G =
     polyaffine (F, MU)’ is the vector representing:

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

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


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

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

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

 -- : P = polyfit (X, Y, N)
 -- : [P, S] = polyfit (X, Y, N)
 -- : [P, S, MU] = polyfit (X, Y, N)
     Return the coefficients of a polynomial P(X) of degree N that
     minimizes the least-squares-error of the fit to the points ‘[X(:),
     Y(:)]’.

     N is typically an integer ≥ 0 specifying the degree of the
     approximating polynomial.  If N is a logical vector, it is used as
     a mask to selectively force the corresponding polynomial
     coefficients to be used or ignored.

     The polynomial coefficients are returned in the row vector P.  The
     output P may be directly used with ‘polyval’ to estimate values
     using the fitted polynomial.

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

     ‘yf’
          The values of the polynomial for each value of X.

     ‘X’
          The Vandermonde matrix used to compute the polynomial
          coefficients.

     ‘R’
          Triangular factor R from the QR decomposition.

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

     ‘df’
          The degrees of freedom.

     ‘normr’
          The norm of the residuals.

     The second output may be used by ‘polyval’ to calculate the
     statistical error limits of the predicted values.  In particular,
     the standard deviation of P coefficients is given by

     ‘sqrt (diag (S.C)/S.DF) * S.NORMR’.

     When the third output, MU, is present the original data is centered
     and scaled which can improve the numerical stability of the fit.
     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).

     Example 1 : logical N and integer N

          f = @(x) x.^2 + 5;   # data-generating function
          x = 0:5;
          y = f (x);
          ## Fit data to polynomial A*x^3 + B*x^1
          p = polyfit (x, y, logical ([1, 0, 1, 0]))
          ⇒ p = [ 0.0680, 0, 4.2444, 0 ]
          ## Fit data to polynomial using all terms up to x^3
          p = polyfit (x, y, 3)
          ⇒ p = [ -4.9608e-17, 1.0000e+00, -3.3813e-15, 5.0000e+00 ]

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

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

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

     Fit a piecewise cubic spline with breaks (knots) BREAKS to the
     noisy data, X and Y.

     X is a vector, and Y is a vector or N-D array.  If Y is an N-D
     array, then X(j) is matched to Y(:,...,:,j).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   A very specific form of polynomial interpretation is the Padé
approximant.  For control systems, a continuous-time delay can be
modeled very simply with the approximant.

 -- : [NUM, DEN] = padecoef (T)
 -- : [NUM, DEN] = padecoef (T, N)
     Compute the Nth-order Padé approximant of the continuous-time delay
     T in transfer function form.

     The Padé approximant of ‘exp (-sT)’ is defined by the following
     equation

                       Pn(s)
          exp (-sT) ~ -------
                       Qn(s)

     Where both Pn(s) and Qn(s) are Nth-order rational functions defined
     by the following expressions

                   N    (2N - k)!N!        k
          Pn(s) = SUM --------------- (-sT)
                  k=0 (2N)!k!(N - k)!

          Qn(s) = Pn(-s)

     The inputs T and N must be non-negative numeric scalars.  If N is
     unspecified it defaults to 1.

     The output row vectors NUM and DEN contain the numerator and
     denominator coefficients in descending powers of s.  Both are
     Nth-order polynomials.

     For example:

          t = 0.1;
          n = 4;
          [num, den] = padecoef (t, n)
          ⇒ num =

                1.0000e-04  -2.0000e-02   1.8000e+00  -8.4000e+01   1.6800e+03

          ⇒ den =

                1.0000e-04   2.0000e-02   1.8000e+00   8.4000e+01   1.6800e+03

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

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

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

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

     Construct a piecewise polynomial (pp) structure from sample points
     BREAKS and coefficients COEFS.

     BREAKS must be a vector of strictly increasing values.  The number
     of intervals is given by ‘NI = length (BREAKS) - 1’.

     When M is the polynomial order COEFS must be of size:
     NI-by-(M + 1).

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

     COEFS may also be a multi-dimensional array, specifying a
     vector-valued or array-valued polynomial.  In that case the
     polynomial order M is defined by the length of the last dimension
     of COEFS.  The size of first dimension(s) are given by the scalar
     or vector D.  If D is not given it is set to ‘1’.  In this case
     ‘P(R, I, :)’ contains the coefficients for the R-th polynomial
     defined on interval I.  In any case COEFS is reshaped to a 2-D
     matrix of size ‘[NI*prod(D) M]’.

     Programming Note: ‘ppval’ evaluates polynomials at ‘XI -
     BREAKS(i)’, i.e., it subtracts the lower endpoint of the current
     interval from XI.  This must be taken into account when creating
     piecewise polynomials objects with ‘mkpp’.

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

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

     Extract the components of a piecewise polynomial structure PP.

     This function is the inverse of ‘mkpp’: it extracts the inputs to
     ‘mkpp’ needed to create the piecewise polynomial structure PP.  The
     code below makes this relation explicit:

          [breaks, coefs, numinter, order, dim] = unmkpp (pp);
          pp2  = mkpp (breaks, coefs, dim);

     The piecewise polynomial structure ‘pp2’ obtained in this way, is
     identical to the original ‘pp’.  The same can be obtained by
     directly accessing the fields of the structure ‘pp’.

     The components are:

     X
          Sample points or breaks.

     P
          Polynomial coefficients for points in sample interval.  ‘P(I,
          :)’ contains the coefficients for the polynomial over interval
          I ordered from highest to lowest degree.  If ‘D > 1’, then P
          is a matrix of size ‘[N*prod(D) M]’, where the ‘I + (1:D)’
          rows are the coefficients of all the D polynomials in the
          interval I.

     N
          Number of polynomial pieces or intervals, ‘N = length (X) -
          1’.

     K
          Order of the polynomial plus 1.

     D
          Number of polynomials defined for each interval.

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

 -- : YI = ppval (PP, XI)
     Evaluate the piecewise polynomial structure PP at the points XI.

     If PP describes a scalar polynomial function, the result is an
     array of the same shape as XI.  Otherwise, the size of the result
     is ‘[pp.dim, length(XI)]’ if XI is a vector, or ‘[pp.dim,
     size(XI)]’ if it is a multi-dimensional array.

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

 -- : ppd = ppder (pp)
 -- : ppd = ppder (pp, m)
     Compute the piecewise M-th derivative of a piecewise polynomial
     struct PP.

     If M is omitted the first derivative is calculated.

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

 -- : PPI = ppint (PP)
 -- : PPI = ppint (PP, C)
     Compute the integral of the piecewise polynomial struct PP.

     C, if given, is the constant of integration.

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

 -- : JUMPS = ppjumps (PP)
     Evaluate the boundary jumps of a piecewise polynomial.

     If there are n intervals, and the dimensionality of PP is d, the
     resulting array has dimensions ‘[d, n-1]’.

     See also: *note mkpp: XREFmkpp.


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

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

 -- : Y = poly (A)
 -- : Y = poly (X)
     If A is a square N-by-N matrix, ‘poly (A)’ is the row vector of the
     coefficients of ‘det (z * eye (N) - A)’, the characteristic
     polynomial of A.

     For example, the following code finds the eigenvalues of A which
     are the roots of ‘poly (A)’.

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

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

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

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

 -- : polyout (C)
 -- : polyout (C, X)
 -- : STR = polyout (...)
     Display a formatted version of the polynomial C.

     The formatted polynomial

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

     is returned as a string or written to the screen if ‘nargout’ is
     zero.

     The second argument X specifies the variable name to use for each
     term and defaults to the string "s".

     See also: *note polyreduce: XREFpolyreduce.

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

     See also: *note polyout: XREFpolyout.


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

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

* Menu:

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


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

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

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

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

     One-dimensional interpolation.

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

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

     "previous"
          Return the previous neighbor.

     "next"
          Return the next neighbor.

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

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

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

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

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

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

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

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

     An example of the use of ‘interp1’ is

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

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

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

   This can be demonstrated by the code

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

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

 -- : Y = interpft (X, N)
 -- : Y = interpft (X, N, DIM)

     Fourier interpolation.

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

     If DIM is specified, then interpolate along the dimension DIM.

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

     See also: *note interp1: XREFinterp1.

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

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

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

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

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

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

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

     The variable X must be a vector of length N.

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

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

     See also: *note pchip: XREFpchip, *note ppval: XREFppval, *note
     mkpp: XREFmkpp, *note unmkpp: XREFunmkpp.


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

29.2 Multi-dimensional Interpolation
====================================

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

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

     Two-dimensional interpolation.

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

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

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

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

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

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

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

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

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

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

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

     Three-dimensional interpolation.

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

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

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

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

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

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

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

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

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

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

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

     Each element of the N-dimensional array V represents a value at a
     location given by the parameters X1, X2, ..., XN.  The parameters
     X1, X2, ..., XN are either N-dimensional arrays of the same size as
     the array V in the "ndgrid" format or vectors.

     The parameters Y1, Y2, ..., YN represent the points at which the
     array VI is interpolated.  They can be vectors of the same length
     and orientation in which case they are interpreted as coordinates
     of scattered points.  If they are vectors of differing orientation
     or length, they are used to form a grid in "ndgrid" format.  They
     can also be N-dimensional arrays of equal size.

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

     The interpolation METHOD is one of:

     "nearest"
          Return the nearest neighbor.

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

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

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

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

     The default method is "linear".

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

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

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

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

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


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

30 Geometry
***********

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

* Menu:

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

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

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


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

30.1 Delaunay Triangulation
===========================

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

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

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

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

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

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

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

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

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

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

   For 3-D inputs ‘delaunay’ returns a set of tetrahedra that satisfy
the Delaunay circum-circle criteria.  Similarly, ‘delaunayn’ returns the
N-dimensional simplex satisfying the Delaunay circum-circle criteria.
The N-dimensional extension of a triangulation is called a tessellation.

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

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

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

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

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

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

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

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

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

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

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

* Menu:

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


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

30.1.1 Plotting the Triangulation
---------------------------------

Octave has the functions ‘triplot’, ‘trimesh’, and ‘trisurf’ to plot the
Delaunay triangulation of a 2-dimensional set of points.  ‘tetramesh’
will plot the triangulation of a 3-dimensional set of points.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

30.1.2 Identifying Points in Triangulation
------------------------------------------

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

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

     P = BETA * T

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

     sum (BETA) == 1

is imposed, and we can therefore write the above as

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

Solving for BETA we can then write

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

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

     0 <= BETA(I) <= 1

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

 -- : IDX = tsearch (X, Y, T, XI, YI)
     Search for the enclosing Delaunay convex hull.

     For ‘T = delaunay (X, Y)’, finds the index in T containing the
     points ‘(XI, YI)’.  For points outside the convex hull, IDX is NaN.

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

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

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

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

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

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

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

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

     tsearch (X, Y, TRI, -0.5, -0.5)
     ⇒ 1
     tsearch (X, Y, TRI, 0.5, 0.5)
     ⇒ 2

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

     tsearch (X, Y, TRI, 2, 2)
     ⇒ NaN

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

 -- : IDX = dsearch (X, Y, TRI, XI, YI)
 -- : IDX = dsearch (X, Y, TRI, XI, YI, S)
     Return the index IDX of the closest point in ‘X, Y’ to the elements
     ‘[XI(:), YI(:)]’.

     The variable S is accepted for compatibility but is ignored.

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

 -- : IDX = dsearchn (X, TRI, XI)
 -- : IDX = dsearchn (X, TRI, XI, OUTVAL)
 -- : IDX = dsearchn (X, XI)
 -- : [IDX, D] = dsearchn (...)
     Return the index IDX of the closest point in X to the elements XI.

     If OUTVAL is supplied, then the values of XI that are not contained
     within one of the simplices TRI are set to OUTVAL.  Generally, TRI
     is returned from ‘delaunayn (X)’.

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

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

   An example of the use of ‘dsearch’, using the above values of X, Y
and TRI is

     dsearch (X, Y, TRI, -2, -2)
     ⇒ 1

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

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

where the point outside the tessellation are then flagged with ‘NaN’.


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

30.2 Voronoi Diagrams
=====================

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

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

     The Voronoi facets with points at infinity are not drawn.

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

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

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

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

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

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

     See also: *note voronoin: XREFvoronoin, *note delaunay:
     XREFdelaunay, *note convhull: XREFconvhull.

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

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

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

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

     The default options depend on the dimension of the input:

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

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

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

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

   An example of the use of ‘voronoi’ is

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

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

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

     Determine area of a polygon by triangle method.

     The variables X and Y define the vertex pairs, and must therefore
     have the same shape.  They can be either vectors or arrays.  If
     they are arrays then the columns of X and Y are treated separately
     and an area returned for each.

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

   An example of the use of ‘polyarea’ might be

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

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

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

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

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

     Each row of A and B define a rectangle, and if both define multiple
     rectangles, then the output, AREA, is a matrix where the i-th row
     corresponds to the i-th row of a and the j-th column corresponds to
     the j-th row of b.

     See also: *note polyarea: XREFpolyarea.

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

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

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

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

     See also: *note delaunay: XREFdelaunay.

   An example of the use of ‘inpolygon’ might be

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

