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

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

   Copyright (C) 1996, 1997, 2007 John W. Eaton.

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

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

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


File: octave.info,  Node: Sparse Linear Algebra,  Next: Iterative Techniques,  Prev: Basics,  Up: Sparse Matrices

20.2 Linear Algebra on Sparse Matrices
======================================

Octave includes a poly-morphic solver for sparse matrices, where the
exact solver used to factorize the matrix, depends on the properties of
the sparse matrix itself. Generally, the cost of determining the matrix
type is small relative to the cost of factorizing the matrix itself,
but in any case the matrix type is cached once it is calculated, so
that it is not re-determined each time it is used in a linear equation.

   The selection tree for how the linear equation is solve is

  1. If the matrix is diagonal, solve directly and goto 8

  2. If the matrix is a permuted diagonal, solve directly taking into
     account the permutations. Goto 8

  3. If the matrix is square, banded and if the band density is less
     than that given by `spparms ("bandden")' continue, else goto 4.

       a. If the matrix is tridiagonal and the right-hand side is not
          sparse continue, else goto 3b.

            1. If the matrix is hermitian, with a positive real
               diagonal, attempt       Cholesky factorization using
               LAPACK xPTSV.

            2. If the above failed or the matrix is not hermitian with
               a positive       real diagonal use Gaussian elimination
               with pivoting using       LAPACK xGTSV, and goto 8.

       b. If the matrix is hermitian with a positive real diagonal,
          attempt       Cholesky factorization using LAPACK xPBTRF.

       c. if the above failed or the matrix is not hermitian with a
          positive       real diagonal use Gaussian elimination with
          pivoting using       LAPACK xGBTRF, and goto 8.

  4. If the matrix is upper or lower triangular perform a sparse forward
     or backward substitution, and goto 8

  5. If the matrix is a upper triangular matrix with column permutations
     or lower triangular matrix with row permutations, perform a sparse
     forward or backward substitution, and goto 8

  6. If the matrix is square, hermitian with a real positive diagonal,
     attempt sparse Cholesky factorization using CHOLMOD.

  7. If the sparse Cholesky factorization failed or the matrix is not
     hermitian with a real positive diagonal, and the matrix is square,
     factorize using UMFPACK.

  8. If the matrix is not square, or any of the previous solvers flags
     a singular or near singular matrix, find a minimum norm solution
     using CXSPARSE(1).

   The band density is defined as the number of non-zero values in the
matrix divided by the number of non-zero values in the matrix. The
banded matrix solvers can be entirely disabled by using "spparms" to
set `bandden' to 1 (i.e. `spparms ("bandden", 1)').

   The QR solver factorizes the problem with a Dulmage-Mendhelsohn, to
seperate the problem into blocks that can be treated as over-determined,
multiple well determined blocks, and a final over-determined block. For
matrices with blocks of strongly connectted nodes this is a big win as
LU decomposition can be used for many blocks. It also significantly
improves the chance of finding a solution to over-determined problems
rather than just returning a vector of "NaN"'s.

   All of the solvers above, can calculate an estimate of the condition
number. This can be used to detect numerical stability problems in the
solution and force a minimum norm solution to be used. However, for
narrow banded, triangular or diagonal matrices, the cost of calculating
the condition number is significant, and can in fact exceed the cost of
factoring the matrix. Therefore the condition number is not calculated
in these case, and Octave relies on simplier techniques to detect
sinular matrices or the underlying LAPACK code in the case of banded
matrices.

   The user can force the type of the matrix with the `matrix_type'
function. This overcomes the cost of discovering the type of the matrix.
However, it should be noted incorrectly identifying the type of the
matrix will lead to unpredictable results, and so `matrix_type' should
be used with care.

 -- Function File: [N, C] = normest (A, TOL)
     Estimate the 2-norm of the matrix A using a power series analysis.
     This is typically used for large matrices, where the cost of
     calculating the `norm (A)' is prohibitive and an approximation to
     the 2-norm is acceptable.

     TOL is the tolerance to which the 2-norm is calculated. By default
     TOL is 1e-6. C returns the number of iterations needed for
     `normest' to converge.

 -- Loadable Function: R = spchol (A)
 -- Loadable Function: [R, P] = spchol (A)
 -- Loadable Function: [R, P, Q] = spchol (A)
     Compute the Cholesky factor, R, of the symmetric positive definite
     sparse matrix A, where

          r' * r = a.

     If called with 2 or more outputs P is the 0 when R is positive
     definite and P is a positive integer otherwise.

     If called with 3 outputs then a sparsity preserving row/column
     permutation is applied to A prior to the factorization. That is R
     is the factorization of `A(Q,Q)' such that

          r' * r = q * a * q'.

     Note that `splchol' factorizations is faster and use less memory.

     *See also:* spcholinv, spchol2inv, splchol.

 -- Loadable Function:  spcholinv (A)
     Use the Cholesky factorization to compute the inverse of the
     sparse symmetric positive definite matrix A.

     *See also:* spchol, spchol2inv.

 -- Loadable Function:  spchol2inv (U)
     Invert a sparse symmetric, positive definite square matrix from its
     Cholesky decomposition, U.  Note that U should be an
     upper-triangular matrix with positive diagonal elements.
     `chol2inv (U)' provides `inv (U'*U)' but it is much faster than
     using `inv'.

     *See also:* spchol, spcholinv.

 -- Loadable Function: [D, RCOND] =  spdet (A)
     Compute the determinant of sparse matrix A using UMFPACK.  Return
     an estimate of the reciprocal condition number if requested.

 -- Loadable Function: [X, RCOND] =  spinv (A, Q)
     Compute the inverse of the sparse square matrix A.  Return an
     estimate of the reciprocal condition number if requested,
     otherwise warn of an ill-conditioned matrix if the reciprocal
     condition number is small.  This function takes advantage of the
     sparsity of the matrix to accelerate the calculation of the
     inverse.

     In general X will be a full matrix, and so if possible forming the
     inverse of a sparse matrix should be avoided. It is significantly
     more accurate and faster to do `Y = A \ B', rather than `Y = spinv
     (A) * B'.

 -- Loadable Function:  spkron (A, B)
     Form the kronecker product of two sparse matrices. This is defined
     block by block as

          x = [a(i, j) b]

     For example,

          kron(speye(3),spdiag([1,2,3]))
          =>
          Compressed Column Sparse (rows = 9, cols = 9, nnz = 9)

            (1, 1) ->  1
            (2, 2) ->  2
            (3, 3) ->  3
            (4, 4) ->  1
            (5, 5) ->  2
            (6, 6) ->  3
            (7, 7) ->  1
            (8, 8) ->  2
            (9, 9) ->  3

 -- Loadable Function: L = splchol (A)
 -- Loadable Function: [L, P] = splchol (A)
 -- Loadable Function: [L, P, Q] = splchol (A)
     Compute the Cholesky factor, L, of the symmetric positive definite
     sparse matrix A, where

          l * l' = a.

     If called with 2 or more outputs P is the 0 when L is positive
     definite and L is a positive integer otherwise.

     If called with 3 outputs that a sparsity preserving row/column
     permutation is applied to A prior to the factorization. That is L
     is the factorization of `A(Q,Q)' such that

          r * r' = a (q, q).

     Note that `splchol' factorizations is faster and use less memory
     than `spchol'. `splchol(A)' is equivalent to `spchol(A)''.

     *See also:* spcholinv, spchol2inv, splchol.

 -- Loadable Function: [L, U] = splu (A)
 -- Loadable Function: [L, U, P] = splu (A)
 -- Loadable Function: [L, U, P, Q] = splu (A)
 -- Loadable Function: [L, U, P, Q] = splu (..., THRES)
 -- Loadable Function: [L, U, P] = splu (..., Q)
     Compute the LU decomposition of the sparse matrix A, using
     subroutines from UMFPACK.  The result is returned in a permuted
     form, according to the optional return values P and Q.

     Called with two or three output arguments and a single input
     argument, "splu" is a replacement for "lu", and therefore the
     sparsity preserving column permutations Q are not performed.
     Called with a fourth output argument, the sparsity preserving
     column transformation Q is returned, such that `P * A * Q = L * U'.

     An additional input argument THRES, that defines the pivoting
     threshold can be given. Alternatively, the desired sparsity
     preserving column permutations Q can be passed. Note that Q is
     assumed to be fixed if three are fewer than four output arguments.
     Otherwise, the updated column permutations are returned as the
     fourth argument.

     With two output arguments, returns the permuted forms of the upper
     and lower triangular matrices, such that `A = L * U'.  With two or
     three output arguments, if a user-defined Q is given, then `U *
     Q'' is returned. The matrix is not required to be square.

     *See also:* sparse, spinv, colamd, symamd.

 -- Loadable Function:   spparms ()
 -- Loadable Function: VALS = spparms ()
 -- Loadable Function: [KEYS, VALS] = spparms ()
 -- Loadable Function: VAL = spparms (KEY)
 -- Loadable Function:   spparms (VALS)
 -- Loadable Function:   spparms ('defaults')
 -- Loadable Function:   spparms ('tight')
 -- Loadable Function:   spparms (KEY, VAL)
     Sets or displays the parameters used by the sparse solvers and
     factorization functions. The first four calls above get
     information about the current settings, while the others change
     the current settings. The parameters are stored as pairs of keys
     and values, where the values are all floats and the keys are one
     of the strings

        * spumoni Printing level of debugging information of the
          solvers (default 0)

        * ths_rel Included for compatiability. Bot used. (default 1)

        * ths_abs Included for compatiability. Bot used. (default 1)

        * exact_d Included for compatiability. Bot used. (default 0)

        * supernd Included for compatiability. Not used. (default 3)

        * rreduce Included for compatiability. Not used. (default 3)

        * wh_frac Inluded for compatiability. Not used. (default 0.5)

        * autommd Flag whether the LU/QR and the '\' and '/' operators
          will automatically use the sparsity preserving mmd functions
          (default 1)

        * autoamd Flag whether the LU and the '\' and '/' operators
          will automatically use the sparsity preserving amd functions
          (default 1)

        * piv_tol The pivot tolerance of the UMFPACK solvers (default
          0.1)

        * bandden ?? (default 0.5)

        * umfpack Flag whether the UMFPACK or mmd solvers are used for
          the LU, '\' and '/' operations (default 1)

     The value of individual keys can be set with `spparms (KEY, VAL)'.
     The default values can be restored with the special keyword
     'defaults'. The special keyword 'tight' can be used to set the mmd
     solvers to attempt for a sparser solution at the potetial cost of
     longer running time.

 -- Loadable Function: R = spqr (A)
 -- Loadable Function: R = spqr (A,0)
 -- Loadable Function: [C, R] = spqr (A,B)
 -- Loadable Function: [C, R] = spqr (A,B,0)
     Compute the sparse QR factorization of A, using CSPARSE.  As the
     matrix Q is in general a full matrix, this function returns the
     Q-less factorization R of A, such that `R = chol (A' * A)'.

     If the final argument is the scalar `0' and the number of rows is
     larger than the number of columns, then an economy factorization is
     returned. That is R will have only `size (A,1)' rows.

     If an additional matrix B is supplied, then `spqr' returns C,
     where `C = Q' * B'. This allows the least squares approximation of
     `A \ B' to be calculated as

          [C,R] = spqr (A,B)
          X = R \ C


     *See also:* spchol, qr.

 -- Loadable Function: P = sprank (S)
     Calculates the structural rank of a sparse matrix S. Note that
     only the structure of the matrix is used in this calculation based
     on a Dulmage-Mendelsohn to block triangular form. As such the
     numerical rank of the matrix S is bounded by `sprank (S) >= rank
     (S)'. Ignoring floating point errors `sprank (S) == rank (S)'.

     *See also:* dmperm.

 -- Loadable Function: [COUNT, H, PARENT, POST, R] = symbfact (S, TYP,
          MODE)
     Performs a symbolic factorization analysis on the sparse matrix S.
     Where

    S
          S is a complex or real sparse matrix.

    TYP
          Is the type of the factorization and can be one of

         `sym'
               Factorize S. This is the default.

         `col'
               Factorize `S' * S'.

         `row'
               Factorize `S * S''.

         `lo'
               Factorize `S''

    MODE
          The default is to return the Cholesky factorization for R,
          and if MODE is 'L', the conjugate transpose of the Choleksy
          factorization is returned. The conjugate transpose version is
          faster and uses less memory, but returns the same values for
          COUNT, H, PARENT and POST outputs.

     The output variables are

    COUNT
          The row counts of the Cholesky factorization as determined by
          TYP.

    H
          The height of the elimination tree.

    PARENT
          The elimination tree itself.

    POST
          A sparse boolean matrix whose structure is that of the
          Cholesky factorization as determined by TYP.

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

   (1) CHOLMOD, UMFPACK and CXSPARSE are written by Tim Davis and are
available at http://www.cise.ufl.edu/research/sparse/


File: octave.info,  Node: Iterative Techniques,  Next: Real Life Example,  Prev: Sparse Linear Algebra,  Up: Sparse Matrices

20.3 Iterative Techniques applied to sparse matrices
====================================================

The left division `\' and right division `/' operators, discussed in
the previous section, use direct solvers to resolve a linear equation
of the form `X = A \ B' or `X = B / A'. Octave equally includes a
number of functions to solve sparse linear equations using iterative
techniques.

 -- Function File: X = pcg (A, B, TOL, MAXIT, M1, M2, X0, ...)
 -- Function File: [X, FLAG, RELRES, ITER, RESVEC, EIGEST] = pcg (...)
     Solves the linear system of equations `A * X = B' by means of the
     Preconditioned Conjugate Gradient iterative method. The input
     arguments are

        * A can be either a square (preferably sparse) matrix or a
          function handle, inline function or string containing the name
          of a function which computes `A * X'. In principle A should
          be symmetric and positive definite; if `pcg' finds A to not
          be positive definite, you will get a warning message and the
          FLAG output parameter will be set.

        * B is the right hand side vector.

        * TOL is the required relative tolerance for the residual error,
          `B - A * X'. The iteration stops if `norm (B - A * X) <= TOL
          * norm (B - A * X0)'. If TOL is empty or is omitted, the
          function sets `TOL = 1e-6' by default.

        * MAXIT is the maximum allowable number of iterations; if `[]'
          is supplied for `maxit', or `pcg' has less arguments, a
          default value equal to 20 is used.

        * M = M1 * M2 is the (left) preconditioning matrix, so that the
          iteration is (theoretically) equivalent to solving by `pcg'
          `P * X = M \ B', with `P = M \ A'.  Note that a proper choice
          of the preconditioner may dramatically improve the overall
          performance of the method. Instead of matrices M1 and M2, the
          user may pass two functions which return the results of
          applying the inverse of M1 and M2 to a vector (usually this
          is the preferred way of using the preconditioner).  If `[]'
          is supplied for M1, or M1 is omitted, no preconditioning is
          applied. If M2 is omitted, M = M1 will be used as
          preconditioner.

        * X0 is the initial guess. If X0 is empty or omitted, the
          function sets X0 to a zero vector by default.

     The arguments which follow X0 are treated as parameters, and
     passed in a proper way to any of the functions (A or M) which are
     passed to `pcg'. See the examples below for further details. The
     output arguments are

        * X is the computed approximation to the solution of `A * X =
          B'.

        * FLAG reports on the convergence. `FLAG = 0' means the
          solution converged and the tolerance criterion given by TOL
          is satisfied. `FLAG = 1' means that the MAXIT limit for the
          iteration count was reached. `FLAG = 3' reports that the
          (preconditioned) matrix was found not positive definite.

        * RELRES is the ratio of the final residual to its initial
          value, measured in the Euclidean norm.

        * ITER is the actual number of iterations performed.

        * RESVEC describes the convergence history of the method.
          `RESVEC (i,1)' is the Euclidean norm of the residual, and
          `RESVEC (i,2)' is the preconditioned residual norm, after the
          (I-1)-th iteration, `I = 1, 2, ..., ITER+1'. The
          preconditioned residual norm is defined as `norm (R) ^ 2 = R'
          * (M \ R)' where `R = B - A * X', see also the description of
          M. If EIGEST is not required, only `RESVEC (:,1)' is returned.

        * EIGEST returns the estimate for the smallest `EIGEST (1)' and
          largest `EIGEST (2)' eigenvalues of the preconditioned matrix
          `P = M \ A'. In particular, if no preconditioning is used,
          the extimates for the extreme eigenvalues of A are returned.
          `EIGEST (1)' is an overestimate and `EIGEST (2)' is an
          underestimate, so that `EIGEST (2) / EIGEST (1)' is a lower
          bound for `cond (P, 2)', which nevertheless in the limit
          should theoretically be equal to the actual value of the
          condition number.  The method which computes EIGEST works
          only for symmetric positive definite A and M, and the user is
          responsible for verifying this assumption.

     Let us consider a trivial problem with a diagonal matrix (we
     exploit the sparsity of A)

          	N = 10;
          	A = spdiag ([1:N]);
          	b = rand (N, 1);
               [L, U, P, Q] = luinc (A,1.e-3);

     EXAMPLE 1: Simplest use of `pcg'

            x = pcg(A,b)

     EXAMPLE 2: `pcg' with a function which computes `A * X'

            function y = applyA (x)
              y = [1:N]'.*x;
            endfunction

            x = pcg ("applyA", b)

     EXAMPLE 3: `pcg' with a preconditioner: L * U

          x=pcg(A,b,1.e-6,500,L*U);

     EXAMPLE 4: `pcg' with a preconditioner: L * U.  Faster than
     EXAMPLE 3 since lower and upper triangular matrices are easier to
     invert

          x=pcg(A,b,1.e-6,500,L,U);

     EXAMPLE 5: Preconditioned iteration, with full diagnostics. The
     preconditioner (quite strange, because even the original matrix A
     is trivial) is defined as a function

            function y = applyM(x)
              K = floor (length (x) - 2);
              y = x;
              y(1:K) = x(1:K)./[1:K]';
            endfunction

            [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], [], "applyM");
            semilogy (1:iter+1, resvec);

     EXAMPLE 6: Finally, a preconditioner which depends on a parameter
     K.

            function y = applyM (x, varargin)
            K = varargin{1};
            y = x;
            y(1:K) = x(1:K)./[1:K]';
            endfuntion

            [x, flag, relres, iter, resvec, eigest] = ...
                 pcg (A, b, [], [], "applyM", [], [], 3)

     REFERENCES

     	[1] C.T.Kelley, 'Iterative methods for linear and nonlinear
     equations', 	SIAM, 1995 (the base PCG algorithm)

     	[2] Y.Saad, 'Iterative methods for sparse linear systems', PWS 1996
     (condition number estimate from PCG) Revised version of this book
     is 	available online at
     http://www-users.cs.umn.edu/~saad/books.html


     *See also:* sparse, pcr.

 -- Function File: X = pcr (A, B, TOL, MAXIT, M, X0, ...)
 -- Function File: [X, FLAG, RELRES, ITER, RESVEC] = pcr (...)
     Solves the linear system of equations `A * X = B' by means of the
     Preconditioned Conjugate Residuals iterative method. The input
     arguments are

        * A can be either a square (preferably sparse) matrix or a
          function handle, inline function or string containing the name
          of a function which computes `A * X'. In principle A should
          be symmetric and non-singular; if `pcr' finds A to be
          numerically singular, you will get a warning message and the
          FLAG output parameter will be set.

        * B is the right hand side vector.

        * TOL is the required relative tolerance for the residual error,
          `B - A * X'. The iteration stops if `norm (B - A * X) <= TOL
          * norm (B - A * X0)'. If TOL is empty or is omitted, the
          function sets `TOL = 1e-6' by default.

        * MAXIT is the maximum allowable number of iterations; if `[]'
          is supplied for `maxit', or `pcr' has less arguments, a
          default value equal to 20 is used.

        * M is the (left) preconditioning matrix, so that the iteration
          is (theoretically) equivalent to solving by `pcr' `P * X = M
          \ B', with `P = M \ A'.  Note that a proper choice of the
          preconditioner may dramatically improve the overall
          performance of the method. Instead of matrix M, the user may
          pass a function which returns the results of applying the
          inverse of M to a vector (usually this is the preferred way
          of using the preconditioner). If `[]' is supplied for M, or M
          is omitted, no preconditioning is applied.

        * X0 is the initial guess. If X0 is empty or omitted, the
          function sets X0 to a zero vector by default.

     The arguments which follow X0 are treated as parameters, and
     passed in a proper way to any of the functions (A or M) which are
     passed to `pcr'. See the examples below for further details. The
     output arguments are

        * X is the computed approximation to the solution of `A * X =
          B'.

        * FLAG reports on the convergence. `FLAG = 0' means the
          solution converged and the tolerance criterion given by TOL
          is satisfied. `FLAG = 1' means that the MAXIT limit for the
          iteration count was reached. `FLAG = 3' reports t `pcr'
          breakdown, see [1] for details.

        * RELRES is the ratio of the final residual to its initial
          value, measured in the Euclidean norm.

        * ITER is the actual number of iterations performed.

        * RESVEC describes the convergence history of the method, so
          that `RESVEC (i)' contains the Euclidean norms of the
          residualafter the (I-1)-th iteration, `I = 1,2, ..., ITER+1'.

     Let us consider a trivial problem with a diagonal matrix (we
     exploit the sparsity of A)

          	N = 10;
          	A = diag([1:N]); A = sparse(A);
          	b = rand(N,1);

     EXAMPLE 1: Simplest use of `pcr'

            x = pcr(A, b)

     EXAMPLE 2: `pcr' with a function which computes `A * X'.

            function y = applyA(x)
              y = [1:10]'.*x;
            endfunction

            x = pcr('applyA',b)

     EXAMPLE 3:  Preconditioned iteration, with full diagnostics. The
     preconditioner (quite strange, because even the original matrix A
     is trivial) is defined as a function

            function y = applyM(x)
              K = floor(length(x)-2);
              y = x;
              y(1:K) = x(1:K)./[1:K]';
            endfunction

            [x, flag, relres, iter, resvec] = pcr(A,b,[],[],'applyM')
            semilogy([1:iter+1], resvec);

     EXAMPLE 4: Finally, a preconditioner which depends on a parameter
     K.

            function y = applyM(x, varargin)
              K = varargin{1};
              y = x; y(1:K) = x(1:K)./[1:K]';
            endfunction

            [x, flag, relres, iter, resvec] = pcr(A,b,[],[],'applyM',[],3)

     REFERENCES

     	[1] W. Hackbusch, "Iterative Solution of Large Sparse Systems of
     Equations", section 9.5.4; Springer, 1994


     *See also:* sparse, pcg.

   The speed with which an iterative solver converges to a solution can
be accelerated with the use of a pre-conditioning matrix M. In this
case the linear equation `M^-1 * X = M^-1 * A \ B' is solved instead.
Typical pre-conditioning matrices are partial factorizations of the
original matrix.

 -- Loadable Function: [L, U, P, Q] = luinc (A, '0')
 -- Loadable Function: [L, U, P, Q] = luinc (A, DROPTOL)
 -- Loadable Function: [L, U, P, Q] = luinc (A, OPTS)
     Produce the incomplete LU factorization of the sparse matrix A.
     Two types of incomplete factorization are possible, and the type
     is determined by the second argument to "luinc".

     Called with a second argument of '0', the zero-level incomplete LU
     factorization is produced. This creates a factorization of A where
     the position of the non-zero arguments correspond to the same
     positions as in the matrix A.

     Alternatively, the fill-in of the incomplete LU factorization can
     be controlled through the variable DROPTOL or the structure OPTS.
     The UMFPACK multifrontal factorization code by Tim A.  Davis is
     used for the incomplete LU factorication, (availability
     `http://www.cise.ufl.edu/research/sparse/umfpack/')

     DROPTOL determines the values below which the values in the LU
     factorization are dropped and replaced by zero. It must be a
     positive scalar, and any values in the factorization whose
     absolute value are less than this value are dropped, expect if
     leaving them increase the sparsity of the matrix. Setting DROPTOL
     to zero results in a complete LU factorization which is the
     default.

     OPTS is a structure containing one or more of the fields

    `droptol'
          The drop tolerance as above. If OPTS only contains `droptol'
          then this is equivalent to using the variable DROPTOL.

    `milu'
          A logical variable flagging whether to use the modified
          incomplete LU factorization. In the case that `milu' is true,
          the dropped values are subtract from the diagonal of the
          matrix U of the factorization.  The default is `false'.

    `udiag'
          A logical variable that flags whether zero elements on the
          diagonal of U should be replaced with DROPTOL to attempt to
          avoid singular factors. The default is `false'.

    `thresh'
          Defines the pivot threshold in the interval [0,1]. Values
          outside that range are ignored.

     All other fields in OPTS are ignored. The outputs from "luinc" are
     the same as for "lu".

     *See also:* sparse, lu, cholinc.


File: octave.info,  Node: Real Life Example,  Prev: Iterative Techniques,  Up: Sparse Matrices

20.4 Real Life Example of the use of Sparse Matrices
====================================================

A common application for sparse matrices is in the solution of Finite
Element Models. Finite element models allow numerical solution of
partial differential equations that do not have closed form solutions,
typically because of the complex shape of the domain.

   In order to motivate this application, we consider the boundary value
Laplace equation. This system can model scalar potential fields, such
as heat or electrical potential. Given a medium Omega with boundary
dOmega . At all points on the dOmega the boundary conditions are known,
and we wish to calculate the potential in Omega . Boundary conditions
may specify the potential (Dirichlet boundary condition), its normal
derivative across the boundary (Neumann boundary condition), or a
weighted sum of the potential and its derivative (Cauchy boundary
condition).

   In a thermal model, we want to calculate the temperature in Omega
and know the boundary temperature (Dirichlet condition) or heat flux
(from which we can calculate the Neumann condition by dividing by the
thermal conductivity  at the boundary). Similarly, in an electrical
model, we want to calculate the voltage in Omega and know the boundary
voltage (Dirichlet) or current (Neumann condition after diving by the
electrical conductivity).  In an electrical model, it is common for
much of the boundary to be electrically isolated; this is a Neumann
boundary condition with the current equal to zero.

   The simplest finite element models will divide Omega into simplexes
(triangles in 2D, pyramids in 3D).

   The following example creates a simple rectangular 2D electrically
conductive medium with 10 V and 20 V imposed on opposite sides
(Dirichlet boundary conditions). All other edges are electrically
isolated.

        node_y= [1;1.2;1.5;1.8;2]*ones(1,11);
        node_x= ones(5,1)*[1,1.05,1.1,1.2, ...
                  1.3,1.5,1.7,1.8,1.9,1.95,2];
        nodes= [node_x(:), node_y(:)];

        [h,w]= size(node_x);
        elems= [];
        for idx= 1:w-1
          widx= (idx-1)*h;
          elems= [elems; ...
            widx+[(1:h-1);(2:h);h+(1:h-1)]'; ...
            widx+[(2:h);h+(2:h);h+(1:h-1)]' ];
        endfor

        E= size(elems,1); # No. of simplices
        N= size(nodes,1); # No. of vertices
        D= size(elems,2); # dimensions+1

   This creates a N-by-2 matrix `nodes' and a E-by-3 matrix `elems'
with values, which define finite element triangles:

       nodes(1:7,:)'
         1.00 1.00 1.00 1.00 1.00 1.05 1.05 ...
         1.00 1.20 1.50 1.80 2.00 1.00 1.20 ...

       elems(1:7,:)'
         1    2    3    4    2    3    4 ...
         2    3    4    5    7    8    9 ...
         6    7    8    9    6    7    8 ...

   Using a first order FEM, we approximate the electrical conductivity
distribution in Omega as constant on each simplex (represented by the
vector `conductivity').  Based on the finite element geometry, we first
calculate a system (or stiffness) matrix for each simplex (represented
as 3-by-3 elements on the diagonal of the element-wise system matrix
`SE'. Based on `SE' and a N-by-DE connectivity matrix `C', representing
the connections between simplices and vectices, the global connectivity
matrix `S' is calculated.

       # Element conductivity
       conductivity= [1*ones(1,16), ...
              2*ones(1,48), 1*ones(1,16)];

       # Connectivity matrix
       C = sparse ((1:D*E), reshape (elems', ...
              D*E, 1), 1, D*E, N);

       # Calculate system matrix
       Siidx = floor ([0:D*E-1]'/D) * D * ...
              ones(1,D) + ones(D*E,1)*(1:D) ;
       Sjidx = [1:D*E]'*ones(1,D);
       Sdata = zeros(D*E,D);
       dfact = factorial(D-1);
       for j=1:E
          a = inv([ones(D,1), ...
              nodes(elems(j,:), :)]);
          const = conductivity(j) * 2 / ...
              dfact / abs(det(a));
          Sdata(D*(j-1)+(1:D),:) = const * ...
              a(2:D,:)' * a(2:D,:);
       endfor
       # Element-wise system matrix
       SE= sparse(Siidx,Sjidx,Sdata);
       # Global system matrix
       S= C'* SE *C;

   The system matrix acts like the conductivity `S' in Ohm's law `S * V
= I'.  Based on the Dirichlet and Neumann boundary conditions, we are
able to solve for the voltages at each vertex `V'.

       # Dirichlet boundary conditions
       D_nodes=[1:5, 51:55];
       D_value=[10*ones(1,5), 20*ones(1,5)];

       V= zeros(N,1);
       V(D_nodes) = D_value;
       idx = 1:N; # vertices without Dirichlet
                  # boundary condns
       idx(D_nodes) = [];

       # Neumann boundary conditions. Note that
       # N_value must be normalized by the
       # boundary length and element conductivity
       N_nodes=[];
       N_value=[];

       Q = zeros(N,1);
       Q(N_nodes) = N_value;

       V(idx) = S(idx,idx) \ ( Q(idx) - ...
                 S(idx,D_nodes) * V(D_nodes));

   Finally, in order to display the solution, we show each solved
voltage value in the z-axis for each simplex vertex.

       elemx = elems(:,[1,2,3,1])';
       xelems = reshape (nodes(elemx, 1), 4, E);
       yelems = reshape (nodes(elemx, 2), 4, E);
       velems = reshape (V(elemx), 4, E);
       plot3 (xelems,yelems,velems,'k');
       print ('grid.eps');


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

21 Numerical Integration
************************

Octave comes with several built-in functions for computing the integral
of a function numerically.  These functions all solve 1-dimensional
integration problems.

* Menu:

* Functions of One Variable::
* Functions of Multiple Variables::
* Orthogonal Collocation::


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

21.1 Functions of One Variable
==============================

Octave supports three different algorithms for computing the integral
of a function f over the interval from a to b.  These are

`quad'
     Numerical integration based on Gaussian quadrature.

`quadl'
     Numerical integration using an adaptive Lobatto rule.

`trapz'
     Numerical integration using the trapezodial method.

Besides these functions Octave also allows you to perform cumulative
numerical integration using the trapezodial method through the
`cumtrapz' function.

 -- Loadable Function: [V, IER, NFUN, ERR] = quad (F, A, B, TOL, SING)
     Integrate a nonlinear function of one variable using Quadpack.
     The first argument is the name of the  function, the function
     handle or the inline function to call to compute the value of the
     integrand.  It must have the form

          y = f (x)

     where Y and X are scalars.

     The second and third arguments are limits of integration.  Either
     or both may be infinite.

     The optional argument TOL is a vector that specifies the desired
     accuracy of the result.  The first element of the vector is the
     desired absolute tolerance, and the second element is the desired
     relative tolerance.  To choose a relative test only, set the
     absolute tolerance to zero.  To choose an absolute test only, set
     the relative tolerance to zero.

     The optional argument SING is a vector of values at which the
     integrand is known to be singular.

     The result of the integration is returned in V and IER contains an
     integer error code (0 indicates a successful integration).  The
     value of NFUN indicates how many function evaluations were
     required, and ERR contains an estimate of the error in the
     solution.

     You can use the function `quad_options' to set optional parameters
     for `quad'.

     It should be noted that since `quad' is written in Fortran it
     cannot be called recursively.

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

     Options include

    `"absolute tolerance"'
          Absolute tolerance; may be zero for pure relative error test.

    `"relative tolerance"'
          Nonnegative relative tolerance.  If the absolute tolerance is
          zero, the relative tolerance must be greater than or equal to
          `max (50*eps, 0.5e-28)'.

   Here is an example of using `quad' to integrate the function

       F(X) = X * sin (1/X) * sqrt (abs (1 - X))

from X = 0 to X = 3.

   This is a fairly difficult integration (plot the function over the
range of integration to see why).

   The first step is to define the function:

     function y = f (x)
       y = x .* sin (1 ./ x) .* sqrt (abs (1 - x));
     endfunction

   Note the use of the `dot' forms of the operators.  This is not
necessary for the call to `quad', but it makes it much easier to
generate a set of points for plotting (because it makes it possible to
call the function with a vector argument to produce a vector result).

   Then we simply call quad:

     [v, ier, nfun, err] = quad ("f", 0, 3)
          => 1.9819
          => 1
          => 5061
          => 1.1522e-07

   Although `quad' returns a nonzero value for IER, the result is
reasonably accurate (to see why, examine what happens to the result if
you move the lower bound to 0.1, then 0.01, then 0.001, etc.).

 -- Function File: Q = quadl (F, A, B)
 -- Function File: Q = quadl (F, A, B, TOL)
 -- Function File: Q = quadl (F, A, B, TOL, TRACE)
 -- Function File: Q = quadl (F, A, B, TOL, TRACE, P1, P2, ...)
     Numerically evaluate integral using adaptive Lobatto rule.  `quadl
     (F, A, B)' approximates the integral of `F(X)' to machine
     precision. F is either a function handle, inline function or
     string containing the name of the function to evaluate. The
     function F must return a vector of output values if given a vector
     of input values.

     If defined, TOL defines the relative tolerance to which to which
     to integrate `F(X)'. While if TRACE is defined, displays the left
     end point of the current interval, the interval length, and the
     partial integral.

     Additional arguments P1, etc, are passed directly to F.  To use
     default values for TOL and TRACE, one may pass empty matrices.

     Reference: W. Gander and W. Gautschi, 'Adaptive Quadrature -
     Revisited', BIT Vol. 40, No. 1, March 2000, pp. 84-101.
     `http://www.inf.ethz.ch/personal/gander/'


 -- Function File: Z = trapz (Y)
 -- Function File: Z = trapz (X, Y)
 -- Function File: Z = trapz (..., DIM)
     Numerical intergration using trapezodial method. `trapz (Y)'
     computes the integral of the Y along the first non singleton
     dimension. If the argument X is omitted a equally spaced vector is
     assumed. `trapz (X, Y)' evaluates the integral with respect to X.


     *See also:* cumtrapz.

 -- Function File: Z = cumtrapz (Y)
 -- Function File: Z = cumtrapz (X, Y)
 -- Function File: Z = cumtrapz (..., DIM)
     Cumulative numerical intergration using trapezodial method.
     `cumtrapz (Y)' computes the cummulative integral of the Y along
     the first non singleton dimension. If the argument X is omitted a
     equally spaced vector is assumed. `cumtrapz (X, Y)' evaluates the
     cummulative integral with respect to X.


     *See also:* trapz,cumsum.


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

21.2 Orthogonal Collocation
===========================

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

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

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

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

   Then the solution at the roots R is

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


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

21.3 Functions of Multiple Variables
====================================

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

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

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

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

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

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

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

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


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

22 Differential Equations
*************************

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

* Menu:

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


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

22.1 Ordinary Differential Equations
====================================

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

     dx
     -- = f (x, t)
     dt

using Hindmarsh's ODE solver LSODE.

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

          dx
          -- = f(x, t)
          dt

     with

          x(t_0) = x_0

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

     The first argument, FCN, is a string, or cell array of strings,
     inline or function handles, that names the function 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, the first element names the
     function f described above, and the second element names a function
     to compute the Jacobian of f.  The Jacobian function must have the
     form

          JAC = j (X, T)

     in which JAC is the matrix of partial derivatives

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

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

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

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

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

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

     *See also:* daspk, dassl, dasrt.

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

     Options include

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

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

          The local error test applied at each integration step is

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

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

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

         "bdf"

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

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

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

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

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

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

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

     function xdot = f (x, t)

       xdot = zeros (3,1);

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

     endfunction

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

     t = linspace (0, 500, 1000);

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

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

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

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


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

22.2 Differential-Algebraic Equations
=====================================

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

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

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

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

          0 = f (x, xdot, t)

     with

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

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

     The first argument, FCN, is a string or a two element cell array
     of strings, inline or function handle, that names the function, 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, 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:* dassl.

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

     Options include

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

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

          The local error test applied at each integration step is

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

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

            1. Given Y_d, calculate Y_a and Y'_d

            2. Given Y', calculate Y.

          In either case, initial values for the given components are
          input, and initial guesses for the unknown components must
          also be provided as input.  Set this option to 1 to solve the
          first problem, or 2 to solve the second (the default 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 number of Newton iterations
               allowed in all 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 occaisionally suffer from
          severe scaling difficulties on the first step.  If you know a
          great deal about the scaling of your problem, you can help to
          alleviate this problem by specifying an initial stepsize
          (default is computed automatically).

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

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

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

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

          0 = f (x, xdot, t)

     with

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

     with functional stopping criteria (root solving).

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

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

     The first argument, FCN, is a string, or cell array of strings or
     inline or function handles, that names the function 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 two element cell array,
     the first element names the function f described above, and the
     second element names a function to compute the modified Jacobian

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

     The modified Jacobian function must have the form


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

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

          G_OUT = g (X, T)

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

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

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

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

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

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

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

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

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

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

     *See also:* daspk, dasrt, lsode.

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

     Options include

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

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

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

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

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

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

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

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


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

23 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

23.1 Linear Programming
=======================

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

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

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

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

          min C'*x

     subject to

          A*x  = b
            x >= 0

     but may also solve problems of the form

          [ min | max ] C'*x

     subject to

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

     Input arguments:

    C
          A column array containing the objective function coefficients.

    A
          A matrix containing the constraints coefficients.

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

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

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

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

         `"U"'
               Variable with upper bound (`A(i,:)*x <= b(i)').

         `"S"'
               Fixed Variable (`A(i,:)*x = b(i)').

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

         `"D"'
               Double-bounded variable (`A(i,:)*x >= -b(i)' _and_
               (`A(i,:)*x <= b(i)').

    VARTYPE
          A column array containing the types of the variables.
         `"F"'
               "C" Continuous variable.  "I" Integer variable

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

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

          Integer parameters:

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

              1
                    Error messages only.

              2
                    Normal output .

              3
                    Full output (includes informational messages).

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

              1
                    Equilibration scaling .

              2
                    Geometric mean scaling, then equilibration scaling.

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

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

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

              1
                    Steepest edge pricing.

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

              1
                    Replace tiny primal and dual values by exact zero.

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

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

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

              1
                    Branch on the last variable.

              2
                    Branch using a heuristic by Driebeck and Tomlin.

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

              1
                    Breadth first search.

              2
                    Backtrack using the best projection heuristic.

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

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

              2
                    Interior point method.

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

          Real parameters:

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

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

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

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

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

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

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

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

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

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

     Output values:

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

    FOPT
          The optimum value of the objective function.

    STATUS
          Status of the optimization.

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

         181 (`LPX_FEAS')
               Solution is feasible.

         182 (`LPX_INFEAS')
               Solution is infeasible.

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

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

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

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

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

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

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

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

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

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

         207 (`LPX_E_ITLIM')
               Iterations limit exhausted.

         208 (`LPX_E_TMLIM')
               Time limit exhausted.

         209 (`LPX_E_NOFEAS')
               No feasible solution.

         210 (`LPX_E_INSTAB')
               Numerical instability.

         211 (`LPX_E_SING')
               Problems with basis matrix.

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

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

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

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

         `redcosts'
               Reduced Costs.

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

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

     Example:

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

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

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


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

23.2 Quadratic Programming
==========================

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

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

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

     subject to

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

     using a null-space active-set method.

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

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

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

         1
               The problem is not convex.  Local solution found.

         2
               The problem is not convex and unbounded.

         3
               Maximum number of iterations reached.

         6
               The problem is infeasible.


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

23.3 Nonlinear Programming
==========================

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

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

               min phi (x)
                x

     subject to

               g(x)  = 0
               h(x) >= 0

     using a successive quadratic programming method.

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

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

               y = phi (x)

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

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

     If supplied, the gradient function must be of the form

               g = gradient (x)

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

     If supplied, the hessian function must be of the form

               h = hessian (x)

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

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

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

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

               r = f (x)

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

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

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

     Here is an example of calling `sqp':

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

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

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

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

               x =

                 -1.71714
                  1.59571
                  1.82725
                 -0.76364
                 -0.76364

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

                 -0.0401627
                  0.0379578
                 -0.0052227

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

    102
          The BFGS update failed.

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


     *See also:* qp.


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

23.4 Linear Least Squares
=========================

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

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

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

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

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

    SIGMA
          The OLS estimator for the matrix S,

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

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

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

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

    BETA
          The GLS estimator for b.

    V
          The GLS estimator for s^2.

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


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

24 Statistics
*************

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

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

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

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

   It should be noted that the statistics functions doesn't handle data
containing NaN, NA, or Inf.  Such values needs to be handled explicitly.

* Menu:

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


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

24.1 Descriptive Statistics
===========================

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

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

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

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

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

    `"g"'
          Computer the geometric mean.

    `"h"'
          Compute the harmonic mean.

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

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

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

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

     *See also:* std, mean.

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

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

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

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

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

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

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

     *See also:* mean, median.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     If X is a vector, treat it as a column vector.

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

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

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

          moment (x, 3, "ac")

     computes the third central absolute moment of X.

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


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

24.2 Basic Statistical Functions
================================

Octave also supports various helpful statistical functions.

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

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

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

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

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

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

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


     *See also:* bincoeff.

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File:  ranks (X, DIM)
     If X is a vector, return the (column) vector of ranks of X
     adjusted for ties.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

24.3 Statistical Plots
======================

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

24.4 Tests
==========

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The output is a structure with the following elements:

    PVAL
          The p-value of the test.

    STAT
          The value of the test statistic.

    DIST
          The distribution of the test statistic.

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

    ALTERNATIVE
          The alternative hypothesis.

    METHOD
          The method used for testing.

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

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

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

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

     If not given explicitly, R = 0.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

24.5 Models
===========

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

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

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

     fits the model

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

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

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

     The full form is

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

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

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

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

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

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


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

24.6 Distributions
==================

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The arguments can be of common size or scalar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The arguments must be of common size or scalar.

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

     for X > 0.

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

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

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

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

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

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

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

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

     Default values are MU = 1, SIGMA = 1.

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

     Default values are MU = 1, SIGMA = 1.

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

     Default values are MU = 1, SIGMA = 1.

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

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

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

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

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

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

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

     Default values are M = 0, S = 1.

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

     Default values are M = 0, S = 1.

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

     Default values are M = 0, S = 1.

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

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

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

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

 -- Function File:  tinv (X, N)
     For each component of X, compute the quantile (the inverse of the
     CDF) at X of the t (Student) distribution with parameter N.

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

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

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

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

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

     Default values are A = 0, B = 1.

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

     Default values are A = 0, B = 1.

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

     Default values are A = 0, B = 1.

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

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

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

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

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

     for X > 0.


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

24.7 Random Number Generation
=============================

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

25 Financial Functions
**********************

 -- Function File:  fv (R, N, P, L, METHOD)
     Return the future value at the end of period N of an investment
     which consists of N payments of P in each period, assuming an
     interest rate R.

     The optional argument L may be used to specify an additional
     lump-sum payment.

     The optional argument METHOD may be used ot specify whether the
     payments are made at the end (`"e"', default) or at the beginning
     (`"b"') of each period.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

 -- Function File:  fvl (R, N, L)
     Return the future value at the end of N periods of an initial lump
     sum investment L, given a per-period interest rate R.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

 -- Function File:  irr (P, I)
     Return the internal rate of return of a series of payments P from
     an initial investment I (i.e., the solution of `npv (r, p) = i'.
     If the second argument is omitted, a value of 0 is used.

     *See also:* npv, pv, rate.

 -- Function File:  nper (R, P, A, L, METHOD)
     Return the number of regular payments of P necessary to amortize A
     loan of amount A and interest R.

     The optional argument L may be used to specify an additional
     lump-sum payment of L made at the end of the amortization time.

     The optional argument METHOD may be used to specify whether
     payments are made at the end ("E", default) or at the beginning
     ("B") of each period.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

     *See also:* pv, pmt, rate, npv.

 -- Function File:  npv (R, P, I)
     Returns the net present value of a series of irregular (i.e., not
     necessarily identical) payments P which occur at the ends of N
     consecutive periods.  R specifies the one-period interest rates and
     can either be a scalar (constant rates) or a vector of the same
     length as P.

     The optional argument I may be used to specify an initial
     investment.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

     *See also:* irr, pv.

 -- Function File:  pmt (R, N, A, L, METHOD)
     Return the amount of periodic payment necessary to amortize a loan
     of amount a with interest rate R in N periods.

     The optional argument L may be used to specify a terminal lump-sum
     payment.

     The optional argument METHOD may be used to specify whether
     payments are made at the end ("E", default) or at the beginning
     ("B") of each period.

     *See also:* pv, nper, rate.

 -- Function File:  pv (R, N, P, L, METHOD)
     Returns the present value of an investment that will pay off P for
     N consecutive periods, assuming an interest R.

     The optional argument L may be used to specify an additional
     lump-sum payment made at the end of N periods.

     The optional argument METHOD may be used to specify whether
     payments are made at the end (`"e"', default) or at the beginning
     (`"b"') of each period.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

     *See also:* pmt, nper, rate, npv.

 -- Function File:  pvl (R, N, P)
     Return the present value of an investment that will pay off P in
     one lump sum at the end of N periods, given the interest rate R.

     Note that the rate R is specified as a fraction (i.e., 0.05, not 5
     percent).

 -- Function File:  rate (N, P, V, L, METHOD)
     Return the rate of return on an investment of present value V which
     pays P in N consecutive periods.

     The optional argument L may be used to specify an additional
     lump-sum payment made at the end of N periods.

     The optional string argument METHOD may be used to specify whether
     payments are made at the end (`"e"', default) or at the beginning
     (`"b"') of each period.

     *See also:* pv, pmt, nper, npv.

 -- Function File:  vol (X, M, N)
     Return the volatility of each column of the input matrix X.  The
     number of data sets per period is given by M (e.g. the number of
     data per year if you want to compute the volatility per year).
     The optional parameter N gives the number of past periods used for
     computation, if it is omitted, a value of 1 is used.  If T is the
     number of rows of X, `vol' returns the volatility from `n*m' to T.


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

26 Sets
*******

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

 -- Function File:  create_set (X)
     Return a row vector containing the unique values in X, sorted in
     ascending order.  For example,

          create_set ([ 1, 2; 3, 4; 4, 2 ])
          => [ 1, 2, 3, 4 ]


     *See also:* union, intersection, complement.

 -- Function File:  unique (X)
     Return the unique elements of X, sorted in ascending order.  If X
     is a row vector, return a row vector, but if X is a column vector
     or a matrix return a column vector.

 -- Function File:  unique (A, 'rows')
     Return the unique rows of A, sorted in ascending order.

 -- Function File: [Y, I, J] =  unique (X)
     Return index vectors I and J such that `x(i)==y' and `y(j)==x'.

     *See also:* union, intersect, setdiff, setxor, ismember.

* Menu:

* Set Operations::


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

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

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

     union(x, y)

computes the union of the two sets.

 -- Function File:  ismember (A, S)
     Return a matrix the same shape as A which has 1 if `A(i,j)' is in
     S or 0 if it isn't.

     *See also:* unique, union, intersection, setxor, setdiff.

 -- Function File:  union (X, Y)
     Return the set of elements that are in either of the sets X and Y.
     For example,

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


     *See also:* create_set, intersection, complement.

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

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



*See also:* unique, union, setxor, setdiff, ismember.

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

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


     *See also:* create_set, union, intersection.

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

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

     *See also:* unique, union, intersect, setxor, ismember.

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


     *See also:* unique, union, intersect, setdiff, ismember.


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

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

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

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

* Menu:

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


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

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

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

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

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

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

 -- Function File:  polyval (C, X)
     Evaluate a polynomial.

     `polyval (C, X)' will evaluate the polynomial at the specified
     value of X.

     If X is a vector or matrix, the polynomial is evaluated at each of
     the elements of X.

     *See also:* polyvalm, poly, roots, conv, deconv, residue, filter,
     polyderiv, polyinteg.

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

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

     The argument X must be a square matrix.

     *See also:* polyval, poly, roots, conv, deconv, residue, filter,
     polyderiv, and polyinteg.


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

27.2 Finding Roots
==================

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

 -- Function File:  roots (V)
     For a vector V with N components, return the roots of the
     polynomial

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

     As an example, the following code finds the roots of the quadratic
     polynomial
          p(x) = x^2 - 5.

          c = [1, 0, -5];
          roots(c)
          =>  2.2361
          => -2.2361
     Note that the true result is +/- sqrt(5) which is roughly +/-
     2.2361.

     *See also:* compan.

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

     The companion matrix is

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

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

     *See also:* poly, roots, residue, conv, deconv, polyval, polyderiv,
     polyinteg.


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

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

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

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

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

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

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

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

     *See also:* conv, poly, roots, residue, polyval, polyderiv,
     polyinteg.

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

    SHAPE= 'full'
          returns full 2-D convolution

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

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

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

 -- Function File: Q = polygcd (B, A, TOL)
     Find greatest common divisor of two polynomials.  This is
     equivalent to the polynomial found by multiplying together all the
     common roots.  Together with deconv, you can reduce a ratio of two
     polynomials.  Tolerance defaults to
          sqrt(eps).
      Note that this is an unstable algorithm, so don't try it on large
     polynomials.

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


     *See also:* poly, polyinteg, polyderiv, polyreduce, roots, conv,
     deconv, residue, filter, polyval, and polyvalm.

 -- Function File:  residue (B, A, TOL)
     If B and A are vectors of polynomial coefficients, then residue
     calculates the partial fraction expansion corresponding to the
     ratio of the two polynomials.  

     The function `residue' returns R, P, K, and E, where the vector R
     contains the residue terms, P contains the pole values, K contains
     the coefficients of a direct polynomial term (if it exists) and E
     is a vector containing the powers of the denominators in the
     partial fraction terms.

     Assuming B and A represent polynomials  P (s) and Q(s)  we have:

           P(s)    M       r(m)         N
           ---- = SUM -------------  + SUM k(i)*s^(N-i)
           Q(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
     vectors) and N is the length of the K vector.

     The argument TOL is optional, and if not specified, a default
     value of 0.001 is assumed.  The tolerance value is used to
     determine whether poles with small imaginary components are
     declared real.  It is also used to determine if two poles are
     distinct.  If the ratio of the imaginary part of a pole to the
     real part is less than TOL, the imaginary part is discarded.  If
     two poles are farther apart than TOL they are distinct.  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 implies 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)


     *See also:* poly, roots, conv, deconv, polyval, polyderiv, and
     polyinteg.


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

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

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

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

 -- Function File:  polyderiv (C)
 -- Function File: [Q] = polyderiv (B, A)
 -- Function File: [Q, R] = polyderiv (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by vector C.  If a pair of polynomials is
     given B and A, the derivative of the product is returned in Q, or
     the quotient numerator in Q and the quotient denominator in R.

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

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

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

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


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

27.5 Polynomial Interpolation
=============================

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

 -- Function File: [P, S] = polyfit (X, Y, N)
     Return the coefficients of a polynomial P(X) of degree N that
     minimizes `sumsq (p(x(i)) - y(i))',  to best fit the data in the
     least squares sense.

     The polynomial coefficients are returned in a row vector.

     If two output arguments are requested, the second is a structure
     containing the following fields:

    `R'
          The Cholesky factor of the Vandermonde matrix used to compute
          the polynomial coefficients.

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

    `df'
          The degrees of freedom.

    `normr'
          The norm of the residuals.

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

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

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

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

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

     *See also:* mkpp, unmkpp, spline.

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

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

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


     *See also:* unmkpp, ppval, spline.

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

    X
          Samples points.

    P
          Polynomial coefficients for points in sample interval. `P (I,
          :)' contains the coefficients for the polynomial over
          interval I ordered from highest to lowest. If `D > 1', `P (R,
          I, :)' contains the coeffients for the r-th polynomial
          defined on interval I. However, this is stored as a 2-D array
          such that `C = reshape (P (:, J), N, D)' gives `C (I,  R)' is
          the j-th coefficient of the r-th polynomial over the i-th
          interval.

    N
          Number of polynomial pieces.

    K
          Order of the polynomial plus 1.

    D
          Number of polynomials defined for each interval.


     *See also:* mkpp, ppval, spline.


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

27.6 Miscellaneous Functions
============================

 -- Function File:  poly (A)
     If A is a square N-by-N matrix, `poly (A)' is the row vector of
     the coefficients of `det (z * eye (N) - a)', the characteristic
     polynomial of A.  As an example we can use this to find the
     eigenvalues of A as the roots of `poly (A)'.
          roots(poly(eye(3)))
          => 1.00000 + 0.00000i
          => 1.00000 - 0.00000i
          => 1.00000 + 0.00000i
     In real-life examples you should, however, use the `eig' function
     for computing eigenvalues.

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

     *See also:* eig, roots.

 -- Function File:  polyout (C, X)
     Write formatted polynomial
             c(x) = c(1) * x^n + ... + c(n) x + c(n+1)
      and return it as a string or write it to the screen (if NARGOUT
     is zero).  X defaults to the string `"s"'.

     *See also:* polyval, polyvalm, poly, roots, conv, deconv, residue,
     filter, polyderiv, and polyinteg.

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

     *See also:* poly, roots, conv, deconv, residue, filter, polyval,
     polyvalm, polyderiv, polyinteg.


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

28 Interpolation
****************

* Menu:

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


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

28.1 One-dimensional Interpolation
==================================

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

 -- Function File: YI = interp1 (X, Y, XI)
 -- Function File: YI = interp1 (..., METHOD)
 -- Function File: YI = interp1 (..., EXTRAP)
 -- Function File: PP = interp1 (..., 'pp')
     One-dimensional interpolation. Interpolate Y, defined at the
     points X, at the points XI. The sample points X must be strictly
     monotonic. If Y is an array, treat the columns of Y seperately.

     Method is one of:

    'nearest'
          Return the nearest neighbour.

    'linear'
          Linear interpolation from nearest neighbours

    'pchip'
          Piece-wise cubic hermite interpolating polynomial

    'cubic'
          Cubic interpolation from four nearest neighbours

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

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

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

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

     An example of the use of `interp1' is

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


     *See also:* interpft.

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

   This can be demonstrated by the code

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

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

 -- Function File:  interpft (X, N)
 -- Function File:  interpft (X, N, DIM)
     Fourier interpolation. If X is a vector, then X is resampled with
     N points. The data in X is assumed to be equispaced. If X is an
     array, then operate along each column of the array seperately. If
     DIM is specified, then interpolate along the dimension DIM.

     `interpft' assumes that the interpolated function is periodic, and
     so assumption are made about the end points of the inetrpolation.


     *See also:* interp1.

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

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

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

   In additional the support function `spline' and `lookup' that
underlie the `interp1' function can be called directly.

 -- Function File: PP =  spline (X, Y)
 -- Function File: YI =  spline (X, Y, XI)
     Returns the cubic spline interpolation of Y at the point X. Called
     with two arguments the piece-wise polynomial PP that may later be
     used with `ppval' to evaluate the polynomial at specific points.

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

     If Y is an array, then the size of Y must have the form `[S1, S2,
     ..., SK, N]' or `[S1, S2, ..., SK, N + 2]'.  The array is then
     reshaped internally to a matrix where to leading dimension is
     given by `S1 * S2 * ... * SK' and each row this matrix is then
     treated seperately. Note that this is exactly the opposite
     treatment than `interp1' and is done for compatiability.

     Called with a third input argument, `spline' evaluates the
     piece-wise spline at the points XI. There is an equivalence
     between `ppval (spline (X, Y), XI)' and `spline (X, Y, XI)'.


     *See also:* ppval, mkpp, unmkpp.

   The `lookup' is used by other interpolation function to identify the
points of the original data that are closest to the current point of
interest.

 -- Function File: IDX = lookup (TABLE, Y)
     Lookup values in a sorted table.  Usually used as a prelude to
     interpolation.

     If table is strictly increasing and `idx = lookup (table, y)', then
     `table(idx(i)) <= y(i) < table(idx(i+1))' for all `y(i)' within
     the table.  If `y(i)' is before the table, then `idx(i)' is 0. If
     `y(i)' is after the table then `idx(i)' is `table(n)'.

     If the table is strictly decreasing, then the tests are reversed.
     There are no guarantees for tables which are non-monotonic or are
     not strictly monotonic.

     To get an index value which lies within an interval of the table,
     use:

          idx = lookup (table(2:length(table)-1), y) + 1

     This expression puts values before the table into the first
     interval, and values after the table into the last interval.


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

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

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

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

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

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

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

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

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

    'nearest'
          Return the nearest neighbor.

    'linear'
          Linear interpolation from nearest neighbors.

    'pchip'
          Piece-wise cubic hermite interpolating polynomial (not
          implemented yet).

    'cubic'
          Cubic interpolation from four nearest neighbors.

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

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


     *See also:* interp1.

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

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

     Method is one of:

    'nearest'
          Return the nearest neighbour.

    'linear'
          Linear interpolation from nearest neighbours.

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

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

     The default method is 'linear'.

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

     *See also:* interp1, interp2, spline, meshgrid.

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

     If X1, ..., XN are ommitted, 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 interplation points. This
     process is performed M times. If only V is specified, then M is
     assumed to be `1'.

     Method is one of:

    'nearest'
          Return the nearest neighbour.

    'linear'
          Linear interpolation from nearest neighbours.

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

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

     The default method is 'linear'.

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

     *See also:* interp1, interp2, spline, ndgrid.

   A significant difference between `interpn' and the other two
multidimensional interpolation function 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 the the array. As Octave indexes arrays in
column major order, the first dimension of any array is the columns, and
so `interpn' effectively reverses the 'x' and 'y' dimensions.  Consider
the example

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

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

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

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

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

     *See also:* interp2.


File: octave.info,  Node: Geometry,  Next: Control Theory,  Prev: Interpolation,  Up: Top

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

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

* Menu:

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

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

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


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

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

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

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

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

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

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


     *See also:* voronoi, delaunay3, delaunayn.

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

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

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

     *See also:* delaunay,delaunayn.

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

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

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

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

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

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


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

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

* Menu:

* Plotting the Triangulation::
* Identifying points in Triangulation::


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

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

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

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

     *See also:* plot, trimesh, delaunay.

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

     *See also:* triplot, delaunay3.

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

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

   that plot the Delaunay triangulation of a set of random points in
2-dimensions.


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

29.1.2 Identifying points in Triangulation
------------------------------------------

It is often necessary to identify whether a particular point in the
N-dimensional space is within the Delaunay tesselation of a set of
points in this N-dimensional space, and if so which N-Simplex contains
the point and which point in the tesselation 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
tesselation.

   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 is given by

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

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

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

is imposed, and we can therefore write the above as

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

Solving for BETA we can then write

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

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

     0 <= BETA(I) <= 1

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

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

     *See also:* delaunay, delaunayn.

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

     *See also:* delaunay, delaunayn.

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

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

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

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

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

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

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

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

     *See also:* dsearchn, tsearch.

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

     *See also:* dsearch, tsearch.

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

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

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

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

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


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

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

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

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

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

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


     *See also:* voronoin, delaunay, convhull.

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

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

     *See also:* voronoin, delaunay, convhull.

   An example of the use of `voronoi' is

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

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

 -- Function File:  polyarea (X, Y)
 -- Function File:  polyarea (X, Y, DIM)
     Determines area of a polygon by triangle method. The variables X
     and Y define the vertex pairs, and must therefore have the same
     shape. Then might be either vectors or arrays. If they are arrays
     then the columns of X and Y are treated seperately 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.

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


   An example of the use of `inpolygon' might be

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


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

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

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

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

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


     *See also:* delaunay, convhulln.

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

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


     *See also:* convhull, delaunayn.

   An example of the use of `convhull' is

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


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

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

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

 -- Function File: ZI = griddata (X, Y, Z, XI, YI, METHOD)
 -- Function File: [XI, YI, ZI] = griddata (X, Y, Z, XI, YI, METHOD)
     Generate a regular mesh from irregular data using interpolation.
     The function is defined by `Z = f (X, Y)'.  The interpolation
     points are all `(XI, YI)'.  If XI, YI are vectors then they are
     made into a 2D mesh.

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

     *See also:* delaunay.

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

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

     *See also:* griddata, delaunayn.

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

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

     *See also:* griddata, delaunayn.

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

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

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


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

30 Control Theory
*****************

The Octave Control Systems Toolbox (OCST) was initially developed by
Dr. A. Scottedward Hodel <a.s.hodel@eng.auburn.edu> with the assistance
of his students
   * R. Bruce Tenison <btenison@dibbs.net>,

   * David C. Clem,

   * John E. Ingram <John.Ingram@sea.siemans.com>, and

   * Kristi McGowan.
   This development was supported in part by NASA's Marshall Space
Flight Center as part of an in-house CACSD environment.  Additional
important contributions were made by Dr. Kai Mueller
<mueller@ifr.ing.tu-bs.de> and Jose Daniel Munoz Frias (`place.m').

   An on-line menu-driven tutorial is available via `DEMOcontrol';
beginning OCST users should start with this program.

 -- Function File:  DEMOcontrol
     Octave Control Systems Toolbox demo/tutorial program.  The demo
     allows the user to select among several categories of OCST
     function:
          octave:1> DEMOcontrol
          O C T A V E    C O N T R O L   S Y S T E M S   T O O L B O X
          Octave Controls System Toolbox Demo

            [ 1] System representation
            [ 2] Block diagram manipulations
            [ 3] Frequency response functions
            [ 4] State space analysis functions
            [ 5] Root locus functions
            [ 6] LQG/H2/Hinfinity functions
            [ 7] End
     Command examples are interactively run for users to observe
     the use of OCST functions.

     *See also:* Demo Programs: bddemo.m, frdemo.m, analdemo.m,
     moddmeo.m, rldemo.m.

* Menu:

* sysstruct::
* sysinterface::
* sysdisp::
* blockdiag::
* numerical::
* sysprop::
* systime::
* sysfreq::
* cacsd::
* misc::


File: octave.info,  Node: sysstruct,  Next: sysinterface,  Up: Control Theory

30.1 System Data Structure
==========================

* Menu:

* sysstructvars::
* sysstructtf::
* sysstructzp::
* sysstructss::

   The OCST stores all dynamic systems in a single data structure
format that can represent continuous systems, discrete-systems, and
mixed (hybrid) systems in state-space form, and can also represent
purely continuous/discrete systems in either transfer function or
pole-zero form. In order to provide more flexibility in treatment of
discrete/hybrid systems, the OCST also keeps a record of which system
outputs are sampled.

   Octave structures are accessed with a syntax much like that used by
the C programming language.  For consistency in use of the data
structure used in the OCST, it is recommended that the system structure
access m-files be used (*note sysinterface::).  Some elements of the
data structure are absent depending on the internal system
representation(s) used.  More than one system representation can be
used for SISO systems; the OCST m-files ensure that all representations
used are consistent with one another.

 -- Function File:  sysrepdemo
     Tutorial for the use of the system data structure functions.


File: octave.info,  Node: sysstructvars,  Next: sysstructtf,  Up: sysstruct

30.1.1 Variables common to all OCST system formats
--------------------------------------------------

The data structure elements (and variable types) common to all  system
representations are listed below; examples of the initialization and
use of the system data structures are given in subsequent sections and
in the online demo `DEMOcontrol'.
N
NZ
     The respective number of continuous and discrete states in the
     system (scalar)

INNAME
OUTNAME
     list of name(s) of the system input, output signal(s). (list of
     strings)

SYS
     System status vector.  (vector)

     This vector indicates both what representation was used to
     initialize the system data structure (called the primary system
     type) and which other representations are currently up-to-date
     with the primary system type (*note structaccess::).

     The value of the first element of the vector indicates the primary
     system type.

    0
          for tf form (initialized with `tf2sys' or `fir2sys')

    1
          for zp form (initialized with `zp2sys')

    2
          for ss form (initialized with `ss2sys')

     The next three elements are boolean flags that indicate whether
     tf, zp, or ss, respectively, are "up to date" (whether it is safe
     to use the variables associated with these representations).
     These flags are changed when calls are made to the `sysupdate'
     command.

TSAM
     Discrete time sampling period  (nonnegative scalar).   TSAM is set
     to 0 for continuous time systems.

YD
     Discrete-time output list (vector)

     indicates which outputs are discrete time (i.e.,     produced by
     D/A converters) and which are continuous time.      yd(ii) = 0 if
     output ii is continuous, = 1 if discrete.

   The remaining variables of the  system data structure are only
present if the corresponding entry of the `sys' vector is true (=1).


File: octave.info,  Node: sysstructtf,  Next: sysstructzp,  Prev: sysstructvars,  Up: sysstruct

30.1.2 `tf' format variables
----------------------------

NUM
     numerator coefficients   (vector)

DEN
     denominator coefficients   (vector)



File: octave.info,  Node: sysstructzp,  Next: sysstructss,  Prev: sysstructtf,  Up: sysstruct

30.1.3 `zp' format variables
----------------------------

ZER
     system zeros   (vector)

POL
     system poles    (vector)

K
     leading coefficient   (scalar)



File: octave.info,  Node: sysstructss,  Prev: sysstructzp,  Up: sysstruct

30.1.4 `ss' format variables
----------------------------

A
B
C
D
     The usual state-space matrices. If a system has both
     continuous and discrete states, they are sorted so that
     continuous states come first, then discrete states

     *Note* some functions (e.g., `bode', `hinfsyn') will not accept
     systems with both discrete and continuous states/outputs

STNAME
     names of system states   (list of strings)



File: octave.info,  Node: sysinterface,  Next: sysdisp,  Prev: sysstruct,  Up: Control Theory

30.2 System Construction and Interface Functions
================================================

Construction and manipulations of the OCST system data structure (*note
sysstruct::) requires attention to many details in order to ensure that
data structure contents remain consistent.  Users are strongly
encouraged to use the system interface functions in this section.
Functions for the formatted display in of system data structures are
given in *Note sysdisp::.

* Menu:

* fir2sys::
* ss2sys::
* tf2sys::
* zp2sys::
* structaccess::


File: octave.info,  Node: fir2sys,  Next: ss2sys,  Up: sysinterface

30.2.1 Finite impulse response system interface functions
---------------------------------------------------------

 -- Function File:  fir2sys (NUM, TSAM, INNAME, OUTNAME)
     construct a system data structure from FIR description

     *Inputs*
    NUM
          vector of coefficients [c0, c1, ..., cn] of the SISO FIR
          transfer function C(z) = c0 + c1*z^(-1) + c2*z^(-2) + ... +
          cn*z^(-n)

    TSAM
          sampling time (default: 1)

    INNAME
          name of input signal;  may be a string or a list with a
          single entry.

    OUTNAME
          name of output signal; may be a string or a list with a
          single entry.

     *Output*
    SYS
          system data structure

     *Example*
          octave:1> sys = fir2sys([1 -1 2 4],0.342,\
          > "A/D input","filter output");
          octave:2> sysout(sys)
          Input(s)
                  1: A/D input

          Output(s):
                  1: filter output (discrete)

          Sampling interval: 0.342
          transfer function form:
          1*z^3 - 1*z^2 + 2*z^1 + 4
          -------------------------
          1*z^3 + 0*z^2 + 0*z^1 + 0

 -- Function File: [C, TSAM, INPUT, OUTPUT] = sys2fir (SYS)
     Extract FIR data from system data structure; see `fir2sys' for
     parameter descriptions.

     *See also:* fir2sys.


File: octave.info,  Node: ss2sys,  Next: tf2sys,  Prev: fir2sys,  Up: sysinterface

30.2.2 State space system interface functions
---------------------------------------------

 -- Function File: OUTSYS = ss (A, B, C, D, TSAM, N, NZ, STNAME,
          INNAME, OUTNAME, OUTLIST)
     Create system structure from state-space data.   May be continous,
     discrete, or mixed (sampled data)

     *Inputs*
    A
    B
    C
    D
          usual state space matrices.

          default: D = zero matrix

    TSAM
          sampling rate.  Default: tsam = 0 (continuous system)

    N
    NZ
          number of continuous, discrete states in the system

          If TSAM is 0, n = `rows'(A), nz = 0.

          If TSAM is greater than zero, n = 0, nz = `rows'(A)

          see below for system partitioning

    STNAME
          cell array of strings of state signal names

          default (STNAME=[] on input): `x_n' for continuous states,
          `xd_n' for discrete states

    INNAME
          cell array of strings of input signal names

          default (INNAME = [] on input): `u_n'

    OUTNAME
          cell array of strings of output signal names

          default (OUTNAME = [] on input): `y_n'

    OUTLIST
          list of indices of outputs y that are sampled

          If TSAM is 0, outlist = [].

          If TSAM is greater than 0, outlist = 1:`rows'(C).

     Unlike states, discrete/continous outputs may appear in any order.

     `sys2ss' returns a vector YD where YD(OUTLIST) = 1; all other
     entries of YD are 0.

     *Output*
    OUTSYS
          system data structure

     *System partitioning*

     Suppose for simplicity that outlist specified that the first
     several outputs were continuous and the remaining outputs were
     discrete.  Then the system is partitioned as
          x = [ xc ]  (n x 1)
              [ xd ]  (nz x 1 discrete states)
          a = [ acc acd ]  b = [ bc ]
              [ adc add ]      [ bd ]
          c = [ ccc ccd ]  d = [ dc ]
              [ cdc cdd ]      [ dd ]

              (cdc = c(outlist,1:n), etc.)
     with dynamic equations: d/dt xc(t)     = acc*xc(t)      +
     acd*xd(k*tsam) + bc*u(t)

     xd((k+1)*tsam) = adc*xc(k*tsam) + add*xd(k*tsam) + bd*u(k*tsam)

     yc(t)      = ccc*xc(t)      + ccd*xd(k*tsam) + dc*u(t)

     yd(k*tsam) = cdc*xc(k*tsam) + cdd*xd(k*tsam) + dd*u(k*tsam)

     *Signal partitions*
                  | continuous      | discrete               |
          ----------------------------------------------------
          states  | stname(1:n,:)   | stname((n+1):(n+nz),:) |
          ----------------------------------------------------
          outputs | outname(cout,:) | outname(outlist,:)     |
          ----------------------------------------------------
     where cout is the list of in 1:`rows'(P) that are not
     contained in outlist. (Discrete/continuous outputs may be entered
     in any order desired by the user.)

     *Example*
          octave:1> a = [1 2 3; 4 5 6; 7 8 10];
          octave:2> b = [0 0 ; 0 1 ; 1 0];
          octave:3> c = eye (3);
          octave:4> sys = ss (a, b, c, [], 0, 3, 0, {"volts", "amps", "joules"});
          octave:5> sysout(sys);
          Input(s)
                  1: u_1
                  2: u_2

          Output(s):
                  1: y_1
                  2: y_2
                  3: y_3

          state-space form:
          3 continuous states, 0 discrete states
          State(s):
                  1: volts
                  2: amps
                  3: joules

          A matrix: 3 x 3
             1   2   3
             4   5   6
             7   8  10
          B matrix: 3 x 2
            0  0
            0  1
            1  0
          C matrix: 3 x 3
            1  0  0
            0  1  0
            0  0  1
          D matrix: 3 x 3
            0  0
            0  0
            0  0
     Notice that the D matrix is constructed  by default to the correct
     dimensions.  Default input and output signals names were assigned
     since none were given.

 -- Function File:  ss (A, B, C, D, TSAM, N, NZ, STNAME, INNAME,
          OUTNAME, OUTLIST)
     Create system structure from state-space data.   May be continous,
     discrete, or mixed (sampled data)

     *Inputs*
    A
    B
    C
    D
          usual state space matrices.

          default: D = zero matrix

    TSAM
          sampling rate.  Default: tsam = 0 (continuous system)

    N
    NZ
          number of continuous, discrete states in the system

          If TSAM is 0, n = `rows'(A), nz = 0.

          If TSAM is greater than zero, n = 0, nz = `rows'(A)

          see below for system partitioning

    STNAME
          cell array of strings of state signal names

          default (STNAME=[] on input): `x_n' for continuous states,
          `xd_n' for discrete states

    INNAME
          cell array of strings of input signal names

          default (INNAME = [] on input): `u_n'

    OUTNAME
          cell array of strings of input signal names

          default (OUTNAME = [] on input): `y_n'

    OUTLIST
          list of indices of outputs y that are sampled

          If TSAM is 0, outlist = [].

          If TSAM is greater than 0, outlist = 1:`rows'(C).

     Unlike states, discrete/continous outputs may appear in any order.

     `sys2ss' returns a vector YD where YD(OUTLIST) = 1; all other
     entries of YD are 0.

     *Outputs* OUTSYS = system data structure

     *System partitioning*

     Suppose for simplicity that outlist specified that the first
     several outputs were continuous and the remaining outputs were
     discrete.  Then the system is partitioned as
          x = [ xc ]  (n x 1)
              [ xd ]  (nz x 1 discrete states)
          a = [ acc acd ]  b = [ bc ]
              [ adc add ]      [ bd ]
          c = [ ccc ccd ]  d = [ dc ]
              [ cdc cdd ]      [ dd ]

              (cdc = c(outlist,1:n), etc.)
     with dynamic equations: d/dt xc(t)     = acc*xc(t)      +
     acd*xd(k*tsam) + bc*u(t)

     xd((k+1)*tsam) = adc*xc(k*tsam) + add*xd(k*tsam) + bd*u(k*tsam)

     yc(t)      = ccc*xc(t)      + ccd*xd(k*tsam) + dc*u(t)

     yd(k*tsam) = cdc*xc(k*tsam) + cdd*xd(k*tsam) + dd*u(k*tsam)

     *Signal partitions*
                  | continuous      | discrete               |
          ----------------------------------------------------
          states  | stname(1:n,:)   | stname((n+1):(n+nz),:) |
          ----------------------------------------------------
          outputs | outname(cout,:) | outname(outlist,:)     |
          ----------------------------------------------------
     where cout is the list of in 1:`rows'(P) that are not
     contained in outlist. (Discrete/continuous outputs may be entered
     in any order desired by the user.)

     *Example*
          octave:1> a = [1 2 3; 4 5 6; 7 8 10];
          octave:2> b = [0 0 ; 0 1 ; 1 0];
          octave:3> c = eye (3);
          octave:4> sys = ss (a, b, c, [], 0, 3, 0, {"volts", "amps", "joules"});
          octave:5> sysout(sys);
          Input(s)
                  1: u_1
                  2: u_2

          Output(s):
                  1: y_1
                  2: y_2
                  3: y_3

          state-space form:
          3 continuous states, 0 discrete states
          State(s):
                  1: volts
                  2: amps
                  3: joules

          A matrix: 3 x 3
             1   2   3
             4   5   6
             7   8  10
          B matrix: 3 x 2
            0  0
            0  1
            1  0
          C matrix: 3 x 3
            1  0  0
            0  1  0
            0  0  1
          D matrix: 3 x 3
            0  0
            0  0
            0  0
     Notice that the D matrix is constructed  by default to the correct
     dimensions.  Default input and output signals names were assigned
     since none were given.

 -- Function File: [A, B, C, D, TSAM, N, NZ, STNAME, INNAME, OUTNAME,
YD] = sys2ss (SYS)
     Extract state space representation from system data structure.

     *Input*
    SYS
          System data structure.

     *Outputs*
    A
    B
    C
    D
          State space matrices for SYS.

    TSAM
          Sampling time of SYS (0 if continuous).

    N
    NZ
          Number of continuous, discrete states (discrete states come
          last in state vector X).

    STNAME
    INNAME
    OUTNAME
          Signal names (lists of strings);  names of states, inputs,
          and outputs, respectively.

    YD
          Binary vector; YD(II) is 1 if output Y(II) is discrete
          (sampled); otherwise  YD(II) is 0.

     A warning massage is printed if the system is a mixed continuous
     and discrete system.

     *Example*
          octave:1> sys=tf2sys([1 2],[3 4 5]);
          octave:2> [a,b,c,d] = sys2ss(sys)
          a =
             0.00000   1.00000
            -1.66667  -1.33333
          b =
            0
            1
          c = 0.66667  0.33333
          d = 0


File: octave.info,  Node: tf2sys,  Next: zp2sys,  Prev: ss2sys,  Up: sysinterface

30.2.3 Transfer function system interface functions
---------------------------------------------------

 -- Function File:  tf (NUM, DEN, TSAM, INNAME, OUTNAME)
     build system data structure from transfer function format data

     *Inputs*
    NUM
    DEN
          coefficients of numerator/denominator polynomials

    TSAM
          sampling interval. default: 0 (continuous time)

    INNAME
    OUTNAME
          input/output signal names; may be a string or cell array with
          a single string entry.

     *Outputs* SYS = system data structure

     *Example*
          octave:1> sys=tf([2 1],[1 2 1],0.1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1 (discrete)
          Sampling interval: 0.1
          transfer function form:
          2*z^1 + 1
          -----------------
          1*z^2 + 2*z^1 + 1

 -- Function File:  tf2sys (NUM, DEN, TSAM, INNAME, OUTNAME)
     Build system data structure from transfer function format data.

     *Inputs*
    NUM
    DEN
          Coefficients of numerator/denominator polynomials.

    TSAM
          Sampling interval; default: 0 (continuous time).

    INNAME
    OUTNAME
          Input/output signal names; may be a string or cell array with
          a single string entry.

     *Output*
    SYS
          System data structure.

     *Example*
          octave:1> sys=tf2sys([2 1],[1 2 1],0.1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1 (discrete)
          Sampling interval: 0.1
          transfer function form:
          2*z^1 + 1
          -----------------
          1*z^2 + 2*z^1 + 1

 -- Function File: [NUM, DEN, TSAM, INNAME, OUTNAME] = sys2tf (SYS)
     Extract transfer function data from a system data structure.

     See `tf' for parameter descriptions.

     *Example*
          octave:1> sys=ss([1 -2; -1.1,-2.1],[0;1],[1 1]);
          octave:2> [num,den] = sys2tf(sys)
          num = 1.0000  -3.0000
          den = 1.0000   1.1000  -4.3000


File: octave.info,  Node: zp2sys,  Next: structaccess,  Prev: tf2sys,  Up: sysinterface

30.2.4 Zero-pole system interface functions
-------------------------------------------

 -- Function File:  zp (ZER, POL, K, TSAM, INNAME, OUTNAME)
     Create system data structure from zero-pole data.

     *Inputs*
    ZER
          vector of system zeros

    POL
          vector of system poles

    K
          scalar leading coefficient

    TSAM
          sampling period. default: 0 (continuous system)

    INNAME
    OUTNAME
          input/output signal names (lists of strings)

     *Outputs* sys: system data structure

     *Example*
          octave:1> sys=zp([1 -1],[-2 -2 0],1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1
          zero-pole form:
          1 (s - 1) (s + 1)
          -----------------
          s (s + 2) (s + 2)

 -- Function File:  zp2sys (ZER, POL, K, TSAM, INNAME, OUTNAME)
     Create system data structure from zero-pole data.

     *Inputs*
    ZER
          Vector of system zeros.

    POL
          Vector of system poles.

    K
          Scalar leading coefficient.

    TSAM
          Sampling period; default: 0 (continuous system).

    INNAME
    OUTNAME
          Input/output signal names (lists of strings).

     *Output*
    SYS
          System data structure.

     *Example*
          octave:1> sys=zp2sys([1 -1],[-2 -2 0],1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1
          zero-pole form:
          1 (s - 1) (s + 1)
          -----------------
          s (s + 2) (s + 2)

 -- Function File: [ZER, POL, K, TSAM, INNAME, OUTNAME] = sys2zp (SYS)
     Extract zero/pole/leading coefficient information from a system
     data structure.

     See `zp' for parameter descriptions.

     *Example*
          octave:1> sys=ss([1 -2; -1.1,-2.1],[0;1],[1 1]);
          octave:2> [zer,pol,k] = sys2zp(sys)
          zer = 3.0000
          pol =
            -2.6953
             1.5953
          k = 1


File: octave.info,  Node: structaccess,  Prev: zp2sys,  Up: sysinterface

30.2.5 Data structure access functions
--------------------------------------

 -- Function File:  syschnames (SYS, OPT, LIST, NAMES)
     Superseded by `syssetsignals'.

 -- Function File:  syschtsam (SYS, TSAM)
     This function changes the sampling time (tsam) of the system.
     Exits with an error if sys is purely continuous time.

 -- Function File: [N, NZ, M, P, YD] = sysdimensions (SYS, OPT)
     return the number of states, inputs, and/or outputs in the system
     SYS.

     *Inputs*
    SYS
          system data structure

    OPT
          String indicating which dimensions are desired.  Values:
         `"all"'
               (default) return all parameters as specified under
               Outputs below.

         `"cst"'
               return N= number of continuous states

         `"dst"'
               return N= number of discrete states

         `"in"'
               return N= number of inputs

         `"out"'
               return N= number of outputs

     *Outputs*
    N
          number of continuous states (or individual requested
          dimension as specified by OPT).

    NZ
          number of discrete states

    M
          number of system inputs

    P
          number of system outputs

    YD
          binary vector; YD(II) is nonzero if output II is discrete.
          yd(ii) = 0 if output II is continous


     *See also:* sysgetsignals, sysgettsam.

 -- Function File: [STNAME, INNAME, OUTNAME, YD] = sysgetsignals (SYS)
 -- Function File: SIGLIST = sysgetsignals (SYS, SIGID)
 -- Function File: SIGNAME = sysgetsignals (SYS, SIGID, SIGNUM, STRFLG)
     Get signal names from a system

     *Inputs*
    SYS
          system data structure for the state space system

    SIGID
          signal id.  String.  Must be one of
         `"in"'
               input signals

         `"out"'
               output signals

         `"st"'
               stage signals

         `"yd"'
               value of logical vector YD

    SIGNUM
          index(indices) or name(s) or signals; see `sysidx'

    STRFLG
          flag to return a string instead of a cell array;  Values:
         `0'
               (default) return a cell array (even if signum specifies
               an individual signal)

         `1'
               return a string.  Exits with an error if signum does not
               specify an individual signal.


     *Outputs*
    *If SIGID is not specified:

         STNAME
         INNAME
         OUTNAME
               signal names (cell array of strings);  names of states,
               inputs, and outputs, respectively.

         YD
               binary vector; YD(II) is nonzero if output II is
               discrete.

    *If SIGID is specified but SIGNUM is not specified:

         `sigid="in"'
               SIGLIST is set to the cell array of input names.

         `sigid="out"'
               SIGLIST is set to the cell array of output names.

         `sigid="st"'
               SIGLIST is set to the cell array of state names.

               stage signals

         `sigid="yd"'
               SIGLIST is set to logical vector indicating discrete
               outputs; SIGLIST(II) = 0 indicates that output II is
               continuous (unsampled), otherwise it is discrete.


    *If the first three input arguments are specified:
          SIGNAME is a cell array of the specified signal names (SIGID
          is `"in"', `"out"', or `"st"'), or else the logical flag
          indicating whether output(s) SIGNUM is(are) discrete
          (SIGVAL=1) or continuous (SIGVAL=0).

     *Examples* (From `sysrepdemo')
          octave> sys=ss(rand(4),rand(4,2),rand(3,4));
          octave># get all signal names
          octave> [Ast,Ain,Aout,Ayd] = sysgetsignals(sys)
          Ast =
          (
            [1] = x_1
            [2] = x_2
            [3] = x_3
            [4] = x_4
          )
          Ain =
          (
            [1] = u_1
            [2] = u_2
          )
          Aout =
          (
            [1] = y_1
            [2] = y_2
            [3] = y_3
          )
          Ayd =

            0  0  0
          octave> # get only input signal names:
          octave> Ain = sysgetsignals(sys,"in")
          Ain =
          (
            [1] = u_1
            [2] = u_2
          )
          octave> # get name of output 2 (in cell array):
          octave> Aout = sysgetsignals(sys,"out",2)
          Aout =
          (
            [1] = y_2
          )
          octave> # get name of output 2 (as string):
          octave> Aout = sysgetsignals(sys,"out",2,1)
          Aout = y_2

 -- Function File:  sysgettype (SYS)
     return the initial system type of the system

     *Input*
    SYS
          System data structure.

     *Output*
    SYSTYPE
          String indicating how the structure was initially
          constructed. Values: `"ss"', `"zp"', or `"tf"'.

     FIR initialized systems return `systype="tf"'.

 -- Function File:  syssetsignals (SYS, OPT, NAMES, SIG_IDX)
     change the names of selected inputs, outputs and states.

     *Inputs*
    SYS
          System data structure.

    OPT
          Change default name (output).

         `"out"'
               Change selected output names.

         `"in"'
               Change selected input names.

         `"st"'
               Change selected state names.

         `"yd"'
               Change selected outputs from discrete to continuous or
               from continuous to discrete.

    NAMES

         `opt = "out", "in", "st"'
               string or string array containing desired signal names
               or values.

         `opt = "yd"'
               To desired output continuous/discrete flag.  Set name to
               0 for continuous, or 1 for discrete.

    SIG_IDX
          indices or names of outputs, yd, inputs, or states whose
          respective names/values should be changed.

          Default: replace entire cell array of names/entire yd vector.

     *Outputs*
    RETSYS
          SYS with appropriate signal names changed (or YD values,
          where appropriate).

     *Example*
          octave:1> sys=ss([1 2; 3 4],[5;6],[7 8]);
          octave:2> sys = syssetsignals(sys,"st",str2mat("Posx","Velx"));
          octave:3> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1
          state-space form:
          2 continuous states, 0 discrete states
          State(s):
                  1: Posx
                  2: Velx
          A matrix: 2 x 2
            1  2
            3  4
          B matrix: 2 x 1
            5
            6
          C matrix: 1 x 2
            7  8
          D matrix: 1 x 1
          0

 -- Function File:  sysupdate (SYS, OPT)
     Update the internal representation of a system.

     *Inputs*
    SYS:
          system data structure

    OPT
          string:
         `"tf"'
               update transfer function form

         `"zp"'
               update zero-pole form

         `"ss"'
               update state space form

         `"all"'
               all of the above

     *Outputs*
    RETSYS
          Contains union of data in sys and requested data.  If
          requested data in SYS is already up to date then RETSYS=SYS.

     Conversion to `tf' or `zp' exits with an error if the system is
     mixed continuous/digital.

     *See also:* tf, ss, zp, sysout, sys2ss, sys2tf, sys2zp.

 -- Function File: [SYSTYPE, NOUT, NIN, NCSTATES, NDSTATES] = minfo
          (INMAT)
     Determines the type of system matrix.  INMAT can be a varying, a
     system, a constant, and an empty matrix.

     *Outputs*
    SYSTYPE
          Can be one of: varying, system, constant, and empty.

    NOUT
          The number of outputs of the system.

    NIN
          The number of inputs of the system.

    NCSTATES
          The number of continuous states of the system.

    NDSTATES
          The number of discrete states of the system.

 -- Function File:  sysgettsam (SYS)
     Return the sampling time of the system SYS.


File: octave.info,  Node: sysdisp,  Next: blockdiag,  Prev: sysinterface,  Up: Control Theory

30.3 System display functions
=============================

 -- Function File:  sysout (SYS, OPT)
     print out a system data structure in desired format
    SYS
          system data structure

    OPT
          Display option
         `[]'
               primary system form (default)

         `"ss"'
               state space form

         `"tf"'
               transfer function form

         `"zp"'
               zero-pole form

         `"all"'
               all of the above

 -- Function File:  tfout (NUM, DENOM, X)
     Print formatted transfer function n(s)/d(s) to the screen.  X
     defaults to the string `"s"'

     *See also:* polyval, polyvalm, poly, roots, conv, deconv, residue,
     filter, polyderiv, polyinteg, polyout.

 -- Function File:  zpout (ZER, POL, K, X)
     print formatted zero-pole form to the screen.  X defaults to the
     string `"s"'

     *See also:* polyval, polyvalm, poly, roots, conv, deconv, residue,
     filter, polyderiv, polyinteg, polyout.


File: octave.info,  Node: blockdiag,  Next: numerical,  Prev: sysdisp,  Up: Control Theory

30.4 Block Diagram Manipulations
================================

*Note systime::.

   Unless otherwise noted, all parameters (input,output) are system
data structures.

 -- Function File:  bddemo (INPUTS)
     Octave Controls toolbox demo: Block Diagram Manipulations demo.

 -- Function File:  buildssic (CLST, ULST, OLST, ILST, S1, S2, S3, S4,
          S5, S6, S7, S8)
     Form an arbitrary complex (open or closed loop) system in
     state-space form from several systems. `buildssic' can easily
     (despite its cryptic syntax) integrate transfer functions from a
     complex block diagram into a single system with one call.  This
     function is especially useful for building open loop
     interconnections for H-infinity and H-2 designs or for closing
     loops with these controllers.

     Although this function is general purpose, the use of `sysgroup'
     `sysmult', `sysconnect' and the like is recommended for standard
     operations since they can handle mixed discrete and continuous
     systems and also the names of inputs, outputs, and states.

     The parameters consist of 4 lists that describe the connections
     outputs and inputs and up to 8 systems S1-S8.  Format of the lists:
    CLST
          connection list, describes the input signal of each system.
          The maximum number of rows of Clst is equal to the sum of all
          inputs of s1-s8.

          Example: `[1 2 -1; 2 1 0]' means that:  new input 1 is old
          input 1 + output 2 - output 1, and new input 2 is old input 2
          + output 1. The order of rows is arbitrary.

    ULST
          if not empty the old inputs in vector ULST will be appended
          to the outputs. You need this if you want to "pull out" the
          input of a system. Elements are input numbers of S1-S8.

    OLST
          output list, specifiy the outputs of the resulting systems.
          Elements are output numbers of S1-S8.  The numbers are
          allowed to be negative and may appear in any order. An empty
          matrix means all outputs.

    ILST
          input list, specifiy the inputs of the resulting systems.
          Elements are input numbers of S1-S8.  The numbers are allowed
          to be negative and may appear in any order. An empty matrix
          means all inputs.

     Example:  Very simple closed loop system.
          w        e  +-----+   u  +-----+
           --->o--*-->|  K  |--*-->|  G  |--*---> y
               ^  |   +-----+  |   +-----+  |
             - |  |            |            |
               |  |            +----------------> u
               |  |                         |
               |  +-------------------------|---> e
               |                            |
               +----------------------------+

     The closed loop system GW can be optained by
          GW = buildssic([1 2; 2 -1], 2, [1 2 3], 2, G, K);

    CLST
          1st row: connect input 1 (G) with output 2 (K).

          2nd row: connect input 2 (K) with negative output 1 (G).

    ULST
          Append input of 2 (K) to the number of outputs.

    OLST
          Outputs are output of 1 (G), 2 (K) and appended output 3
          (from ULST).

    ILST
          The only input is 2 (K).

     Here is a real example:
                                   +----+
              -------------------->| W1 |---> v1
          z   |                    +----+
          ----|-------------+
              |             |
              |    +---+    v      +----+
              *--->| G |--->O--*-->| W2 |---> v2
              |    +---+       |   +----+
              |                |
              |                v
             u                  y

          min || GW   ||
                   vz   infty

     The closed loop system GW from [z, u]' to [v1, v2, y]' can be
     obtained by (all SISO systems):
          GW = buildssic([1, 4; 2, 4; 3, 1], 3, [2, 3, 5],
                         [3, 4], G, W1, W2, One);
     where "One" is a unity gain (auxillary) function with order 0.
     (e.g. `One = ugain(1);')

 -- Function File: SYS = jet707 ()
     Creates a linearized state-space model of a Boeing 707-321 aircraft
     at V=80 m/s (M = 0.26, GA0 = -3 deg, ALPHA0 = 4 deg, KAPPA = 50
     deg).

     System inputs: (1) thrust and (2) elevator angle.

     System outputs:  (1) airspeed and (2) pitch angle.

     *Reference*: R. Brockhaus: `Flugregelung' (Flight Control),
     Springer, 1994.

     *See also:* ord2.

 -- Function File:  ord2 (NFREQ, DAMP, GAIN)
     Creates a continuous 2nd order system with parameters:

     *Inputs*
    NFREQ
          natural frequency [Hz]. (not in rad/s)

    DAMP
          damping coefficient

    GAIN
          dc-gain This is steady state value only for damp > 0.  gain
          is assumed to be 1.0 if ommitted.

     *Output*
    OUTSYS
          system data structure has representation with w = 2 * pi *
          nfreq:
                   /                                        \
                   | / -2w*damp -w \  / w \                 |
               G = | |             |, |   |, [ 0  gain ], 0 |
                   | \   w       0 /  \ 0 /                 |
                   \                                        /
*See also* `jet707' (MIMO example, Boeing 707-321
     aircraft model)

 -- Function File:  sysadd (GSYS, HSYS)
     returns SYS = GSYS + HSYS.
        * Exits with an error if GSYS and HSYS are not compatibly
          dimensioned.

        * Prints a warning message is system states have identical
          names; duplicate names are given a suffix to make them unique.

        * SYS input/output names are taken from GSYS.

                    ________
               ----|  gsys  |---
          u   |    ----------  +|
          -----                (_)----> y
              |     ________   +|
               ----|  hsys  |---
                    --------

 -- Function File: SYS = sysappend (SYST, B, C, D, OUTNAME, INNAME, YD)
     appends new inputs and/or outputs to a system

     *Inputs*
    SYST
          system data structure

    B
          matrix to be appended to sys "B" matrix (empty if none)

    C
          matrix to be appended to sys "C" matrix (empty if none)

    D
          revised sys d matrix (can be passed as [] if the revised d is
          all zeros)

    OUTNAME
          list of names for new outputs

    INNAME
          list of names for new inputs

    YD
          binary vector; yd(ii)=0 indicates a continuous output;
          yd(ii)=1 indicates a discrete output.

     *Outputs*
    SYS
                  sys.b := [syst.b , b]
                  sys.c := [syst.c  ]
                           [ c     ]
                  sys.d := [syst.d | D12 ]
                           [ D21   | D22 ]
          where D12, D21, and D22 are the appropriate dimensioned
          blocks of the input parameter D.
             * The leading block D11 of D is ignored.

             * If INNAME and OUTNAME are not given as arguments,
               the new inputs and outputs are be assigned default names.

             * YD is a binary vector of length rows(c) that indicates
                 continuous/sampled outputs.  Default value for YD is:
                  - SYS is continuous or mixed YD = `zeros(1,rows(c))'

                  - SYS is discrete YD = `ones(1,rows(c))'

 -- Function File: CLSYS = sysconnect (SYS, OUT_IDX, IN_IDX, ORDER, TOL)
     Close the loop from specified outputs to respective specified
     inputs

     *Inputs*
    SYS
          System data structure.

    OUT_IDX
    IN_IDX
          Names or indices of signals to connect (see `sysidx').  The
          output specified by out_idx(ii) is connected to the input
          specified by in_idx(ii).

    ORDER
          logical flag (default = 0)
         `0'
               Leave inputs and outputs in their original order.

         `1'
               Permute inputs and outputs to the order shown in the
               diagram below.

    TOL
          Tolerance for singularities in algebraic loops, default:
          200`eps'.

     *Outputs*
    CLSYS
          Resulting closed loop system.

     *Method*

     `sysconnect' internally permutes selected inputs, outputs as shown
     below, closes the loop, and then permutes inputs and outputs back
     to their original order
                           --------------------
           u_1       ----->|                  |----> y_1
                           |        sys       |
                   old u_2 |                  |
          u_2* ---->(+)--->|                  |----->y_2
          (in_idx)   ^     --------------------    | (out_idx)
                     |                             |
                     -------------------------------
     The input that has the summing junction added to it has an *
     added to the end  of the input name.

 -- Function File: [CSYS, ACD, CCD] = syscont (SYS)
     Extract the purely continuous subsystem of an input system.

     *Input*
    SYS
          system data structure.

     *Outputs*
    CSYS
          is the purely continuous input/output connections of SYS

    ACD
    CCD
          connections from discrete states to continuous states,
          discrete states to continuous outputs, respectively.

          returns CSYS empty if no continuous/continous path exists

 -- Function File: [DSYS, ADC, CDC] = sysdisc (SYS)
     *Input*
    SYS
          System data structure.

     *Outputs*
    DSYS
          Purely discrete portion of sys (returned empty if there is no
          purely discrete path from inputs to outputs).

    ADC
    CDC
          Connections from continuous states to discrete states and
          discrete.  outputs, respectively.

 -- Function File: RETSYS = sysdup (ASYS, OUT_IDX, IN_IDX)
     Duplicate specified input/output connections of a system

     *Inputs*
    ASYS
          system data structure

    OUT_IDX
    IN_IDX
          indices or names of desired signals (see `sigidx').
          duplicates are made of `y(out_idx(ii))' and `u(in_idx(ii))'.

     *Output*
    RETSYS
          Resulting closed loop system: duplicated i/o names are
          appended with a `"+"' suffix.

     *Method*

     `sysdup' creates copies of selected inputs and outputs as shown
     below.  U1, Y1 is the set of original inputs/outputs, and U2, Y2
     is the set of duplicated inputs/outputs in the order specified in
     IN_IDX, OUT_IDX, respectively
                    ____________________
          u1  ----->|                  |----> y1
                    |       asys       |
          u2 ------>|                  |----->y2
          (in_idx)  -------------------- (out_idx)

 -- Function File: SYS = sysgroup (ASYS, BSYS)
     Combines two systems into a single system.

     *Inputs*
    ASYS
    BSYS
          System data structures.

     *Output*
    SYS
          sys = block diag(asys,bsys)

                   __________________
                   |    ________    |
          u1 ----->|--> | asys |--->|----> y1
                   |    --------    |
                   |    ________    |
          u2 ----->|--> | bsys |--->|----> y2
                   |    --------    |
                   ------------------
                        Ksys
     The function also rearranges the internal state-space
     realization of SYS so that the continuous states come first and
     the discrete states come last.  If there are duplicate names, the
     second name has a unique suffix appended on to the end of the name.

 -- Function File: SYS = sysmult (ASYS, BSYS)
     Compute sys = Asys*Bsys (series connection):
          u   ----------     ----------
          --->|  Bsys  |---->|  Asys  |--->
              ----------     ----------
     A warning occurs if there is direct feed-through from an input
     or a continuous state of BSYS, through a discrete output of BSYS,
     to a continuous state or output in ASYS (system data structure
     does not recognize discrete inputs).

 -- Function File: RETSYS = sysprune (ASYS, OUT_IDX, IN_IDX)
     Extract specified inputs/outputs from a system

     *Inputs*
    ASYS
          system data structure

    OUT_IDX
    IN_IDX
          Indices or signal names of the outputs and inputs to be kept
          in the returned system; remaining connections are "pruned"
          off.  May select as [] (empty matrix) to specify all
          outputs/inputs.

               retsys = sysprune (Asys, [1:3,4], "u_1");
               retsys = sysprune (Asys, {"tx", "ty", "tz"}, 4);


     *Output*
    RETSYS
          Resulting system.

                     ____________________
          u1 ------->|                  |----> y1
           (in_idx)  |       Asys       | (out_idx)
          u2 ------->|                  |----| y2
            (deleted)-------------------- (deleted)

 -- Function File: PV = sysreorder (VLEN, LIST)
     *Inputs*
    VLEN
          Vector length.

    LIST
          A subset of `[1:vlen]'.

     *Output*
    PV
          A permutation vector to order elements of `[1:vlen]' in
          `list' to the end of a vector.

     Used internally by `sysconnect' to permute vector elements to their
     desired locations.

 -- Function File: RETSYS = sysscale (SYS, OUTSCALE, INSCALE, OUTNAME,
          INNAME)
     scale inputs/outputs of a system.

     *Inputs*
    SYS
          Structured system.

    OUTSCALE
    INSCALE
          Constant matrices of appropriate dimension.

    OUTNAME
    INNAME
          Lists of strings with the names of respectively outputs and
          inputs.

     *Output*
    RETSYS
          resulting open loop system:
                     -----------    -------    -----------
               u --->| inscale |--->| sys |--->| outscale |---> y
                     -----------    -------    -----------
     If the input names and output names (each a list of strings)
     are not given and the scaling matrices are not square, then
     default names will be given to the inputs and/or outputs.

     A warning message is printed if outscale attempts to add continuous
     system outputs to discrete system outputs; otherwise YD is set
     appropriately in the returned value of SYS.

 -- Function File: SYS = syssub (GSYS, HSYS)
     Return sys = Gsys - Hsys.

     *Method*

     GSYS and HSYS are connected in parallel.  The input vector is
     connected to both systems; the outputs are subtracted.  Returned
     system names are those of GSYS.
                   +--------+
              +--->|  Gsys  |---+
              |    +--------+   |
              |                +|
          u --+                (_)--> y
              |                -|
              |    +--------+   |
              +--->|  Hsys  |---+
                   +--------+

 -- Function File:  ugain (N)
     Creates a system with unity gain, no states.  This trivial system
     is sometimes needed to create arbitrary complex systems from
     simple systems with `buildssic'.  Watch out if you are forming
     sampled systems since `ugain' does not contain a sampling period.

     *See also:* hinfdemo, jet707.

 -- Function File: W = wgt1o (VL, VH, FC)
     State space description of a first order weighting function.

     Weighting function are needed by the H-2/H-infinity design
     procedure.  These function are part of the augmented plant P (see
     `hinfdemo' for an application example).

     *Inputs*
    VL
          Gain at low frequencies.

    VH
          Gain at high frequencies.

    FC
          Corner frequency (in Hz, *not* in rad/sec)

     *Output*
    W
          Weighting function, given in form of a system data structure.

 -- Function File: KSYS = parallel (ASYS, BSYS)
     Forms the parallel connection of two systems.

                       --------------------
                       |      --------    |
              u  ----->|----> | asys |--->|----> y1
                  |    |      --------    |
                  |    |      --------    |
                  |--->|----> | bsys |--->|----> y2
                       |      --------    |
                       --------------------
                            ksys

 -- Function File: [RETSYS, NC, NO] = sysmin (SYS, FLG)
     Returns a minimal (or reduced order) system

     *Inputs*
    SYS
          System data structure

    FLG
          When equal to 0 (default value), returns minimal system, in
          which state names are lost; when equal to 1, returns system
          with physical states removed that are either uncontrollable or
          unobservable (cannot reduce further without discarding
          physical meaning of states).
     *Outputs*
    RETSYS
          Returned system.

    NC
          Number of controllable states in the returned system.

    NO
          Number of observable states in the returned system.

    CFLG
          `is_controllable(retsys)'.

    OFLG
          `is_observable(retsys)'.


File: octave.info,  Node: numerical,  Next: sysprop,  Prev: blockdiag,  Up: Control Theory

30.5 Numerical Functions
========================

 -- Function File: X = are (A, B, C, OPT)
     Solve the Algebraic Riccati Equation
          a' * x + x * a - x * b * x + c = 0

     *Inputs* for identically dimensioned square matrices
    A
          N by N matrix;

    B
          N by N matrix or N by M matrix; in the latter case B is
          replaced by b:=b*b';

    C
          N by N matrix or P by M matrix; in the latter case C is
          replaced by c:=c'*c;

    OPT
          (optional argument; default = `"B"'): String option passed to
          `balance' prior to ordered Schur decomposition.

     *Output*
    X
          solution of the ARE.

     *Method* Laub's Schur method (IEEE Transactions on Automatic
     Control, 1979) is applied to the appropriate Hamiltonian matrix.

     *See also:* balance, dare.

 -- Function File: X = dare (A, B, Q, R, OPT)
     Return the solution, X of the discrete-time algebraic Riccati
     equation
          a' x a - x + a' x b (r + b' x b)^(-1) b' x a + q = 0
     *Inputs*
    A
          N by N matrix;

    B
          N by M matrix;

    Q
          N by N matrix, symmetric positive semidefinite, or a P by N
          matrix, In the latter case q:=q'*q is used;

    R
          M by M, symmetric positive definite (invertible);

    OPT
          (optional argument; default = `"B"'): String option passed to
          `balance' prior to ordered QZ decomposition.

     *Output*
    X
          solution of DARE.

     *Method* Generalized eigenvalue approach (Van Dooren; SIAM J.
     Sci. Stat. Comput., Vol 2) applied  to the appropriate symplectic
     pencil.

     See also: Ran and Rodman, `Stable Hermitian Solutions of Discrete
     Algebraic Riccati Equations', Mathematics of Control, Signals and
     Systems, Vol 5, no 2 (1992), pp 165-194.

     *See also:* balance, are.

 -- Function File: [TVALS, PLIST] = dre (SYS, Q, R, QF, T0, TF, PTOL,
          MAXITS)
     Solve the differential Riccati equation
            -d P/dt = A'P + P A - P B inv(R) B' P + Q
            P(tf) = Qf
     for the LTI system sys.  Solution of standard LTI state feedback
     optimization
            min int(t0, tf) ( x' Q x + u' R u ) dt + x(tf)' Qf x(tf)
     optimal input is
            u = - inv(R) B' P(t) x
     *Inputs*
    SYS
          continuous time system data structure

    Q
          state integral penalty

    R
          input integral penalty

    QF
          state terminal penalty

    T0
    TF
          limits on the integral

    PTOL
          tolerance (used to select time samples; see below); default =
          0.1

    MAXITS
          number of refinement iterations (default=10)
     *Outputs*
    TVALS
          time values at which P(T) is computed

    PLIST
          list values of P(T); PLIST { I } is P(TVALS(I))
     TVALS is selected so that:
          || Plist{i} - Plist{i-1} || < Ptol
     for every I between 2 and length(TVALS).

 -- Function File:  dgram (A, B)
     Return controllability gramian of discrete time system
            x(k+1) = a x(k) + b u(k)

     *Inputs*
    A
          N by N matrix

    B
          N by M matrix

     *Output*
    M
          N by N matrix, satisfies
                a m a' - m + b*b' = 0

 -- Function File:  dlyap (A, B)
     Solve the discrete-time Lyapunov equation

     *Inputs*
    A
          N by N matrix;

    B
          Matrix: N by N, N by M, or P by N.

     *Output*
    X
          matrix satisfying appropriate discrete time Lyapunov equation.

     Options:
        * B is square: solve `a x a' - x + b = 0'

        * B is not square: X satisfies either
               a x a' - x + b b' = 0
          or
               a' x a - x + b' b = 0,
          whichever is appropriate.

     *Method* Uses Schur decomposition method as in Kitagawa, `An
     Algorithm for Solving the Matrix Equation X = F X F' + S',
     International Journal of Control, Volume 25, Number 5, pages
     745-753 (1977).

     Column-by-column solution method as suggested in Hammarling,
     `Numerical Solution of the Stable, Non-Negative Definite Lyapunov
     Equation', IMA Journal of Numerical Analysis, Volume 2, pages
     303-323 (1982).

 -- Function File:  gram (A, B)
     Return controllability gramian M of the continuous time system
     dx/dt = a x + b u.

     M satisfies a m + m a' + b b' = 0.

 -- Function File:  lyap (A, B, C)
 -- Function File:  lyap (A, B)
     Solve the Lyapunov (or Sylvester) equation via the Bartels-Stewart
     algorithm (Communications of the ACM, 1972).

     If A, B, and C are specified, then `lyap' returns the solution of
     the  Sylvester equation
              a x + x b + c = 0
     If only `(a, b)' are specified, then `lyap' returns the solution
     of the Lyapunov equation
              a' x + x a + b = 0
     If B is not square, then `lyap' returns the solution of either
              a' x + x a + b' b = 0
     or
              a x + x a' + b b' = 0
     whichever is appropriate.

     Solves by using the Bartels-Stewart algorithm (1972).

 -- Function File:  qzval (A, B)
     Compute generalized eigenvalues of the matrix pencil
          (A - lambda B).

     A and B must be real matrices.

     `qzval' is obsolete; use `qz' instead.

 -- Function File: Y = zgfmul (A, B, C, D, X)
     Compute product of ZGEP incidence matrix F with vector X.  Used by
     `zgepbal' (in `zgscal') as part of generalized conjugate gradient
     iteration.

 -- Function File:  zgfslv (N, M, P, B)
     Solve system of equations for dense zgep problem.

 -- Function File: ZZ = zginit (A, B, C, D)
     Construct right hand side vector ZZ for the zero-computation
     generalized eigenvalue problem balancing procedure.  Called by
     `zgepbal'.

 -- Function File:  zgreduce (SYS, MEPS)
     Implementation of procedure REDUCE in (Emami-Naeini and Van Dooren,
     Automatica, # 1982).

 -- Function File: [NONZ, ZER] = zgrownorm (MAT, MEPS)
     Return NONZ = number of rows of MAT whose two norm exceeds MEPS,
     and ZER = number of rows of mat whose two norm is less than MEPS.

 -- Function File: X = zgscal (F, Z, N, M, P)
     Generalized conjugate gradient iteration to solve zero-computation
     generalized eigenvalue problem balancing equation fx=z; called by
     `zgepbal'.

 -- Function File: [a, b] = zgsgiv (C, S, A, B)
     Apply givens rotation c,s to row vectors A, B.  No longer used in
     zero-balancing (__zgpbal__); kept for backward compatibility.

 -- Function File: X = zgshsr (Y)
     Apply householder vector based on e^(m) to column vector Y.
     Called by `zgfslv'.

   *References*
*ZGEP*
     Hodel, `Computation of Zeros with Balancing', 1992, Linear Algebra
     and its Applications

**Generalized CG**
     Golub and Van Loan, `Matrix Computations, 2nd ed' 1989.


File: octave.info,  Node: sysprop,  Next: systime,  Prev: numerical,  Up: Control Theory

30.6 System Analysis-Properties
===============================

 -- Function File:  analdemo ()
     Octave Controls toolbox demo: State Space analysis demo

 -- Function File: [N, M, P] = abcddim (A, B, C, D)
     Check for compatibility of the dimensions of the matrices defining
     the linear system [A, B, C, D] corresponding to

          dx/dt = a x + b u
          y = c x + d u

     or a similar discrete-time system.

     If the matrices are compatibly dimensioned, then `abcddim' returns

    N
          The number of system states.

    M
          The number of system inputs.

    P
          The number of system outputs.

     Otherwise `abcddim' returns N = M = P = -1.

     Note: n = 0 (pure gain block) is returned without warning.

     *See also:* is_abcd.

 -- Function File:  ctrb (SYS, B)
 -- Function File:  ctrb (A, B)
     Build controllability matrix:
                       2       n-1
          Qs = [ B AB A B ... A   B ]

     of a system data structure or the pair (A, B).

     `ctrb' forms the controllability matrix.  The numerical properties
     of `is_controllable' are much better for controllability tests.

 -- Function File:  h2norm (SYS)
     Computes the H-2 norm of a system data structure (continuous time
     only).

     Reference: Doyle, Glover, Khargonekar, Francis, `State-Space
     Solutions to Standard' `H-2 and H-infinity' `Control Problems',
     IEEE TAC August 1989.

 -- Function File: [G, GMIN, GMAX] = hinfnorm (SYS, TOL, GMIN, GMAX,
          PTOL)
     Computes the H-infinity norm of a system data structure.

     *Inputs*
    SYS
          system data structure

    TOL
          H-infinity norm search tolerance (default: 0.001)

    GMIN
          minimum value for norm search (default: 1e-9)

    GMAX
          maximum value for norm search (default: 1e+9)

    PTOL
          pole tolerance:
             * if sys is continuous, poles with  |real(pole))| <
               ptol*||H||  (H is appropriate Hamiltonian) are
               considered to be on the imaginary axis.

             * if sys is discrete, poles with |abs(pole)-1| <
               ptol*||[s1,s2]|| (appropriate symplectic pencil) are
               considered to be on the unit circle.

             * Default value: 1e-9

     *Outputs*
    G
          Computed gain, within TOL of actual gain.  G is returned as
          Inf if the system is unstable.

    GMIN
    GMAX
          Actual system gain lies in the interval [GMIN, GMAX].

     References: Doyle, Glover, Khargonekar, Francis, `State-space
     solutions to standard' `H-2 and H-infinity' `control problems',
     IEEE TAC August 1989; Iglesias and Glover, `State-Space approach
     to discrete-time' `H-infinity' `control', Int. J. Control, vol 54,
     no. 5, 1991; Zhou, Doyle, Glover, `Robust and Optimal Control',
     Prentice-Hall, 1996.

 -- Function File:  obsv (SYS, C)
 -- Function File:  obsv (A, C)
     Build observability matrix:
               | C        |
               | CA       |
          Qb = | CA^2     |
               | ...      |
               | CA^(n-1) |
     of a system data structure or the pair (A, C).

     The numerical properties of `is_observable' are much better for
     observability tests.

 -- Function File: [ZER, POL] = pzmap (SYS)
     Plots the zeros and poles of a system in the complex plane.

     *Input*
    SYS
          System data structure.

     *Outputs*
    POL

    ZER
          if omitted, the poles and zeros are plotted on the screen.
          otherwise, POL and ZER are returned as the system poles and
          zeros (see `sys2zp' for a preferable function call).

 -- Function File: RETVAL = is_abcd (A, B, C, D)
     Returns RETVAL = 1 if the dimensions of A, B, C, D are compatible,
     otherwise RETVAL = 0 with an  appropriate diagnostic message
     printed to the screen.  The matrices B, C, or D may be omitted.

     *See also:* abcddim.

 -- Function File: [RETVAL, U] = is_controllable (SYS, TOL)
 -- Function File: [RETVAL, U] = is_controllable (A, B, TOL)
     Logical check for system controllability.

     *Inputs*
    SYS
          system data structure

    A
    B
          N by N, N by M matrices, respectively

    TOL
          optional roundoff parameter.  Default value: `10*eps'

     *Outputs*
    RETVAL
          Logical flag; returns true (1) if the system SYS or the pair
          (A, B) is controllable, whichever was passed as input
          arguments.

    U
          U is an orthogonal basis of the controllable subspace.

     *Method* Controllability is determined by applying Arnoldi
     iteration with complete re-orthogonalization to obtain an
     orthogonal basis of the Krylov subspace
          span ([b,a*b,...,a^{n-1}*b]).
     The Arnoldi iteration is executed with `krylov' if the system has
     a single input; otherwise a block Arnoldi iteration is performed
     with `krylovb'.

     *See also:* size, rows, columns, length, ismatrix, isscalar,
     isvector is_observable, is_stabilizable, is_detectable, krylov,
     krylovb.

 -- Function File: RETVAL = is_detectable (A, C, TOL, DFLG)
 -- Function File: RETVAL = is_detectable (SYS, TOL)
     Test for detactability (observability of unstable modes) of (A, C).

     Returns 1 if the system A or the pair (A, C) is detectable, 0 if
     not, and -1 if the system has unobservable modes at the imaginary
     axis (unit circle for discrete-time systems).

     *See* `is_stabilizable' for detailed description of arguments and
     computational method.

     *See also:* is_stabilizable, size, rows, columns, length, ismatrix,
     isscalar, isvector.

 -- Function File: [RETVAL, DGKF_STRUCT ] = is_dgkf (ASYS, NU, NY, TOL )
     Determine whether a continuous time state space system meets
     assumptions of DGKF algorithm.  Partitions system into:
          [dx/dt]   [A  | Bw  Bu  ][w]
          [ z   ] = [Cz | Dzw Dzu ][u]
          [ y   ]   [Cy | Dyw Dyu ]
     or similar discrete-time system.  If necessary, orthogonal
     transformations QW, QZ and nonsingular transformations RU, RY are
     applied to respective vectors W, Z, U, Y in order to satisfy DGKF
     assumptions.  Loop shifting is used if DYU block is nonzero.

     *Inputs*
    ASYS
          system data structure

    NU
          number of controlled inputs

    NY
          number of measured outputs

    TOL
          threshold for 0; default: 200*`eps'.
     *Outputs*
    RETVAL
          true(1) if system passes check, false(0) otherwise

    DGKF_STRUCT
          data structure of `is_dgkf' results.  Entries:
         NW
         NZ
               dimensions of W, Z

         A
               system A matrix

         BW
               (N x NW) QW-transformed disturbance input matrix

         BU
               (N x NU) RU-transformed controlled input matrix;

               B = [Bw Bu]

         CZ
               (NZ x N) Qz-transformed error output matrix

         CY
               (NY x N) RY-transformed measured output matrix

               C = [Cz; Cy]

         DZU

         DYW
               off-diagonal blocks of transformed system D matrix that
               enter Z, Y from U, W respectively

         RU
               controlled input transformation matrix

         RY
               observed output transformation matrix

         DYU_NZ
               nonzero if the DYU block is nonzero.

         DYU
               untransformed DYU block

         DFLG
               nonzero if the system is discrete-time
     `is_dgkf' exits with an error if the system is mixed
     discrete/continuous.

     *References*
    *[1]*
          Doyle, Glover, Khargonekar, Francis, `State Space Solutions
          to Standard' `H-2 and H-infinity' `Control Problems', IEEE
          TAC August 1989.

    *[2]*
          Maciejowksi, J.M., `Multivariable Feedback Design',
          Addison-Wesley, 1989.

 -- Function File: DIGITAL = is_digital (SYS, EFLG)
     Return nonzero if system is digital.

     *Inputs*
    SYS
          System data structure.

    EFLG
          When equal to 0 (default value), exits with an error if the
          system is mixed (continuous and discrete components); when
          equal to 1, print a warning if the system is mixed
          (continuous and discrete); when equal to 2, operate silently.

     *Output*
    DIGITAL
          When equal to 0, the system is purely continuous; when equal
          to 1, the system is purely discrete; when equal to -1, the
          system is mixed continuous and discrete.
     Exits with an error if SYS is a mixed (continuous and discrete)
     system.

 -- Function File: [RETVAL, U] = is_observable (A, C, TOL)
 -- Function File: [RETVAL, U] = is_observable (SYS, TOL)
     Logical check for system observability.

     Default: tol = `tol = 10*norm(a,'fro')*eps'

     Returns 1 if the system SYS or the pair (A, C) is observable, 0 if
     not.

     See `is_controllable' for detailed description of arguments and
     default values.

     *See also:* size, rows, columns, length, ismatrix, isscalar,
     isvector.

 -- Function File:  is_sample (TS)
     Return true if TS is a valid sampling time (real, scalar, > 0).

 -- Function File:  is_siso (SYS)
     Returns nonzero if the system data structure SYS is single-input,
     single-output.

 -- Function File: RETVAL = is_stabilizable (SYS, TOL)
 -- Function File: RETVAL = is_stabilizable (A, B, TOL, DFLG)
     Logical check for system stabilizability (i.e., all unstable modes
     are controllable).  Returns 1 if the system is stabilizable, 0 if
     the system is not stabilizable, -1 if the system has non
     stabilizable modes at the imaginary axis (unit circle for
     discrete-time systems.

     Test for stabilizability is performed via Hautus Lemma. If DFLG!=0
     assume that discrete-time matrices (a,b) are supplied.

     *See also:* size, rows, columns, length, ismatrix, isscalar,
     isvector is_observable, is_stabilizable, is_detectable.

 -- Function File:  is_signal_list (MYLIST)
     Return true if MYLIST is a list of individual strings.

 -- Function File:  is_stable (A, TOL, DFLG)
 -- Function File:  is_stable (SYS, TOL)
     Returns 1 if the matrix A or the system SYS is stable, or 0 if not.

     *Inputs*
    TOL
          is a roundoff parameter, set to 200*`eps' if omitted.

    DFLG
          Digital system flag (not required for system data structure):
         `DFLG != 0'
               stable if eig(a) is in the unit circle

         `DFLG == 0'
               stable if eig(a) is in the open LHP (default)


     *See also:* size, rows, columns, length, ismatrix, isscalar,
     isvector is_observable, is_stabilizable, is_detectable, krylov,
     krylovb.


File: octave.info,  Node: systime,  Next: sysfreq,  Prev: sysprop,  Up: Control Theory

30.7 System Analysis-Time Domain
================================

 -- Function File:  c2d (SYS, OPT, T)
 -- Function File:  c2d (SYS, T)
     Converts the system data structure describing:
          .
          x = Ac x + Bc u
     into a discrete time equivalent model:
          x[n+1] = Ad x[n] + Bd u[n]
     via the matrix exponential or bilinear transform.

     *Inputs*
    SYS
          system data structure (may have both continuous time and
          discrete time subsystems)

    OPT
          string argument; conversion option (optional argument; may be
          omitted as shown above)
         `"ex"'
               use the matrix exponential (default)

         `"bi"'
               use the bilinear transformation
                        2(z-1)
                    s = -----
                        T(z+1)
               FIXME: This option exits with an error if SYS is not
               purely continuous. (The `ex' option can handle mixed
               systems.)

         `"matched"'
               Use the matched pole/zero equivalent transformation
               (currently only works for purely continuous SISO
               systems).

    T
          sampling time; required if SYS is purely continuous.

          *Note* that if the second argument is not a string, `c2d()'
          assumes that the second argument is T and performs
          appropriate argument checks.

     *Output*
    DSYS
          Discrete time equivalent via zero-order hold, sample each T
          sec.

     This function adds the suffix  `_d' to the names of the new
     discrete states.

 -- Function File:  d2c (SYS, TOL)
 -- Function File:  d2c (SYS, OPT)
     Convert a discrete (sub)system into a purely continuous one.  The
     sampling time used is `sysgettsam(SYS)'.

     *Inputs*
    SYS
          system data structure with discrete components

    TOL
          Scalar value.  Tolerance for convergence of default `"log"'
          option (see below)

    OPT
          conversion option.  Choose from:
         `"log"'
               (default) Conversion is performed via a matrix logarithm.
               Due to some problems with this computation, it is
               followed by a steepest descent algorithm to identify
               continuous time A, B, to get a better fit to the
               original data.

               If called as `d2c (SYS, TOL)', with TOL positive scalar,
               the `"log"' option is used.  The default value for TOL
               is `1e-8'.

         `"bi"'
               Conversion is performed via bilinear transform z = (1 +
               s T / 2)/(1 - s T / 2) where T is the system sampling
               time (see `sysgettsam').

               FIXME: bilinear option exits with an error if SYS is not
               purely discrete
     *Output*
    CSYS
          continuous time system (same dimensions and signal names as
          in SYS).

 -- Function File: [DSYS, FIDX] = dmr2d (SYS, IDX, SPREFIX, TS2, CUFLG)
     convert a multirate digital system to a single rate digital system
     states specified by IDX, SPREFIX are sampled at TS2, all others
     are assumed sampled at TS1 = `sysgettsam (SYS)'.

     *Inputs*
    SYS
          discrete time system; `dmr2d' exits with an error if SYS is
          not discrete

    IDX
          indices or names of states with sampling time
          `sysgettsam(SYS)' (may be empty); see `cellidx'

    SPREFIX
          list of string prefixes of states with sampling time
          `sysgettsam(SYS)' (may be empty)

    TS2
          sampling time of states not specified by IDX, SPREFIX must be
          an integer multiple of `sysgettsam(SYS)'

    CUFLG
          "constant u flag" if CUFLG is nonzero then the system inputs
          are assumed to be constant over the revised sampling interval
          TS2.  Otherwise, since the inputs can change during the
          interval T in [k ts2, (k+1) ts2], an additional set of inputs
          is included in the revised B matrix so that these intersample
          inputs may be included in the single-rate system.  default
          CUFLG = 1.

     *Outputs*
    DSYS
          equivalent discrete time system with sampling time TS2.

          The sampling time of sys is updated to TS2.

          if CUFLG=0 then a set of additional inputs is added to the
          system with suffixes _d1, ..., _dn to indicate their delay
          from the starting time k TS2, i.e.  u = [u_1; u_1_d1; ...,
          u_1_dn] where u_1_dk is the input k*ts1 units of time after
          u_1 is sampled. (TS1 is the original sampling time of the
          discrete time system and TS2 = (n+1)*ts1)

    FIDX
          indices of "formerly fast" states specified by IDX and
          SPREFIX; these states are updated to the new (slower)
          sampling interval TS2.

     *WARNING* Not thoroughly tested yet; especially when CUFLG == 0.

 -- Function File:  damp (P, TSAM)
     Displays eigenvalues, natural frequencies and damping ratios of
     the eigenvalues of a matrix P or the A matrix of a system P,
     respectively.  If P is a system, TSAM must not be specified.  If P
     is a matrix and TSAM is specified, eigenvalues of P are assumed to
     be in Z-domain.

     *See also:* eig.

 -- Function File:  dcgain (SYS, TOL)
     Returns dc-gain matrix. If dc-gain is infinite an empty matrix is
     returned.  The argument TOL is an optional tolerance for the
     condition number of the A Matrix in SYS (default TOL = 1.0e-10)

 -- Function File: [Y, T] = impulse (SYS, INP, TSTOP, N)
     Impulse response for a linear system.  The system can be discrete
     or multivariable (or both).  If no output arguments are specified,
     `impulse' produces a plot or the impulse response data for system
     SYS.

     *Inputs*
    SYS
          System data structure.

    INP
          Index of input being excited

    TSTOP
          The argument TSTOP (scalar value) denotes the time when the
          simulation should end.

    N
          the number of data values.

          Both parameters TSTOP and N can be omitted and will be
          computed from the eigenvalues of the A Matrix.
     *Outputs*
    Y
          Values of the impulse response.

    T
          Times of the impulse response.


     *See also:* step, __stepimp__.

 -- Function File: [Y, T] = step (SYS, INP, TSTOP, N)
     Step response for a linear system.  The system can be discrete or
     multivariable (or both).  If no output arguments are specified,
     `step' produces a plot or the step response data for system SYS.

     *Inputs*
    SYS
          System data structure.

    INP
          Index of input being excited

    TSTOP
          The argument TSTOP (scalar value) denotes the time when the
          simulation should end.

    N
          the number of data values.

          Both parameters TSTOP and N can be omitted and will be
          computed from the eigenvalues of the A Matrix.
     *Outputs*
    Y
          Values of the step response.

    T
          Times of the step response.

     When invoked with the output parameter Y the plot is not displayed.

     *See also:* impulse, __stepimp__.


File: octave.info,  Node: sysfreq,  Next: cacsd,  Prev: systime,  Up: Control Theory

30.8 System Analysis-Frequency Domain
=====================================

*Demonstration/tutorial script*

 -- Function File:  frdemo ()
     Octave Control Toolbox demo: Frequency Response demo.

 -- Function File: [MAG, PHASE, W] = bode (SYS, W, OUT_IDX, IN_IDX)
     If no output arguments are given: produce Bode plots of a system;
     otherwise, compute the frequency response of a system data
     structure

     *Inputs*
    SYS
          a system data structure (must be either purely continuous or
          discrete; see is_digital)

    W
          frequency values for evaluation.

          if SYS is continuous, then bode evaluates G(jw) where G(s) is
          the system transfer function.

          if SYS is discrete, then bode evaluates G(`exp'(jwT)), where
             * T is the system sampling time

             * G(z) is the system transfer function.

          *Default* the default frequency range is selected as follows:
          (These steps are *not* performed if W is specified)
            1. via routine __bodquist__, isolate all poles and zeros
               away from W=0 (JW=0 or `exp'(jwT)=1) and select the
               frequency range based on the breakpoint locations of the
               frequencies.

            2. if SYS is discrete time, the frequency range is limited
                           to jwT in [0,2 pi /T]

            3. A "smoothing" routine is used to ensure that the plot
               phase does not change excessively from point to point
               and that singular points (e.g., crossovers from +/- 180)
               are accurately shown.


    OUT_IDX
    IN_IDX
          The names or indices of outputs and inputs to be used in the
          frequency response.  See `sysprune'.

          *Example*
               bode(sys,[],"y_3", {"u_1","u_4"});
     *Outputs*
    MAG
    PHASE
          the magnitude and phase of the frequency response G(jw) or
          G(`exp'(jwT)) at the selected frequency values.

    W
          the vector of frequency values used

       1. If no output arguments are given, e.g.,
               bode(sys);
          bode plots the results to the screen.  Descriptive labels are
          automatically placed.

          Failure to include a concluding semicolon will yield some
          garbage being printed to the screen (`ans = []').

       2. If the requested plot is for an MIMO system, mag is set to
          ||G(jw)|| or ||G(`exp'(jwT))|| and phase information is not
          computed.

 -- Function File: [WMIN, WMAX] = bode_bounds (ZER, POL, DFLG, TSAM)
     Get default range of frequencies based on cutoff frequencies of
     system poles and zeros.  Frequency range is the interval [10^WMIN,
     10^WMAX]

     Used internally in `__freqresp__' (`bode', `nyquist')

 -- Function File:  freqchkw (W)
     Used by `__freqresp__' to check that input frequency vector W is
     valid.  Returns boolean value.

 -- Function File: OUT = ltifr (A, B, W)
 -- Function File: OUT = ltifr (SYS, W)
     Linear time invariant frequency response of single-input systems.

     *Inputs*
    A
    B
          coefficient matrices of dx/dt = A x + B u

    SYS
          system data structure

    W
          vector of frequencies
     *Output*
    OUT
          frequency response, that is:

                                     -1
                       G(s) = (jw I-A) B
     for complex frequencies s = jw.

 -- Function File: [REALP, IMAGP, W] = nyquist (SYS, W, OUT_IDX,
          IN_IDX, ATOL)
 -- Function File:  nyquist (SYS, W, OUT_IDX, IN_IDX, ATOL)
     Produce Nyquist plots of a system; if no output arguments are
     given, Nyquist plot is printed to the screen.

     Compute the frequency response of a system.

     *Inputs* (pass as empty to get default values)
    SYS
          system data structure (must be either purely continuous or
          discrete; see `is_digital')

    W
          frequency values for evaluation.  If sys is continuous, then
          bode evaluates G(JW); if sys is discrete, then bode evaluates
          G(exp(JWT)), where T is the system sampling time.

    DEFAULT
          the default frequency range is selected as follows: (These
          steps are *not* performed if W is specified)
            1. via routine `__bodquist__', isolate all poles and zeros
               away from W=0 (JW=0 or exp(JWT)=1) and select the
               frequency range based on the breakpoint locations of the
               frequencies.

            2. if SYS is discrete time, the frequency range is limited
               to JWT in [0,2p*pi]

            3. A "smoothing" routine is used to ensure that the plot
               phase does not change excessively from point to point
               and that singular points (e.g., crossovers from +/- 180)
               are accurately shown.

    ATOL
          for interactive nyquist plots: atol is a change-in-slope
          tolerance for the of asymptotes (default = 0; 1e-2 is a good
          choice).  This allows the user to "zoom in" on portions of
          the Nyquist plot too small to be seen with large asymptotes.
     *Outputs*
    REALP
    IMAGP
          the real and imaginary parts of the frequency response G(jw)
          or G(exp(jwT)) at the selected frequency values.

    W
          the vector of frequency values used

     If no output arguments are given, nyquist plots the results to the
     screen.  If ATOL != 0 and asymptotes are detected then the user is
     asked interactively if they wish to zoom in (remove asymptotes)
     Descriptive labels are automatically placed.

     Note: if the requested plot is for an MIMO system, a warning
     message is presented; the returned information is of the magnitude
     ||G(jw)|| or ||G(exp(jwT))|| only; phase information is not
     computed.

 -- Function File: [MAG, PHASE, W] = nichols (SYS, W, OUTPUTS, INPUTS)
     Produce Nichols plot of a system.

     *Inputs*
    SYS
          System data structure (must be either purely continuous or
          discrete; see `is_digital').

    W
          Frequency values for evaluation.
             * if sys is continuous, then nichols evaluates G(jw).

             * if sys is discrete, then nichols evaluates G(exp(jwT)),
               where T=SYS. TSAM is the system sampling time.

             * the default frequency range is selected as follows (These
                     steps are *not* performed if W is specified):
                 1. via routine `__bodquist__', isolate all poles and
                    zeros away from W=0 (jw=0 or exp(jwT)=1) and select
                    the frequency range based on the breakpoint
                    locations of the frequencies.

                 2. if sys is discrete time, the frequency range is
                    limited to jwT in [0,2p*pi].

                 3. A "smoothing" routine is used to ensure that the
                    plot phase does not change excessively from point
                    to point and that singular points (e.g., crossovers
                    from +/- 180) are accurately shown.

    OUTPUTS
    INPUTS
          the names or indices of the output(s) and input(s) to be used
          in the frequency response; see `sysprune'.
     *Outputs*
    MAG
    PHASE
          The magnitude and phase of the frequency response G(jw) or
          G(exp(jwT)) at the selected frequency values.

    W
          The vector of frequency values used.
     If no output arguments are given, `nichols' plots the results to
     the screen.  Descriptive labels are automatically placed. See
     `xlabel', `ylabel', and `title'.

     Note: if the requested plot is for an MIMO system, MAG is set to
     ||G(jw)|| or ||G(exp(jwT))|| and phase information is not computed.

 -- Function File: [ZER, GAIN] = tzero (A, B, C, D, OPT)
 -- Function File: [ZER, GAIN] = tzero (SYS, OPT)
     Compute transmission zeros of a continuous system:
          .
          x = Ax + Bu
          y = Cx + Du
     or of a discrete one:
          x(k+1) = A x(k) + B u(k)
          y(k)   = C x(k) + D u(k)

     *Outputs*
    ZER
          transmission zeros of the system

    GAIN
          leading coefficient (pole-zero form) of SISO transfer function
          returns gain=0 if system is multivariable
     *References*
       1. Emami-Naeini and Van Dooren, Automatica, 1982.

       2. Hodel, `Computation of Zeros with Balancing', 1992 Lin. Alg.
          Appl.

 -- Function File: ZR = tzero2 (A, B, C, D, BAL)
     Compute the transmission zeros of A, B, C, D.

     BAL = balancing option (see balance); default is `"B"'.

     Needs to incorporate `mvzero' algorithm to isolate finite zeros;
     use `tzero' instead.


File: octave.info,  Node: cacsd,  Next: misc,  Prev: sysfreq,  Up: Control Theory

30.9 Controller Design
======================

 -- Function File:  dgkfdemo ()
     Octave Controls toolbox demo: H-2/H-infinity options demos.

 -- Function File:  hinfdemo ()
     H-infinity design demos for continuous SISO and MIMO systems and a
     discrete system.  The SISO system is difficult to control because
     it is non-minimum-phase and unstable. The second design example
     controls the `jet707' plant, the linearized state space model of a
     Boeing 707-321 aircraft at V=80 m/s (M = 0.26, GA0 = -3 deg,
     ALPHA0 = 4 deg, KAPPA = 50 deg).  Inputs: (1) thrust and (2)
     elevator angle Outputs: (1) airspeed and (2) pitch angle. The
     discrete system is a stable and second order.

    SISO plant:
                               s - 2
                    G(s) = --------------
                           (s + 2)(s - 1)


                                             +----+
                        -------------------->| W1 |---> v1
                    z   |                    +----+
                    ----|-------------+
                        |             |
                        |    +---+    v   y  +----+
                      u *--->| G |--->O--*-->| W2 |---> v2
                        |    +---+       |   +----+
                        |                |
                        |    +---+       |
                        -----| K |<-------
                             +---+

               min || T   ||
                       vz   infty

          W1 und W2 are the robustness and performance weighting
          functions.

    MIMO plant:
          The optimal controller minimizes the H-infinity norm of the
          augmented plant P (mixed-sensitivity problem):
                    w
                     1 -----------+
                                  |                   +----+
                              +---------------------->| W1 |----> z1
                    w         |   |                   +----+
                     2 ------------------------+
                              |   |            |
                              |   v   +----+   v      +----+
                           +--*-->o-->| G  |-->o--*-->| W2 |---> z2
                           |          +----+      |   +----+
                           |                      |
                           ^                      v
                           u                       y (to K)
                        (from controller K)

                                 +    +           +    +
                                 | z  |           | w  |
                                 |  1 |           |  1 |
                                 | z  | = [ P ] * | w  |
                                 |  2 |           |  2 |
                                 | y  |           | u  |
                                 +    +           +    +

    Discrete system:
          This is not a true discrete design. The design is carried out
          in continuous time while the effect of sampling is described
          by a bilinear transformation of the sampled system.  This
          method works quite well if the sampling period is "small"
          compared to the plant time constants.

    The continuous plant:
                                  1
                    G (s) = --------------
                     k      (s + 2)(s + 1)

          is discretised with a ZOH (Sampling period = TS = 1 second):

                              0.199788z + 0.073498
                    G(z) = --------------------------
                           (z - 0.36788)(z - 0.13534)


                                             +----+
                        -------------------->| W1 |---> v1
                    z   |                    +----+
                    ----|-------------+
                        |             |
                        |    +---+    v      +----+
                        *--->| G |--->O--*-->| W2 |---> v2
                        |    +---+       |   +----+
                        |                |
                        |    +---+       |
                        -----| K |<-------
                             +---+

               min || T   ||
                       vz   infty
          W1 and W2 are the robustness and performance weighting
          functions.

 -- Function File: [L, M, P, E] = dlqe (A, G, C, SIGW, SIGV, Z)
     Construct the linear quadratic estimator (Kalman filter) for the
     discrete time system

          x[k+1] = A x[k] + B u[k] + G w[k]
            y[k] = C x[k] + D u[k] + v[k]

     where W, V are zero-mean gaussian noise processes with respective
     intensities `SIGW = cov (W, W)' and `SIGV = cov (V, V)'.

     If specified, Z is `cov (W, V)'.  Otherwise `cov (W, V) = 0'.

     The observer structure is

          z[k|k] = z[k|k-1] + L (y[k] - C z[k|k-1] - D u[k])
          z[k+1|k] = A z[k|k] + B u[k]

     The following values are returned:

    L
          The observer gain, (A - ALC).  is stable.

    M
          The Riccati equation solution.

    P
          The estimate error covariance after the measurement update.

    E
          The closed loop poles of (A - ALC).

 -- Function File: [K, P, E] = dlqr (A, B, Q, R, Z)
     Construct the linear quadratic regulator for the discrete time
     system

          x[k+1] = A x[k] + B u[k]

     to minimize the cost functional

          J = Sum (x' Q x + u' R u)

     Z omitted or

          J = Sum (x' Q x + u' R u + 2 x' Z u)

     Z included.

     The following values are returned:

    K
          The state feedback gain, (A - BK) is stable.

    P
          The solution of algebraic Riccati equation.

    E
          The closed loop poles of (A - BK).

 -- Function File: [LP, LF, P, Z] = dkalman (A, G, C, QW, RV, S)
     Construct the linear quadratic estimator (Kalman predictor) for the
     discrete time system

          x[k+1] = A x[k] + B u[k] + G w[k]
            y[k] = C x[k] + D u[k] + v[k]

     where W, V are zero-mean gaussian noise processes with respective
     intensities `QW = cov (W, W)' and `RV = cov (V, V)'.

     If specified, S is `cov (W, V)'.  Otherwise `cov (W, V) = 0'.

     The observer structure is

          x[k+1|k] = A x[k|k-1] + B u[k] + LP (y[k] - C x[k|k-1] - D u[k])
          x[k|k] = x[k|k-1] + LF (y[k] - C x[k|k-1] - D u[k])

     The following values are returned:

    LP
          The predictor gain, (A - LP C) is stable.

    LF
          The filter gain.

    P
          The Riccati solution.

          P = E [(x - x[n|n-1])(x - x[n|n-1])']

    Z
          The updated error covariance matrix.

          Z = E [(x - x[n|n])(x - x[n|n])']

 -- Function File: [K, GAIN, KC, KF, PC, PF] =  h2syn (ASYS, NU, NY,
          TOL)
     Design H-2 optimal controller per procedure in Doyle, Glover,
     Khargonekar, Francis, `State-Space Solutions to Standard' `H-2 and
     H-infinity' `Control Problems', IEEE TAC August 1989.

     Discrete-time control per Zhou, Doyle, and Glover, `Robust and
     optimal control', Prentice-Hall, 1996.

     *Inputs*
    ASYS
          system data structure (see ss, sys2ss)
             * controller is implemented for continuous time systems

             * controller is *not* implemented for discrete time systems

    NU
          number of controlled inputs

    NY
          number of measured outputs

    TOL
          threshold for 0.  Default: 200*`eps'

     *Outputs*
    K
          system controller

    GAIN
          optimal closed loop gain

    KC
          full information control (packed)

    KF
          state estimator (packed)

    PC
          ARE solution matrix for regulator subproblem

    PF
          ARE solution matrix for filter subproblem

 -- Function File: K = hinf_ctr (DGS, F, H, Z, G)
     Called by `hinfsyn' to compute the H-infinity optimal controller.

     *Inputs*
    DGS
          data structure returned by `is_dgkf'

    F
    H
          feedback and filter gain (not partitioned)

    G
          final gamma value
     *Outputs*
    K
          controller (system data structure)

     Do not attempt to use this at home; no argument checking performed.

 -- Function File: [K, G, GW, XINF, YINF] = hinfsyn (ASYS, NU, NY,
          GMIN, GMAX, GTOL, PTOL, TOL)
     *Inputs* input system is passed as either
    ASYS
          system data structure (see `ss', `sys2ss')
             * controller is implemented for continuous time systems

             * controller is *not* implemented for discrete time
               systems  (see bilinear transforms in `c2d', `d2c')

    NU
          number of controlled inputs

    NY
          number of measured outputs

    GMIN
          initial lower bound on H-infinity optimal gain

    GMAX
          initial upper bound on H-infinity Optimal gain.

    GTOL
          Gain threshold.  Routine quits when GMAX/GMIN < 1+tol.

    PTOL
          poles with `abs(real(pole))' < ptol*||H|| (H is appropriate
          Hamiltonian) are considered to be on the imaginary axis.
          Default: 1e-9.

    TOL
          threshold for 0.  Default: 200*`eps'.

          GMAX, MIN, TOL, and TOL must all be postive scalars.
     *Outputs*
    K
          System controller.

    G
          Designed gain value.

    GW
          Closed loop system.

    XINF
          ARE solution matrix for regulator subproblem.

    YINF
          ARE solution matrix for filter subproblem.

     References:
       1. Doyle, Glover, Khargonekar, Francis, `State-Space Solutions
          to Standard' `H-2 and H-infinity' `Control Problems', IEEE
          TAC August 1989.

       2. Maciejowksi, J.M., `Multivariable feedback design',
          Addison-Wesley, 1989, ISBN 0-201-18243-2.

       3. Keith Glover and John C. Doyle, `State-space formulae for all
          stabilizing controllers that satisfy an' `H-infinity-norm'
          `bound and relations to risk sensitivity', Systems & Control
          Letters 11, Oct. 1988, pp 167-172.

 -- Function File: [RETVAL, PC, PF] = hinfsyn_chk (A, B1, B2, C1, C2,
          D12, D21, G, PTOL)
     Called by `hinfsyn' to see if gain G satisfies conditions in
     Theorem 3 of Doyle, Glover, Khargonekar, Francis, `State Space
     Solutions to Standard' `H-2 and H-infinity' `Control Problems',
     IEEE TAC August 1989.

     *Warning:* do not attempt to use this at home; no argument
     checking performed.

     *Inputs*

     As returned by `is_dgkf', except for:
    G
          candidate gain level

    PTOL
          as in `hinfsyn'

     *Outputs*
    RETVAL
          1 if g exceeds optimal Hinf closed loop gain, else 0

    PC
          solution of "regulator" H-infinity ARE

    PF
          solution of "filter" H-infinity ARE
     Do not attempt to use this at home; no argument checking performed.

 -- Function File: [XINF, X_HA_ERR] = hinfsyn_ric (A, BB, C1, D1DOT, R,
          PTOL)
     Forms
          xx = ([bb; -c1'*d1dot]/r) * [d1dot'*c1 bb'];
          Ha = [a 0*a; -c1'*c1 - a'] - xx;
     and solves associated Riccati equation.  The error code X_HA_ERR
     indicates one of the following conditions:
    0
          successful

    1
          XINF has imaginary eigenvalues

    2
          HX not Hamiltonian

    3
          XINF has infinite eigenvalues (numerical overflow)

    4
          XINF not symmetric

    5
          XINF not positive definite

    6
          R is singular

 -- Function File: [K, P, E] = lqe (A, G, C, SIGW, SIGV, Z)
     Construct the linear quadratic estimator (Kalman filter) for the
     continuous time system

          dx
          -- = A x + G u
          dt

          y = C x + v

     where W and V are zero-mean gaussian noise processes with
     respective intensities

          sigw = cov (w, w)
          sigv = cov (v, v)

     The optional argument Z is the cross-covariance `cov (W, V)'.  If
     it is omitted, `cov (W, V) = 0' is assumed.

     Observer structure is `dz/dt = A z + B u + k (y - C z - D u)'

     The following values are returned:

    K
          The observer gain, (A - KC) is stable.

    P
          The solution of algebraic Riccati equation.

    E
          The vector of closed loop poles of (A - KC).

 -- Function File: [K, Q1, P1, EE, ER] = lqg (SYS, SIGW, SIGV, Q, R,
          IN_IDX)
     Design a linear-quadratic-gaussian optimal controller for the
     system
          dx/dt = A x + B u + G w       [w]=N(0,[Sigw 0    ])
              y = C x + v               [v]  (    0   Sigv ])
     or
          x(k+1) = A x(k) + B u(k) + G w(k)       [w]=N(0,[Sigw 0    ])
            y(k) = C x(k) + v(k)                  [v]  (    0   Sigv ])

     *Inputs*
    SYS
          system data structure

    SIGW
    SIGV
          intensities of independent Gaussian noise processes (as above)

    Q
    R
          state, control weighting respectively.  Control ARE is

    IN_IDX
          names or indices of controlled inputs (see `sysidx',
          `cellidx')

          default: last dim(R) inputs are assumed to be controlled
          inputs, all others are assumed to be noise inputs.
     *Outputs*
    K
          system data structure format LQG optimal controller (Obtain
          A, B, C matrices with `sys2ss', `sys2tf', or `sys2zp' as
          appropriate).

    P1
          Solution of control (state feedback) algebraic Riccati
          equation.

    Q1
          Solution of estimation algebraic Riccati equation.

    EE
          Estimator poles.

    ES
          Controller poles.


     *See also:* h2syn, lqe, lqr.

 -- Function File: [K, P, E] = lqr (A, B, Q, R, Z)
     construct the linear quadratic regulator for the continuous time
     system

          dx
          -- = A x + B u
          dt

     to minimize the cost functional

                infinity
                /
            J = |  x' Q x + u' R u
               /
              t=0

     Z omitted or

                infinity
                /
            J = |  x' Q x + u' R u + 2 x' Z u
               /
              t=0

     Z included.

     The following values are returned:

    K
          The state feedback gain, (A - BK) is stable and minimizes the
          cost functional

    P
          The stabilizing solution of appropriate algebraic Riccati
          equation.

    E
          The vector of the closed loop poles of (A - BK).

     *Reference* Anderson and Moore, `Optimal control: linear quadratic
     methods', Prentice-Hall, 1990, pp. 56-58.

 -- Function File: [Y, X] = lsim (SYS, U, T, X0)
     Produce output for a linear simulation of a system; produces a
     plot for the output of the system, SYS.

     U is an array that contains the system's inputs.  Each row in U
     corresponds to a different time step.  Each column in U
     corresponds to a different input.  T is an array that contains the
     time index of the system; T should be regularly spaced.  If
     initial conditions are required on the system, the X0 vector
     should be added to the argument list.

     When the lsim function is invoked a plot is not displayed;
     however, the data is returned in Y (system output) and X (system
     states).

 -- Function File: K = place (SYS, P)
     Computes the matrix K such that if the state is feedback with gain
     K, then the eigenvalues  of the closed loop system (i.e. A-BK) are
     those specified in the vector P.

     Version: Beta (May-1997): If you have any comments, please let me
     know.  (see the file place.m for my address)

