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, 1999, 2000, 2001, 2002, 2005, 2006, 2007
John W. Eaton.

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

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

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


File: octave.info,  Node: 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 detectability (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.

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


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


File: octave.info,  Node: misc,  Prev: cacsd,  Up: Control Theory

30.10 Miscellaneous Functions (Not yet properly filed/documented)
=================================================================

 -- Function File:  axis2dlim (AXDATA)
     Determine axis limits for 2-D data (column vectors); leaves a 10%
     margin around the plots.  Inserts margins of +/- 0.1 if data is
     one-dimensional (or a single point).

     *Input*
    AXDATA
          N by 2 matrix of data [X, Y].

     *Output*
    AXVEC
          Vector of axis limits appropriate for call to `axis' function.

 -- Function File:  moddemo (INPUTS)
     Octave Control toolbox demo: Model Manipulations demo.

 -- Function File:  prompt (STR)
     Prompt user to continue

     *Input*
    STR
          Input string. Its default value is:
               \n ---- Press a key to  continue ---

 -- Function File:  rldemo (INPUTS)
     Octave Control toolbox demo: Root Locus demo.

 -- Function File: [RLDATA, K] = rlocus (SYS[, INCREMENT, MIN_K, MAX_K])
     Display root locus plot of the specified SISO system.
                 -----   ---     --------
             --->| + |---|k|---->| SISO |----------->
                 -----   ---     --------        |
                 - ^                             |
                   |_____________________________|

     *Inputs*
    SYS
          system data structure

    MIN_K
          Minimum value of K

    MAX_K
          Maximum value of K

    INCREMENT
          The increment used in computing gain values

     *Outputs*

     Plots the root locus to the screen.
    RLDATA
          Data points plotted: in column 1 real values, in column 2 the
          imaginary values.

    K
          Gains for real axis break points.

 -- Function File: [YY, IDX] = sortcom (XX[, OPT])
     Sort a complex vector.

     *Inputs*
    XX
          Complex vector

    OPT
          sorting option:
         `"re"'
               Real part (default);

         `"mag"'
               By magnitude;

         `"im"'
               By imaginary part.
          if OPT is not chosen as `"im"', then complex conjugate pairs
          are grouped together, a - jb followed by a + jb.

     *Outputs*
    YY
          Sorted values

    IDX
          Permutation vector: `yy = xx(idx)'

 -- Function File: [NUM, DEN] = ss2tf (A, B, C, D)
     Conversion from transfer function to state-space.  The state space
     system:
                .
                x = Ax + Bu
                y = Cx + Du

     is converted to a transfer function:

                          num(s)
                    G(s)=-------
                          den(s)

     used internally in system data structure format manipulations.

 -- Function File: [POL, ZER, K] = ss2zp (A, B, C, D)
     Converts a state space representation to a set of poles and zeros;
     K is a gain associated with the zeros.

     Used internally in system data structure format manipulations.

 -- Function File:  starp (P, K, NY, NU)
     Redheffer star product or upper/lower LFT, respectively.

                         +-------+
               --------->|       |--------->
                         |   P   |
                    +--->|       |---+  ny
                    |    +-------+   |
                    +-------------------+
                                     |  |
                    +----------------+  |
                    |                   |
                    |    +-------+      |
                    +--->|       |------+ nu
                         |   K   |
               --------->|       |--------->
                         +-------+
     If NY and NU "consume" all inputs and outputs of K then the
     result is a lower fractional transformation.  If NY and NU
     "consume" all inputs and outputs of P then the result is an upper
     fractional transformation.

     NY and/or NU may be negative (i.e. negative feedback).

 -- Function File: [A, B, C, D] = tf2ss (NUM, DEN)
     Conversion from transfer function to state-space.  The state space
     system:
                .
                x = Ax + Bu
                y = Cx + Du
     is obtained from a transfer function:
                          num(s)
                    G(s)=-------
                          den(s)

     The vector DEN must contain only one row, whereas the vector NUM
     may contain as many rows as there are outputs Y of the system. The
     state space system matrices obtained from this function will be in
     controllable canonical form as described in `Modern Control
     Theory', (Brogan, 1991).

 -- Function File: [ZER, POL, K] = tf2zp (NUM, DEN)
     Converts transfer functions to poles-and-zero representations.

     Returns the zeros and poles of the SISO system defined by NUM/DEN.
     K is a gain associated with the system zeros.

 -- Function File: [A, B, C, D] = zp2ss (ZER, POL, K)
     Conversion from zero / pole to state space.

     *Inputs*
    ZER
    POL
          Vectors of (possibly) complex poles and zeros of a transfer
          function. Complex values must come in conjugate pairs (i.e.,
          x+jy in ZER means that x-jy is also in ZER).  The number of
          zeros must not exceed the number of poles.

    K
          Real scalar (leading coefficient).

     *Outputs*
    A
    B
    C
    D
          The state space system, in the form:
                    .
                    x = Ax + Bu
                    y = Cx + Du

 -- Function File: [NUM, DEN] = zp2tf (ZER, POL, K)
     Converts zeros / poles to a transfer function.

     *Inputs*
    ZER
    POL
          Vectors of (possibly complex) poles and zeros of a transfer
          function.  Complex values must appear in conjugate pairs.

    K
          Real scalar (leading coefficient).


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

31 Signal Processing
********************

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

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

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

 -- Loadable Function:  fft (A, N, DIM)
     Compute the FFT of A using subroutines from FFTW. The FFT is
     calculated along the first non-singleton dimension of the array.
     Thus if A is a matrix, `fft (A)' computes the FFT for each column
     of A.

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

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

     *See also:* ifft, fft2, fftn, fftw.

   Octave uses the FFTW libraries to perform FFT computations. When
Octave starts up and initializes the FFTW libraries, they read a system
wide file (on a Unix system, it is typically `/etc/fftw/wisdom') that
contains information useful to speed up FFT computations.  This
information is called the _wisdom_.  The system-wide file allows wisdom
to be shared between all applications using the FFTW libraries.

   Use the `fftw' function to generate and save wisdom.  Using the
utilities provided together with the FFTW libraries (`fftw-wisdom' on
Unix systems), you can even add wisdom generated by Octave to the
system-wide wisdom file.

 -- Loadable Function: METHOD = fftw ('planner')
 -- Loadable Function:  fftw ('planner', METHOD)
 -- Loadable Function: WISDOM = fftw ('dwisdom')
 -- Loadable Function: WISDOM = fftw ('dwisdom', WISDOM)
     Manage FFTW wisdom data. Wisdom data can be used to significantly
     accelerate the calculation of the FFTs but implies an initial cost
     in its calculation. When the FFTW libraries are initialized, they
     read a system wide wisdom file (typically in `/etc/fftw/wisdom'),
     allowing wisdom to be shared between applications other than
     Octave. Alternatively, the `fftw' function can be used to import
     wisdom. For example

          WISDOM = fftw ('dwisdom')

     will save the existing wisdom used by Octave to the string WISDOM.
     This string can then be saved to a file and restored using the
     `save' and `load' commands respectively. This existing wisdom can
     be reimported as follows

          fftw ('dwisdom', WISDOM)

     If WISDOM is an empty matrix, then the wisdom used is cleared.

     During the calculation of fourier transforms further wisdom is
     generated.  The fashion in which this wisdom is generated is
     equally controlled by the `fftw' function. There are five
     different manners in which the wisdom can be treated, these being

    'estimate'
          This specifies that no run-time measurement of the optimal
          means of calculating a particular is performed, and a simple
          heuristic is used to pick a (probably sub-optimal) plan. The
          advantage of this method is that there is little or no
          overhead in the generation of the plan, which is appropriate
          for a fourier transform that will be calculated once.

    'measure'
          In this case a range of algorithms to perform the transform
          is considered and the best is selected based on their
          execution time.

    'patient'
          This is like 'measure', but a wider range of algorithms is
          considered.

    'exhaustive'
          This is like 'measure', but all possible algorithms that may
          be used to treat the transform are considered.

    'hybrid'
          As run-time measurement of the algorithm can be expensive,
          this is a compromise where 'measure' is used for transforms
          up to the size of 8192 and beyond that the 'estimate' method
          is used.

     The default method is 'estimate', and the method currently being
     used can be probed with

          METHOD = fftw ('planner')

     and the method used can be set using

          fftw ('planner', METHOD)

     Note that calculated wisdom will be lost when restarting Octave.
     However, the wisdom data can be reloaded if it is saved to a file
     as described above. Saved wisdom files should not be used on
     different platforms since they will not be efficient and the point
     of calculating the wisdom is lost.

     *See also:* fft, ifft, fft2, ifft2, fftn, ifftn.

 -- Loadable Function:  ifft (A, N, DIM)
     Compute the inverse FFT of A using subroutines from FFTW. The
     inverse FFT is calculated along the first non-singleton dimension
     of the array. Thus if A is a matrix, `fft (A)' computes the
     inverse FFT for each column of A.

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

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

     *See also:* fft, ifft2, ifftn, fftw.

 -- Loadable Function:  fft2 (A, N, M)
     Compute the two dimensional FFT of A using subroutines from FFTW.
     The optional arguments N and M may be used specify the number of
     rows and columns of A to use.  If either of these is larger than
     the size of A, A is resized and padded with zeros.

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

     *See also:* ifft2, fft, fftn, fftw.

 -- Loadable Function:  fft2 (A, N, M)
     Compute the inverse two dimensional FFT of A using subroutines from
     FFTW. The optional arguments N and M may be used specify the
     number of rows and columns of A to use.  If either of these is
     larger than the size of A, A is resized and padded with zeros.

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

     *See also:* fft2, ifft, ifftn, fftw.

 -- Loadable Function:  fftn (A, SIZE)
     Compute the N dimensional FFT of A using subroutines from FFTW.
     The optional vector argument SIZE may be used specify the
     dimensions of the array to be used. If an element of SIZE is
     smaller than the corresponding dimension, then the dimension is
     truncated prior to performing the FFT. Otherwise if an element of
     SIZE is larger than the corresponding dimension A is resized and
     padded with zeros.

     *See also:* ifftn, fft, fft2, fftw.

 -- Loadable Function:  ifftn (A, SIZE)
     Compute the inverse N dimensional FFT of A using subroutines from
     FFTW. The optional vector argument SIZE may be used specify the
     dimensions of the array to be used. If an element of SIZE is
     smaller than the corresponding dimension, then the dimension is
     truncated prior to performing the inverse FFT. Otherwise if an
     element of SIZE is larger than the corresponding dimension A is
     resized and padded with zeros.

     *See also:* fftn, ifft, ifft2, fftw.

 -- Function File:  fftconv (A, B, N)
     Return the convolution of the vectors A and B, as a vector with
     length equal to the `length (a) + length (b) - 1'.  If A and B are
     the coefficient vectors of two polynomials, the returned value is
     the coefficient vector of the product polynomial.

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

 -- Function File:  fftfilt (B, X, N)
     With two arguments, `fftfilt' filters X with the FIR filter B
     using the FFT.

     Given the optional third argument, N, `fftfilt' uses the
     overlap-add method to filter X with B using an N-point FFT.

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

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

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

     where  N=length(a)-1 and M=length(b)-1.  over the first
     non-singleton dimension of X or over DIM if supplied. An
     equivalent form of this equation is:

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

     where  c = a/a(1) and d = b/a(1).

     If the fourth argument SI is provided, it is taken as the initial
     state of the system and the final state is returned as SF.  The
     state vector is a column vector whose length is equal to the
     length of the longest coefficient vector minus one.  If SI is not
     supplied, the initial state vector is set to all zeros.

     In terms of the z-transform, y is the result of passing the
     discrete- time signal x through a system characterized by the
     following rational system function:

                       M
                      SUM d(k+1) z^(-k)
                      k=0
            H(z) = ----------------------
                         N
                    1 + SUM c(k+1) z^(-k)
                        k=1

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

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

    'same'
          unpadded X (default)

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

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

     *See also:* conv2.

 -- Function File: [H, W] = freqz (B, A, N, "whole")
     Return the complex frequency response H of the rational IIR filter
     whose numerator and denominator coefficients are B and A,
     respectively.  The response is evaluated at N angular frequencies
     between 0 and  2*pi.

     The output value W is a vector of the frequencies.

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

     If N is omitted, a value of 512 is assumed.

     If A is omitted, the denominator is assumed to be 1 (this
     corresponds to a simple FIR filter).

     For fastest computation, N should factor into a small number of
     small primes.

 -- Function File: H = freqz (B, A, W)
     Evaluate the response at the specific frequencies in the vector W.
     The values for W are measured in radians.

 -- Function File: [...] = freqz (..., FS)
     Return frequencies in Hz instead of radians assuming a sampling
     rate FS.  If you are evaluating the response at specific
     frequencies W, those frequencies should be requested in Hz rather
     than radians.

 -- Function File:  freqz (...)
     Plot the pass band, stop band and phase response of H rather than
     returning them.

 -- Function File:  freqz_plot (W, H)
     Plot the pass band, stop band and phase response of H.

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

 -- Function File: B = unwrap (A, TOL, DIM)
     Unwrap radian phases by adding multiples of 2*pi as appropriate to
     remove jumps greater than TOL.  TOL defaults to pi.

     Unwrap will unwrap along the first non-singleton dimension of A,
     unless the optional argument DIM is given, in which case the data
     will be unwrapped along this dimension

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

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

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

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

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

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

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

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

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

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

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

          y = x * b + e

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

     I.e., the model is

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

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

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

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

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

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

     as the t-th row of X.

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

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

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

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

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

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

 -- Function File:  autocor (X, H)
     Return the autocorrelations from lag 0 to H of vector X.  If H is
     omitted, all autocorrelations are computed.  If X is a matrix, the
     autocorrelations of each column are computed.

 -- Function File:  autocov (X, H)
     Return the autocovariances from lag 0 to H of vector X.  If H is
     omitted, all autocovariances are computed.  If X is a matrix, the
     autocovariances of each column are computed.

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

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

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

 -- Function File:  blackman (M)
     Return the filter coefficients of a Blackman window of length M.

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

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

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

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

     Reference: Brockwell, Peter J. & Davis, Richard A. Time Series:
     Theory and Methods Springer 1987.

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

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

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

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

     If V is a vector of N elements corresponding to N time samples
     spaced of Dt each, then `fftshift (fft (V))' corresponds to
     frequencies

          f = ((1:N) - ceil(N/2)) / N / Dt

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

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

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

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

 -- Function File:  hamming (M)
     Return the filter coefficients of a Hamming window of length M.

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

 -- Function File:  hanning (M)
     Return the filter coefficients of a Hanning window of length M.

     For a definition of this window type, see e.g. A. V. Oppenheim &
     R. W. Schafer, "Discrete-Time Signal Processing".

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

 -- Function File: PP =  pchip (X, Y)
 -- Function File: YI =  pchip (X, Y, XI)
     Piecewise Cubic Hermite interpolating polynomial. Called with two
     arguments, the piece-wise polynomial PP is returned, that may
     later be used with `ppval' to evaluate the polynomial at specific
     points.

     The variable X must be a strictly monotonic vector (either
     increasing or decreasing). While Y can be either a vector or
     array. In the case where Y is a vector, it must have a length of
     N. If Y is an array, then the size of Y must have the form `[S1,
     S2, ..., SK, N]' The array is then reshaped internally to a matrix
     where the leading dimension is given by `S1 * S2 * ... * SK' and
     each row in this matrix is then treated separately. Note that this
     is exactly the opposite treatment than `interp1' and is done for
     compatibility.

     Called with a third input argument, `pchip' evaluates the
     piece-wise polynomial at the points XI. There is an equivalence
     between `ppval (pchip (X, Y), XI)' and `pchip (X, Y, XI)'.


     *See also:* spline, ppval, mkpp, unmkpp.

 -- Function File:  periodogram (X)
     For a data matrix X from a sample of size N, return the
     periodogram.

 -- Function File:  rectangle_lw (N, B)
     Rectangular lag window. Subfunction used for spectral density
     estimation.

 -- Function File:  rectangle_sw (N, B)
     Rectangular spectral window.  Subfunction used for spectral density
     estimation.

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

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

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

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

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

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

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

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

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

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

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

 -- Function File: [Y, C] = stft (X, WIN_SIZE, INC, NUM_COEF, W_TYPE)
     Compute the short-term Fourier transform of the vector X with
     NUM_COEF coefficients by applying a window of WIN_SIZE data points
     and an increment of INC points.

     Before computing the Fourier transform, one of the following
     windows is applied:

    hanning
          w_type = 1

    hamming
          w_type = 2

    rectangle
          w_type = 3

     The window names can be passed as strings or by the W_TYPE number.

     If not all arguments are specified, the following defaults are
     used: WIN_SIZE = 80, INC = 24, NUM_COEF = 64, and W_TYPE = 1.

     `Y = stft (X, ...)' returns the absolute values of the Fourier
     coefficients according to the NUM_COEF positive frequencies.

     `[Y, C] = stft (`x', ...)' returns the entire STFT-matrix Y and a
     3-element vector C containing the window size, increment, and
     window type, which is needed by the synthesis function.

 -- Function File:  synthesis (Y, C)
     Compute a signal from its short-time Fourier transform Y and a
     3-element vector C specifying window size, increment, and window
     type.

     The values Y and C can be derived by

          [Y, C] = stft (X , ...)

 -- Function File:  triangle_lw (N, B)
     Triangular lag window. Subfunction used for spectral density
     estimation.

 -- Function File:  triangle_sw (N, B)
     Triangular spectral window.  Subfunction used for spectral density
     estimation.

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

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


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

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

Since an image basically is a matrix Octave is a very powerful
environment for processing and analysing images. To illustrate how easy
it is to do image processing in Octave, the following example will load
an image, smooth it by a 5-by-5 averaging filter, and compute the
gradient of the smoothed image.

     I = loadimage ("default.img");
     S = conv2 (I, ones (5, 5) / 25, "same");
     [Dx, Dy] = gradient (S);

In this example `S' contains the smoothed image, and `Dx' and `Dy'
contains the partial spatial derivatives of the image.

* Menu:

* Loading and Saving Images::
* Displaying Images::
* Representing Images::
* Plotting on top of Images::
* Color Conversion::


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

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

The first step in most image processing tasks is to load an image into
Octave. Currently Octave only support saving images in the Portable
Pixmap Format (PPM), PostScript, and Octave's own format, and loading
images in Octave's format. Most image processing code will follow the
structure of this code

     I = loadimage ("my_input_image.img");
     J = process_my_image (I);
     saveimage ("my_output_image.img", J);

 -- Function File: [X, MAP] = loadimage (FILE)
     Load an image file and it's associated color map from the specified
     FILE.  The image must be stored in Octave's image format.

     *See also:* saveimage, load, save.

 -- Function File:  saveimage (FILE, X, FMT, MAP)
     Save the matrix X to FILE in image format FMT.  Valid values for
     FMT are

    `"img"'
          Octave's image format.  The current colormap is also saved in
          the file.

    `"ppm"'
          Portable pixmap format.

    `"ps"'
          PostScript format.  Note that images saved in PostScript
          format can not be read back into Octave with loadimage.

     If the fourth argument is supplied, the specified colormap will
     also be saved along with the image.

     Note: if the colormap contains only two entries and these entries
     are black and white, the bitmap ppm and PostScript formats are
     used.  If the image is a gray scale image (the entries within each
     row of the colormap are equal) the gray scale ppm and PostScript
     image formats are used, otherwise the full color formats are used.

     *See also:* loadimage, save, load, colormap.

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


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

32.2 Displaying Images
======================

A natural part of image processing is visualization of an image.  The
most basic function for this is the `imshow' function that shows the
image given in the first input argument. This function uses an external
program to show the image. If gnuplot 4.2 or later is available it will
be used to display the image, otherwise the `display', `xv', or
`xloadimage' program is used. The actual program can be selected with
the `image_viewer' function.

 -- Function File:  imshow (IM)
 -- Function File:  imshow (IM, LIMITS)
 -- Function File:  imshow (IM, MAP)
 -- Function File:  imshow (RGB, ...)
 -- Function File:  imshow (FILENAME)
 -- Function File:  imshow (..., STRING_PARAM1, VALUE1, ...)
     Display the image IM, where IM can be a 2-dimensional (gray-scale
     image) or a 3-dimensional (RGB image) matrix.

     If LIMITS is a 2-element vector `[LOW, HIGH]', the image is shown
     using a display range between LOW and HIGH.  If an empty matrix is
     passed for LIMITS, the display range is computed as the range
     between the minimal and the maximal value in the image.

     If MAP is a valid color map, the image will be shown as an indexed
     image using the supplied color map.

     If a file name is given instead of an image, the file will be read
     and shown.

     If given, the parameter STRING_PARAM1 has value VALUE1.
     STRING_PARAM1 can be any of the following:
    `"displayrange"'
          VALUE1 is the display range as described above.


     *See also:* image, imagesc, colormap, gray2ind, rgb2ind.

 -- Function File:  image (IMG)
 -- Function File:  image (X, Y, IMG)
     Display a matrix as a color image.  The elements of X are indices
     into the current colormap, and the colormap will be scaled so that
     the extremes of X are mapped to the extremes of the colormap.

     It first tries to use `gnuplot', then `display' from
     `ImageMagick', then `xv', and then `xloadimage'.  The actual
     program used can be changed using the `image_viewer' function.

     The axis values corresponding to the matrix elements are specified
     in X and Y. If you're not using gnuplot 4.2 or later, these
     variables are ignored.

     *See also:* imshow, imagesc, colormap, image_viewer.

 -- Function File:  imagesc (A)
 -- Function File:  imagesc (X, Y, A)
 -- Function File:  imagesc (..., LIMITS)
 -- Function File:  imagesc (H, ...)
 -- Function File:  H =  imagesc (...)
     Display a scaled version of the matrix A as a color image.  The
     colormap is scaled so that the entries of the matrix occupy the
     entire colormap.  If LIMITS = [LO, HI] are given, then that range
     is set to the 'clim' of the current axes.

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


     *See also:* image, imshow, clim, caxis.

 -- Function File: [FCN, DEFAULT_ZOOM] = image_viewer (FCN,
          DEFAULT_ZOOM)
     Change the program or function used for viewing images and return
     the previous values.

     When the `image' or `imshow' function is called it will launch an
     external program to display the image.  The default behaviour is
     to use gnuplot if the installed version supports image viewing,
     and otherwise try the programs `display', `xv', and `xloadimage'.
     Using this function it is possible to change that behaviour.

     When called with one input argument images will be displayed by
     saving the image to a file and the system command COMMAND will
     called to view the image.  The COMMAND must be a string containing
     `%s' and possibly `%f'. The `%s' will be replaced by the filename
     of the image, and the `%f' will (if present) be replaced by the
     zoom factor given to the `image' function.  For example,
          image_viewer ("eog %s");
     changes the image viewer to the `eog' program.

     With two input arguments, images will be displayed by calling the
     function FUNCTION_HANDLE.  For example,
          image_viewer (data, @my_image_viewer);
     sets the image viewer function to `my_image_viewer'.  The image
     viewer function is called with
          my_image_viewer (X, Y, IM, ZOOM, DATA)
     where X and Y are the axis of the image, IM is the image variable,
     and DATA is extra user-supplied data to be passed to the viewer
     function.

     With three input arguments it is possible to change the zooming.
     Some programs (like `xloadimage') require the zoom factor to be
     between 0 and 100, and not 0 and 1 like Octave assumes. This is
     solved by setting the third argument to 100.


     *See also:* image, imshow.


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

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

In general Octave supports four different kinds of images, gray-scale
images, RGB images, binary images, and indexed images. A gray-scale
image is represented with an M-by-N matrix in which each element
corresponds to the intensity of a pixel. An RGB image is represented
with an M-by-N-by-3 array where each 3-vector corresponds to the red,
green, and blue intensities of each pixel.

   The actual meaning of the value of a pixel in a gray-scale or RGB
image depends on the class of the matrix. If the matrix is of class
`double' pixel intensities are between 0 and 1, if it is of class
`uint8' intensities are between 0 and 255, and if it is of class
`uint16' intensities are between 0 and 65535.

   A binary image is a M-by-N matrix of class `logical'.  A pixel in a
binary image is black if it is `false' and white if it is `true'.

   An indexed image consists of an M-by-N matrix of integers and a
C-by-3 color map. Each integer corresponds to an index in the color
map, and each row in the color map corresponds to a RGB color. The
color map must be of class `double' with values between 0 and 1.

 -- Function File: [IMG, MAP] = gray2ind ()
     Convert a gray scale intensity image to an Octave indexed image.

 -- Function File:  ind2gray (X, MAP)
     Convert an Octave indexed image to a gray scale intensity image.
     If MAP is omitted, the current colormap is used to determine the
     intensities.

     *See also:* gray2ind, rgb2ntsc, image, colormap.

 -- Function File: [X, MAP] = rgb2ind (RGB)
 -- Function File: [X, MAP] = rgb2ind (R, G, B)
     Convert and RGB image to an Octave indexed image.

     *See also:* ind2rgb, rgb2ntsc.

 -- Function File: RGB = ind2rgb (X, MAP)
 -- Function File: [R, G, B] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.
     If the colormap doesn't contain enough colors, pad it with the
     last color in the map.  If MAP is omitted, the current colormap is
     used for the conversion.

     *See also:* rgb2ind, image, imshow, ind2gray, gray2ind.

 -- Function File:  colormap (MAP)
 -- Function File:  colormap ("default")
     Set the current colormap.

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

     `colormap ("default")' restores the default colormap (the `jet'
     map with 64 entries).  The default colormap is returned.

     With no arguments, `colormap' returns the current color map.

     *See also:* jet.

 -- Function File:  autumn (N)
     Create color colormap. This colormap is red through orange to
     yellow.  The argument N should be a scalar.  If it is omitted, the
     length of the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  bone (N)
     Create color colormap. This colormap is a gray colormap with a
     light blue tone. The argument N should be a scalar.  If it is
     omitted, the length of the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  cool (N)
     Create color colormap. The colormap is cyan to magenta. The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  copper (N)
     Create color colormap. This colormap is black to a light copper
     tone.  The argument N should be a scalar.  If it is omitted, the
     length of the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  gray (N)
     Return a gray colormap with N entries corresponding to values from
     0 to N-1.  The argument N should be a scalar.  If it is omitted,
     the length of the current colormap or 64 is assumed.

 -- Function File:  hot (N)
     Create color colormap. This colormap is black through dark red,
     red, orange, yellow to white. The argument N should be a scalar.
     If it is omitted, the length of the current colormap or 64 is
     assumed.

     *See also:* colormap.

 -- Function File:  hsv (N)
     Create color colormap. This colormap is red through yellow, green,
     cyan, blue, magenta to red. The argument N should be a scalar.  If
     it is omitted, the length of the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  jet (N)
     Create color colormap. This colormap is dark blue through blue,
     cyan, green, yellow, red to dark red. The argument N should be a
     scalar.  If it is omitted, the length of the current colormap or
     64 is assumed.

     *See also:* colormap.

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

 -- Function File:  pink (N)
     Create color colormap. This colormap gives a sephia tone on black
     and white images. The argument N should be a scalar.  If it is
     omitted, the length of the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  prism (N)
     Create color colormap. This colormap cycles trough red, orange,
     yellow, green, blue and violet. The argument N should be a scalar.
     If it is omitted, the length of the current colormap or 64 is
     assumed.

     *See also:* colormap.

 -- Function File:  rainbow (N)
     Create color colormap. This colormap is red through orange,
     yellow, green, blue to violet. The argument N should be a scalar.
     If it is omitted, the length of the current colormap or 64 is
     assumed.

     *See also:* colormap.

 -- Function File:  spring (N)
     Create color colormap. This colormap is magenta to yellow.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* colormap.

 -- Function File:  summer (N)
     Create color colormap. This colormap is green to yellow.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* colormap.

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

     *See also:* colormap.

 -- Function File:  winter (N)
     Create color colormap. This colormap is blue to green.  The
     argument N should be a scalar.  If it is omitted, the length of
     the current colormap or 64 is assumed.

     *See also:* colormap.

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

 -- Function File:  gmap40 (N)
     Create a color colormap. The colormap is red, green, blue, yellow,
     magenta and cyan. These are the colors that are allowed with patch
     objects using gnuplot 4.0, and so this colormap function is
     specially designed for users of gnuplot 4.0.  The argument N
     should be a scalar.  If it is omitted, a length of 6 is assumed.
     Larger values of N result in a repetition of the above colors

     *See also:* colormap.


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

32.4 Plotting on top of Images
==============================

If gnuplot is being used to display images it is possible to plot on
top of images. Since an image is a matrix it is indexed by row and
column values. The plotting system is, however, based on the
traditional (x, y) system. To minimize the difference between the two
systems Octave places the origin of the coordinate system in the point
corresponding to the pixel at (1, 1). So, to plot points given by row
and column values on top of an image, one should simply call `plot'
with the column values as the first argument and the row values as the
second. As an example the following code generates an image with random
intensities between 0 and 1, and shows the image with red circles over
pixels with an intensity above 0.99.

     I = rand (100, 100);
     [row, col] = find (I > 0.99);
     hold ("on");
     imshow (I);
     plot (col, row, "ro");
     hold ("off");


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

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

Octave supports conversion from the RGB color system to NTSC and HSV
and vice versa.

 -- Function File: HSV_MAP = rgb2hsv (RGB_MAP)
     Transform a colormap from the rgb space to the hsv space.

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

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

     *See also:* hsv2rgb.

 -- Function File: RGB_MAP = hsv2rgb (HSV_MAP)
     Transform a colormap from the hsv space to the rgb space.

     *See also:* rgb2hsv.

 -- Function File:  rgb2ntsc (RGB)
     Image format conversion.

 -- Function File:  ntsc2rgb (YIQ)
     Image format conversion.


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

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

Octave provides a few functions for dealing with audio data.  An audio
`sample' is a single output value from an A/D converter, i.e., a small
integer number (usually 8 or 16 bits), and audio data is just a series
of such samples.  It can be characterized by three parameters:  the
sampling rate (measured in samples per second or Hz, e.g. 8000 or
44100), the number of bits per sample (e.g. 8 or 16), and the number of
channels (1 for mono, 2 for stereo, etc.).

   There are many different formats for representing such data.
Currently, only the two most popular, _linear encoding_ and _mu-law
encoding_, are supported by Octave.  There is an excellent FAQ on audio
formats by Guido van Rossum <guido@cwi.nl> which can be found at any
FAQ ftp site, in particular in the directory
`/pub/usenet/news.answers/audio-fmts' of the archive site
`rtfm.mit.edu'.

   Octave simply treats audio data as vectors of samples (non-mono data
are not supported yet).  It is assumed that audio files using linear
encoding have one of the extensions `lin' or `raw', and that files
holding data in mu-law encoding end in `au', `mu', or `snd'.

 -- Function File:  lin2mu (X, N)
     Converts audio data from linear to mu-law.  Mu-law values use 8-bit
     unsigned integers.  Linear values use N-bit signed integers or
     floating point values in the range -1<=X<=1 if N is 0.  If N is
     not specified it defaults to 0, 8 or 16 depending on the range
     values in X.

     *See also:* mu2lin, loadaudio, saveaudio, playaudio, setaudio,
     record.

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

     *See also:* lin2mu, loadaudio, saveaudio, playaudio, setaudio,
     record.

 -- Function File:  loadaudio (NAME, EXT, BPS)
     Loads audio data from the file `NAME.EXT' into the vector X.

     The extension EXT determines how the data in the audio file is
     interpreted;  the extensions `lin' (default) and `raw' correspond
     to linear, the extensions `au', `mu', or `snd' to mu-law encoding.

     The argument BPS can be either 8 (default) or 16, and specifies
     the number of bits per sample used in the audio file.

     *See also:* lin2mu, mu2lin, saveaudio, playaudio, setaudio, record.

 -- Function File:  saveaudio (NAME, X, EXT, BPS)
     Saves a vector X of audio data to the file `NAME.EXT'.  The
     optional parameters EXT and BPS determine the encoding and the
     number of bits per sample used in the audio file (see
     `loadaudio');  defaults are `lin' and 8, respectively.

     *See also:* lin2mu, mu2lin, loadaudio, playaudio, setaudio, record.

   The following functions for audio I/O require special A/D hardware
and operating system support.  It is assumed that audio data in linear
encoding can be played and recorded by reading from and writing to
`/dev/dsp', and that similarly `/dev/audio' is used for mu-law
encoding.  These file names are system-dependent.  Improvements so that
these functions will work without modification on a wide variety of
hardware are welcome.

 -- Function File:  playaudio (NAME, EXT)
 -- Function File:  playaudio (X)
     Plays the audio file `NAME.EXT' or the audio data stored in the
     vector X.

     *See also:* lin2mu, mu2lin, loadaudio, saveaudio, setaudio, record.

 -- Function File:  record (SEC, SAMPLING_RATE)
     Records SEC seconds of audio input into the vector X.  The default
     value for SAMPLING_RATE is 8000 samples per second, or 8kHz.  The
     program waits until the user types <RET> and then immediately
     starts to record.

     *See also:* lin2mu, mu2lin, loadaudio, saveaudio, playaudio,
     setaudio.

 -- Function File:  setaudio ([W_TYPE [, VALUE]])
     Execute the shell command `mixer [W_TYPE [, VALUE]]'

 -- Function File: Y = wavread (FILENAME)
     Load the RIFF/WAVE sound file FILENAME, and return the samples in
     vector Y.  If the file contains multichannel data, then Y is a
     matrix with the channels represented as columns.

 -- Function File: [Y, FS, BITS] = wavread (FILENAME)
     Additionally return the sample rate (FS) in Hz and the number of
     bits per sample (BITS).

 -- Function File: [...] = wavread (FILENAME, N)
     Read only the first N samples from each channel.

 -- Function File: [...] = wavread (FILENAME,[N1 N2])
     Read only samples N1 through N2 from each channel.

 -- Function File: [SAMPLES, CHANNELS] = wavread (FILENAME, "size")
     Return the number of samples (N) and channels (CH) instead of the
     audio data.

     *See also:* wavwrite.

 -- Function File:  wavwrite (Y, FILENAME)
 -- Function File:  wavwrite (Y, FS, FILENAME)
 -- Function File:  wavwrite (Y, FS, BITS, FILENAME)
     Write Y to the canonical RIFF/WAVE sound file FILENAME with sample
     rate FS and bits per sample BITS.  The default sample rate is 8000
     Hz with 16-bits per sample.  Each column of the data represents a
     separate channel.

     *See also:* wavread.


File: octave.info,  Node: Quaternions,  Next: System Utilities,  Prev: Audio Processing,  Up: Top

34 Quaternions
**************

Quaternions are hypercomplex numbers used to represent spatial
rotations in three dimensions.  This set of routines provides a useful
basis for working with quaternions in Octave.  A tutorial is in the
Octave source, scripts/quaternion/quaternion.ps.

   These functions were written by A. S. Hodel, Associate Professor,
Auburn University.

 -- Function File: [A, B, C, D] = quaternion (w)
 -- Function File: [VV, THETA] = quaternion (w)
 -- Function File: W = quaternion (A, B, C, D)
 -- Function File: W = quaternion (VV, THETA)
     Construct or extract a quaternion

          w = a*i + b*j + c*k + d

     from given data.

 -- Function File:  qconj (Q)
     Conjugate of a quaternion.

          q = [w, x, y, z] = w*i + x*j + y*k + z
          qconj (q) = -w*i -x*j -y*k + z

 -- Function File:  qderiv (omega)
     Derivative of a quaternion.

     Let Q be a quaternion to transform a vector from a fixed frame to
     a rotating frame.  If the rotating frame is rotating about the [x,
     y, z] axes at angular rates [wx, wy, wz], then the derivative of Q
     is given by

          Q' = qderivmat (omega) * Q

     If the passive convention is used (rotate the frame, not the
     vector), then

          Q' = -qderivmat (omega) * Q

 -- Function File:  qderivmat (OMEGA)
     Derivative of a quaternion.

     Let Q be a quaternion to transform a vector from a fixed frame to
     a rotating frame.  If the rotating frame is rotating about the [x,
     y, z] axes at angular rates [wx, wy, wz], then the derivative of Q
     is given by

          Q' = qderivmat (omega) * Q

     If the passive convention is used (rotate the frame, not the
     vector), then

          Q' = -qderivmat (omega) * Q.

 -- Function File:  qinv (Q)
     Return the inverse of a quaternion.

          q = [w, x, y, z] = w*i + x*j + y*k + z
          qmult (q, qinv (q)) = 1 = [0 0 0 1]

 -- Function File:  qmult (A, B)
     Multiply two quaternions.

          [w, x, y, z] = w*i + x*j + y*k + z

     identities:

          i^2 = j^2 = k^2 = -1
          ij = k                 jk = i
          ki = j                 kj = -i
          ji = -k                ik = -j

 -- Function File:  qtrans (V, Q)
     Transform the unit quaternion V by the unit quaternion Q.  Returns
     `V = Q*V/Q'.

 -- Function File:  qtransv (V, Q)
     Transform the 3-D vector V by the unit quaternion Q.  Return a
     column vector.

          vi = (2*real(q)^2 - 1)*vb + 2*imag(q)*(imag(q)'*vb)
             + 2*real(q)*cross(imag(q),vb)

     Where imag(q) is a column vector of length 3.

 -- Function File:  qtransvmat (QIB)
     Construct a 3x3 transformation matrix from quaternion QIB that is
     equivalent to rotation of th radians about axis VV, where `[VV,
     TH] = quaternion (QIB)'.

 -- Function File:  qcoordinate_plot (QF, QB, QV)
     Plot in the current figure a set of coordinate axes as viewed from
     the orientation specified by quaternion QV.  Inertial axes are
     also plotted:

    QF
          Quaternion from reference (x,y,z) to inertial.

    QB
          Quaternion from reference to body.

    QV
          Quaternion from reference to view angle.


File: octave.info,  Node: System Utilities,  Next: Packages,  Prev: Quaternions,  Up: Top

35 System Utilities
*******************

This chapter describes the functions that are available to allow you to
get information about what is happening outside of Octave, while it is
still running, and use this information in your program.  For example,
you can get information about environment variables, the current time,
and even start other programs from the Octave prompt.

* Menu:

* Timing Utilities::
* Filesystem Utilities::
* File Archiving Utilities::
* Networking Utilities::
* Controlling Subprocesses::
* Process ID Information::
* Environment Variables::
* Current Working Directory::
* Password Database Functions::
* Group Database Functions::
* System Information::
* Hashing Functions::


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

35.1 Timing Utilities
=====================

Octave's core set of functions for manipulating time values are
patterned after the corresponding functions from the standard C library.
Several of these functions use a data structure for time that includes
the following elements:

`usec'
     Microseconds after the second (0-999999).

`sec'
     Seconds after the minute (0-61).  This number can be 61 to account
     for leap seconds.

`min'
     Minutes after the hour (0-59).

`hour'
     Hours since midnight (0-23).

`mday'
     Day of the month (1-31).

`mon'
     Months since January (0-11).

`year'
     Years since 1900.

`wday'
     Days since Sunday (0-6).

`yday'
     Days since January 1 (0-365).

`isdst'
     Daylight Savings Time flag.

`zone'
     Time zone.

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

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

     *See also:* strftime, strptime, localtime, gmtime, mktime, now,
     date, clock, datenum, datestr, datevec, calendar, weekday.

 -- Function File: t = now ()
     Returns the current local time as the number of days since Jan 1,
     0000.  By this reckoning, Jan 1, 1970 is day number 719529.

     The integral part, `floor (now)' corresponds to 00:00:00 today.

     The fractional part, `rem (now, 1)' corresponds to the current
     time on Jan 1, 0000.

     The returned value is also called a "serial date number" (see
     `datenum').

     *See also:* clock, date, datenum.

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

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

 -- Loadable Function:  gmtime (T)
     Given a value returned from time (or any nonnegative integer),
     return a time structure corresponding to CUT.  For example,

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


     *See also:* strftime, strptime, localtime, mktime, time, now,
     date, clock, datenum, datestr, datevec, calendar, weekday.

 -- Loadable Function:  localtime (T)
     Given a value returned from time (or any nonnegative integer),
     return a time structure corresponding to the local time zone.

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


     *See also:* strftime, strptime, gmtime, mktime, time, now, date,
     clock, datenum, datestr, datevec, calendar, weekday.

 -- Loadable Function:  mktime (TM_STRUCT)
     Convert a time structure corresponding to the local time to the
     number of seconds since the epoch.  For example,

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


     *See also:* strftime, strptime, localtime, gmtime, time, now,
     date, clock, datenum, datestr, datevec, calendar, weekday.

 -- Function File:  asctime (TM_STRUCT)
     Convert a time structure to a string using the following five-field
     format: Thu Mar 28 08:40:14 1996.  For example,

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

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

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

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

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

     Literal character fields:

    `%'
          % character.

    `n'
          Newline character.

    `t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

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

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

     Time fields:

    `%H'
          Hour (00-23).

    `%I'
          Hour (01-12).

    `%k'
          Hour (0-23).

    `%l'
          Hour (1-12).

    `%M'
          Minute (00-59).

    `%p'
          Locale's AM or PM.

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

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

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

    `%S'
          Second (00-61).

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

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

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

     Date fields:

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

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

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

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

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

    `%C'
          Century (00-99).

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

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

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

    `%h'
          Same as %b.

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

    `%m'
          Month (01-12).

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

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

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

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

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

    `%Y'
          Year (1970-).


     *See also:* strptime, localtime, gmtime, mktime, time, now, date,
     clock, datenum, datestr, datevec, calendar, weekday.

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

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

     *See also:* strftime, localtime, gmtime, mktime, time, now, date,
     clock, datenum, datestr, datevec, calendar, weekday.

   Most of the remaining functions described in this section are not
patterned after the standard C library.  Some are available for
compatibility with MATLAB and others are provided because they are
useful.

 -- Function File:  clock ()
     Return a vector containing the current year, month (1-12), day
     (1-31), hour (0-23), minute (0-59) and second (0-61).  For example,

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

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

 -- Function File:  date ()
     Return the date as a character string in the form DD-MMM-YY.  For
     example,

          date ()
          => "20-Aug-93"

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

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

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

     *See also:* tic, toc, clock, cputime.

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

 -- Function File:  is_leap_year (YEAR)
     Return 1 if the given year is a leap year and 0 otherwise.  If no
     arguments are provided, `is_leap_year' will use the current year.
     For example,

          is_leap_year (2000)
          => 1

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

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

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

     If called with one output argument then this function returns a
     scalar of type `uint64' and the wall-clock timer is not started.

          t = tic; sleep (5); (double (tic ()) - double (t)) * 1e-6
               => 5

     Nested timing with `tic' and `toc' is not supported.  Therefore
     `toc' will always return the elapsed time from the most recent
     call to `tic'.

     If you are more interested in the CPU time that your process used,
     you should use the `cputime' function instead.  The `tic' and
     `toc' functions report the actual wall clock time that elapsed
     between the calls.  This may include time spent processing other
     jobs or doing nothing at all.  For example,

          tic (); sleep (5); toc ()
               => 5
          t = cputime (); sleep (5); cputime () - t
               => 0

     (This example also illustrates that the CPU timer may have a fairly
     coarse resolution.)

 -- Built-in Function:  pause (SECONDS)
     Suspend the execution of the program.  If invoked without any
     arguments, Octave waits until you type a character.  With a
     numeric argument, it pauses for the given number of seconds.  For
     example, the following statement prints a message and then waits 5
     seconds before clearing the screen.

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

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

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

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

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

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

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

     Code    Format                         Example
     --------------------------------------------------------------- 
     0       dd-mmm-yyyy HH:MM:SS           07-Sep-2000 15:38:09
     1       dd-mmm-yyyy                    07-Sep-2000
     2       mm/dd/yy                       09/07/00
     3       mmm                            Sep
     4       m                              S
     5       mm                             09
     6       mm/dd                          09/07
     7       dd                             07
     8       ddd                            Thu
     9       d                              T
     10      yyyy                           2000
     11      yy                             00
     12      mmmyy                          Sep00
     13      HH:MM:SS                       15:38:09
     14      HH:MM:SS PM                    03:38:09 PM
     15      HH:MM                          15:38
     16      HH:MM PM                       03:38 PM
     17      QQ-YY                          Q3-00
     18      QQ                             Q3
     19      dd/mm                          13/03
     20      dd/mm/yy                       13/03/95
     21      mmm.dd.yyyy HH:MM:SS           Mar.03.1962 13:53:06
     22      mmm.dd.yyyy                    Mar.03.1962
     23      mm/dd/yyyy                     03/13/1962
     24      dd/mm/yyyy                     12/03/1962
     25      yy/mm/dd                       95/03/13
     26      yyyy/mm/dd                     1995/03/13
     27      QQ-YYYY                        Q4-2132
     28      mmmyyyy                        Mar2047
     29      yyyymmdd                       20470313
     30      yyyymmddTHHMMSS                20470313T132603
     31      yyyy-mm-dd HH:MM:SS            1047-03-13 13:26:03

     If F is a format string, the following symbols are recognised:

     Symbol  Meaning                                         Example
     ---------------------------------------------------------------------- 
     yyyy    Full year                                       2005
     yy      Two-digit year                                  2005
     mmmm    Full month name                                 December
     mmm     Abbreviated month name                          Dec
     mm      Numeric month number (padded with zeros)        01, 08, 12
     m       First letter of month name (capitalized)        D
     dddd    Full weekday name                               Sunday
     ddd     Abbreviated weekday name                        Sun
     dd      Numeric day of month (padded with zeros)        11
     d       First letter of weekday name (capitalized)      S
     HH      Hour of day, padded with zeros if PM is set     09:00
             and not padded with zeros otherwise             9:00 AM
     MM      Minute of hour (padded with zeros)              10:05
     SS      Second of minute (padded with zeros)            10:05:03
     PM      Use 12-hour time format                         11:30 PM

     If F is not specified or is `-1', then use 0, 1 or 16, depending
     on whether the date portion or the time portion of DATE is empty.

     If P is nor specified, it defaults to the current year minus 50.

     If a matrix or cell array of dates is given, a vector of date
     strings is returned.


     *See also:* datenum, datevec, date, clock, now, datetick.

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

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

     F is the format string used to interpret date strings (see
     `datestr').

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

     *See also:* datenum, datestr, date, clock, now.

 -- Function File:  calendar (...)
 -- Function File: C = calendar ()
 -- Function File: C = calendar (D)
 -- Function File: C = calendar (Y, M)
     If called with no arguments, return the current monthly calendar in
     a 6x7 matrix.

     If D is specified, return the calendar for the month containing
     the day D, which must be a serial date number or a date string.

     If Y and M are specified, return the calendar for year Y and month
     M.

     If no output arguments are specified, print the calendar on the
     screen instead of returning a matrix.

     *See also:* datenum.

 -- Function File: [N, S] = weekday (D, [FORM])
     Return the day of week as a number in N and a string in S, for
     example `[1, "Sun"]', `[2, "Mon"]', ..., or `[7, "Sat"]'.

     D is a serial date number or a date string.

     If the string FORM is given and is `"long"', S will contain the
     full name of the weekday; otherwise (or if FORM is `"short"'), S
     will contain the abbreviated name of the weekday.

     *See also:* datenum, datevec, eomday.

 -- Function File: E = eomday (Y, M)
     Return the last day of the month M for the year Y.

     *See also:* datenum, datevec, weekday, eomdate.


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

35.2 Filesystem Utilities
=========================

Octave includes the following functions for renaming and deleting files,
creating, deleting, and reading directories, and for getting information
about the status of files.

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

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

     *See also:* ls, dir.

 -- Built-in Function: [ERR, MSG] = link (OLD, NEW)
     Create a new link (also known as a hard link) to an existing file.

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

     *See also:* symlink.

 -- Built-in Function: [ERR, MSG] = symlink (OLD, NEW)
     Create a symbolic link NEW which contains the string OLD.

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

     *See also:* link, readlink.

 -- Built-in Function: [RESULT, ERR, MSG] = readlink (SYMLINK)
     Read the value of the symbolic link SYMLINK.

     If successful, RESULT contains the contents of the symbolic link
     SYMLINK, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     *See also:* link, symlink.

 -- Built-in Function: [ERR, MSG] = unlink (FILE)
     Delete the file named FILE.

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

 -- Built-in Function: [FILES, ERR, MSG] = readdir (DIR)
     Return names of the files in the directory DIR as a cell array of
     strings.  If an error occurs, return an empty cell array in FILES.

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

     *See also:* dir, glob.

 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (PARENT, DIR)
     Create a directory named DIR.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* rmdir.

 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR, `"s"')
     Remove the directory named DIR.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     If the optional second parameter is supplied with value `"s"',
     recursively remove all subdirectories as well.

     *See also:* mkdir, confirm_recursive_rmdir.

 -- Built-in Function: VAL = confirm_recursive_rmdir ()
 -- Built-in Function: OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will ask for confirmation before recursively removing a directory
     tree.

 -- Built-in Function: [ERR, MSG] = mkfifo (NAME, MODE)
     Create a FIFO special file named NAME with file mode MODE

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

 -- Built-in Function:  umask (MASK)
     Set the permission mask for file creation.  The parameter MASK is
     an integer, interpreted as an octal number.  If successful,
     returns the previous value of the mask (as an integer to be
     interpreted as an octal number); otherwise an error message is
     printed.

 -- Built-in Function: [INFO, ERR, MSG] = stat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
     Return a structure S containing the following information about
     FILE.

    `dev'
          ID of device containing a directory entry for this file.

    `ino'
          File number of the file.

    `mode'
          File mode, as an integer.  Use the functions `S_ISREG',
          `S_ISDIR', `S_ISCHR', `S_ISBLK', `S_ISFIFO', `S_ISLNK', or
          `S_ISSOCK' to extract information from this value.

    `modestr'
          File mode, as a string of ten letters or dashes as would be
          returned by `ls -l'.

    `nlink'
          Number of links.

    `uid'
          User ID of file's owner.

    `gid'
          Group ID of file's group.

    `rdev'
          ID of device for block or character special files.

    `size'
          Size in bytes.

    `atime'
          Time of last access in the same form as time values returned
          from `time'.  *Note Timing Utilities::.

    `mtime'
          Time of last modification in the same form as time values
          returned from `time'.  *Note Timing Utilities::.

    `ctime'
          Time of last file status change in the same form as time
          values returned from `time'.  *Note Timing Utilities::.

    `blksize'
          Size of blocks in the file.

    `blocks'
          Number of blocks allocated for file.

     If the call is successful ERR is 0 and MSG is an empty string.  If
     the file does not exist, or some other error occurs, S is an empty
     matrix, ERR is -1, and MSG contains the corresponding system error
     message.

     If FILE is a symbolic link, `stat' will return information about
     the actual file that is referenced by the link.  Use `lstat' if
     you want information about the symbolic link itself.

     For example,

          [s, err, msg] = stat ("/vmlinuz")
                => s =
                  {
                    atime = 855399756
                    rdev = 0
                    ctime = 847219094
                    uid = 0
                    size = 389218
                    blksize = 4096
                    mtime = 847219094
                    gid = 6
                    nlink = 1
                    blocks = 768
                    mode = -rw-r--r--
                    modestr = -rw-r--r--
                    ino = 9316
                    dev = 2049
                  }
               => err = 0
               => msg =

 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
     See stat.

 -- Function File: [STATUS, MSG, MSGID] = fileattrib (FILE)
     Return information about FILE.

     If successful, STATUS is 1, with RESULT containing a structure
     with the following fields:

    `Name'
          Full name of FILE.

    `archive'
          True if FILE is an archive (Windows).

    `system'
          True if FILE is a system file (Windows).

    `hidden'
          True if FILE is a hidden file (Windows).

    `directory'
          True if FILE is a directory.

    `UserRead'
    `GroupRead'
    `OtherRead'
          True if the user (group; other users) has read permission for
          FILE.

    `UserWrite'
    `GroupWrite'
    `OtherWrite'
          True if the user (group; other users) has write permission for
          FILE.

    `UserExecute'
    `GroupExecute'
    `OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.
     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

     With no input arguments, return information about the current
     directory.

     If FILE contains globbing characters, return information about all
     the matching files.

     *See also:* glob.

 -- Function File:  isdir (F)
     Return true if F is a directory.

 -- Built-in Function:  glob (PATTERN)
     Given an array of strings (as a char array or a cell array) in
     PATTERN, return a cell array of file names that match any of them,
     or an empty cell array if no patterns match.  Tilde expansion is
     performed on each of the patterns before looking for matching file
     names.  For example,

          glob ("/vm*")
               => "/vmlinuz"


     *See also:* dir, ls, stat, readdir.

 -- Built-in Function:  fnmatch (PATTERN, STRING)
     Return 1 or zero for each element of STRING that matches any of
     the elements of the string array PATTERN, using the rules of
     filename pattern matching.  For example,

          fnmatch ("a*b", {"ab"; "axyzb"; "xyzab"})
               => [ 1; 1; 0 ]

 -- Built-in Function:  file_in_path (PATH, FILE)
 -- Built-in Function:  file_in_path (PATH, FILE, "all")
     Return the absolute name of FILE if it can be found in PATH.  The
     value of PATH should be a colon-separated list of directories in
     the format described for `path'.  If no file is found, return an
     empty matrix.  For example,

          file_in_path (EXEC_PATH, "sh")
               => "/bin/sh"

     If the second argument is a cell array of strings, search each
     directory of the path for element of the cell array and return the
     first that matches.

     If the third optional argument `"all"' is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

     *See also:* file_in_loadpath.

 -- Built-in Function:  tilde_expand (STRING)
     Performs tilde expansion on STRING.  If STRING begins with a tilde
     character, (`~'), all of the characters preceding the first slash
     (or all characters, if there is no slash) are treated as a
     possible user name, and the tilde and the following characters up
     to the slash are replaced by the home directory of the named user.
     If the tilde is followed immediately by a slash, the tilde is
     replaced by the home directory of the user running Octave.  For
     example,

          tilde_expand ("~joeuser/bin")
               => "/home/joeuser/bin"
          tilde_expand ("~/bin")
               => "/home/jwe/bin"

 -- Built-in Function: [CNAME, STATUS, MSG] canonicalize_file_name
          (NAME)
     Return the canonical name of file NAME.

 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2)
     Move the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.

     If successful, STATUS is 1, with MSG and MSGID empty\n\ character
     strings.  Otherwise, STATUS is 0, MSG contains a\n\
     system-dependent error message, and MSGID contains a unique\n\
     message identifier.\n\

     *See also:* glob.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, FORCE)
     Copy the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory. If FORCE is given and equals the string "f" the
     copy operation will be forced.

     If successful, STATUS is 1, with MSG and MSGID empty\n\ character
     strings.  Otherwise, STATUS is 0, MSG contains a\n\
     system-dependent error message, and MSGID contains a unique\n\
     message identifier.\n\

     *See also:* glob, movefile.

 -- Function File: [DIR, NAME, EXT, VER] = fileparts (FILENAME)
     Return the directory, name, extension, and version components of
     FILENAME.

     *See also:* fullfile.

 -- Built-in Function:  filesep ()
     Return the system-dependent character used to separate directory
     names.

     *See also:* pathsep, dir, ls.

 -- Function File: FILENAME = fullfile (DIR1, DIR2, ..., FILE)
     Return a complete filename constructed from the given components.

     *See also:* fileparts.

 -- Function File: DIR = tempdir ()
     Return the name of the system's directory for temporary files.

 -- Function File: filename =  tempname ()
     This function is an alias for `tmpnam'.

 -- Built-in Function:  P_tmpdir ()
     Return the default name of the directory for temporary files on
     this system.  The name of this directory is system dependent.


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

35.3 File Archiving Utilities
=============================

 -- Function File:  bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE to the directory DIR. If DIR is
     not specified, it defaults to the current directory.

     *See also:* unpack, bzip2, tar, untar, gzip, gunzip, zip, unzip.

 -- Function File: ENTRIES = gzip (FILES)
 -- Function File: ENTRIES = gzip (FILES, OUTDIR)
     Compress the list of files and/or directories specified in FILES.
     Each file is compressed separately and a new file with a '.gz'
     extension is created. The original file is not touched. If ROOTDIR
     is defined the compressed versions of the files are placed in this
     directory.

     *See also:* gunzip, zip, tar.

 -- Function File:  gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE to the directory DIR. If DIR is not
     specified, it defaults to the current directory. If the GZFILE is
     a directory, all files in the directory will be recursively
     gunzipped.

     *See also:* unpack, bzip2, bunzip2, tar, untar, gzip, gunzip, zip,
     unzip.

 -- Function File: ENTRIES = tar (TARFILE, FILES, ROOT)
     Pack FILES FILES into the TAR archive TARFILE.  The list of files
     must be a string or a cell array of strings.

     The optional argument ROOT changes the relative path of FILES from
     the current directory.

     If an output argument is requested the entries in the archive are
     returned in a cell array.

     *See also:* untar, gzip, gunzip, zip, unzip.

 -- Function File:  untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* unpack, bzip2, bunzip2, tar, gzip, gunzip, zip, unzip.

 -- Function File: ENTRIES = zip (ZIPFILE, FILES)
 -- Function File: ENTRIES = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and/or directories specified in FILES
     into the archive ZIPFILES in the same directory. If ROOTDIR is
     defined the FILES is located relative to ROOTDIR rather than the
     current directory

     *See also:* unzip,tar.

 -- Function File:  unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* unpack, bzip2, bunzip2, tar, untar, gzip, gunzip, zip.

 -- Function File:  pack ()
     This function is provided for compatibility with MATLAB, but it
     doesn't actually do anything.

 -- Function File: FILES = unpack (FILE, DIR)
 -- Function File: FILES = unpack (FILE, DIR, FILETYPE)
     Unpack the archive FILE based on its extension to the directory
     DIR.  If FILE is a cellstr, then all files will be handled
     individually.  If DIR is not specified, it defaults to the current
     directory.  It returns a list of FILES unpacked. If a directory is
     in the file list, then the FILETYPE to unpack must also be
     specified.

     The FILES includes the entire path to the output files.

     *See also:* bzip2,bunzip2,tar,untar,gzip,gunzip,zip,unzip.


File: octave.info,  Node: Networking Utilities,  Next: Controlling Subprocesses,  Prev: File Archiving Utilities,  Up: System Utilities

35.4 Networking Utilities
=========================

 -- Loadable Function: S = urlread (URL)
 -- Loadable Function: [S, SUCCESS] = urlread (URL)
 -- Loadable Function: [S, SUCCESS, MESSAGE] = urlread (URL)
 -- Loadable Function: [...] = urlread (URL, METHOD, PARAM)
     Download a remote file specified by its URL and return its content
     in string S.  For example,

          s = urlread ("ftp://ftp.octave.org/pub/octave/README");

     The variable SUCCESS is 1 if the download was successful,
     otherwise it is 0 in which case MESSAGE contains an error message.
     If no output argument is specified and if an error occurs, then
     the error is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL.  For example,

          s = urlread ("http://user:password@example.com/file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example,

          s = urlread ("http://www.google.com/search", "get",
                       {"query", "octave"});


     *See also:* urlwrite.

 -- Loadable Function:  urlwrite (URL, LOCALFILE)
 -- Loadable Function: F = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS] = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS, MESSAGE] = urlwrite (URL, LOCALFILE)
     Download a remote file specified by its URL and save it as
     LOCALFILE.  For example,

          urlwrite ("ftp://ftp.octave.org/pub/octave/README",
                    "README.txt");

     The full path of the downloaded file is returned in F.  The
     variable SUCCESS is 1 if the download was successful, otherwise it
     is 0 in which case MESSAGE contains an error message.  If no
     output argument is specified and if an error occurs, then the
     error is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL, for example:

          urlwrite ("http://username:password@example.com/file.txt",
                    "file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example:

          urlwrite ("http://www.google.com/search", "search.html",
                    "get", {"query", "octave"});


     *See also:* urlread.


File: octave.info,  Node: Controlling Subprocesses,  Next: Process ID Information,  Prev: Networking Utilities,  Up: System Utilities

35.5 Controlling Subprocesses
=============================

Octave includes some high-level commands like `system' and `popen' for
starting subprocesses.  If you want to run another program to perform
some task and then look at its output, you will probably want to use
these functions.

   Octave also provides several very low-level Unix-like functions which
can also be used for starting subprocesses, but you should probably only
use them if you can't find any way to do what you need with the
higher-level functions.

 -- Built-in Function:  system (STRING, RETURN_OUTPUT, TYPE)
     Execute a shell command specified by STRING.  The second argument
     is optional.  If TYPE is `"async"', the process is started in the
     background and the process id of the child process is returned
     immediately.  Otherwise, the process is started, and Octave waits
     until it exits.  If TYPE argument is omitted, a value of `"sync"'
     is assumed.

     If two input arguments are given (the actual value of
     RETURN_OUTPUT is irrelevant) and the subprocess is started
     synchronously, or if SYSTEM is called with one input argument and
     one or more output arguments, the output from the command is
     returned.  Otherwise, if the subprocess is executed synchronously,
     its output is sent to the standard output.  To send the output of
     a command executed with SYSTEM through the pager, use a command
     like

          disp (system (cmd, 1));

     or

          printf ("%s
          ", system (cmd, 1));

     The `system' function can return two values.  The first is the
     exit status of the command and the second is any output from the
     command that was written to the standard output stream.  For
     example,

          [status, output] = system ("echo foo; exit 2");

     will set the variable `output' to the string `foo', and the
     variable `status' to the integer `2'.

 -- Function File: [STATUS, TEXT] unix (COMMAND)
 -- Function File: [STATUS, TEXT] unix (COMMAND, "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* isunix, ispc, system.

 -- Function File: [STATUS, TEXT] = dos (COMMAND)
 -- Function File: [STATUS, TEXT] = dos (COMMAND, "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* unix, isunix, ispc, system.

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.  The name of the command to run
     is given by COMMAND.  The file identifier corresponding to the
     input or output stream of the process is returned in FID.  The
     argument MODE may be

    `"r"'
          The pipe will be connected to the standard output of the
          process, and open for reading.

    `"w"'
          The pipe will be connected to the standard input of the
          process, and open for writing.

     For example,

          fid = popen ("ls -ltr / | tail -3", "r");
          while (isstr (s = fgets (fid)))
            fputs (stdout, s);
          endwhile
               -| drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
               -| drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
               -| drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

 -- Built-in Function:  pclose (FID)
     Close a file identifier that was opened by `popen'.  You may also
     use `fclose' for the same purpose.

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.  The name of the
     process is given by COMMAND, and ARGS is an array of strings
     containing options for the command.  The file identifiers for the
     input and output streams of the subprocess are returned in IN and
     OUT.  If execution of the command is successful, PID contains the
     process ID of the subprocess.  Otherwise, PID is -1.

     For example,

          [in, out, pid] = popen2 ("sort", "-r");
          fputs (in, "these\nare\nsome\nstrings\n");
          fclose (in);
          EAGAIN = errno ("EAGAIN");
          done = false;
          do
            s = fgets (out);
            if (ischar (s))
              fputs (stdout, s);
            elseif (errno () == EAGAIN)
              sleep (0.1);
              fclear (out);
            else
              done = true;
            endif
          until (done)
          fclose (out);
               -| are
               -| some
               -| strings
               -| these

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
     Query or set the internal variable that specifies a colon separated
     list of directories to search when executing external programs.
     Its initial value is taken from the environment variable
     `OCTAVE_EXEC_PATH' (if it exists) or `PATH', but that value can be
     overridden by the command line argument `--exec-path PATH'.  At
     startup, an additional set of directories (including the shell
     PATH) is appended to the path specified in the environment or on
     the command line.  If you use the `EXEC_PATH' function to modify
     the path, you should take care to preserve these additional
     directories.

   In most cases, the following functions simply decode their arguments
and make the corresponding Unix system calls.  For a complete example
of how they can be used, look at the definition of the function
`popen2'.

 -- Built-in Function: [PID, MSG] = fork ()
     Create a copy of the current process.

     Fork can return one of the following values:

    > 0
          You are in the parent process.  The value returned from
          `fork' is the process id of the child process.  You should
          probably arrange to wait for any child processes to exit.

    0
          You are in the child process.  You can call `exec' to start
          another process.  If that fails, you should probably call
          `exit'.

    < 0
          The call to `fork' failed for some reason.  You must take
          evasive action.  A system dependent error message will be
          waiting in MSG.

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.  Calling `exec' without
     first calling `fork' will terminate your current Octave process and
     replace it with the program named by FILE.  For example,

          exec ("ls" "-l")

     will run `ls' and return you to your shell prompt.

     If successful, `exec' does not return.  If `exec' does return, ERR
     will be nonzero, and MSG will contain a system-dependent error
     message.

 -- Built-in Function: [READ_FD, WRITE_FD, ERR, MSG] = pipe ()
     Create a pipe and return the reading and writing ends of the pipe
     into READ_FD and WRITE_FD respectively.

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

 -- Built-in Function: [FID, MSG] = dup2 (OLD, NEW)
     Duplicate a file descriptor.

     If successful, FID is greater than zero and contains the new file
     ID.  Otherwise, FID is negative and MSG contains a
     system-dependent error message.

 -- Built-in Function: [PID, STATUS, MSG] = waitpid (PID, OPTIONS)
     Wait for process PID to terminate.  The PID argument can be:

    -1
          Wait for any child process.

    0
          Wait for any child process whose process group ID is equal to
          that of the Octave interpreter process.

    > 0
          Wait for termination of the child process with ID PID.

     The OPTIONS argument can be a bitwise OR of zero or more of the
     following constants:

    `0'
          Wait until signal is received or a child process exits (this
          is the default if the OPTIONS argument is missing).

    `WNOHANG'
          Do not hang if status is not immediately available.

    `WUNTRACED'
          Report the status of any child processes that are stopped,
          and whose status has not yet been reported since they stopped.

    `WCONTINUED'
          Return if a stopped child has been resumed by delivery of
          `SIGCONT'.  This value may not be meaningful on all systems.

     If the returned value of PID is greater than 0, it is the process
     ID of the child process that exited.  If an error occurs, PID will
     be less than zero and MSG will contain a system-dependent error
     message.  The value of STATUS contains additional system-dependent
     information about the subprocess that exited.

     *See also:* WCONTINUED, WCOREDUMP, WEXITSTATUS, WIFCONTINUED,
     WIFSIGNALED, WIFSTOPPED, WNOHANG, WSTOPSIG, WTERMSIG, WUNTRACED.

 -- Built-in Function: [ERR, MSG] = fcntl (FID, REQUEST, ARG)
     Change the properties of the open file FID.  The following values
     may be passed as REQUEST:

    `F_DUPFD'
          Return a duplicate file descriptor.

    `F_GETFD'
          Return the file descriptor flags for FID.

    `F_SETFD'
          Set the file descriptor flags for FID.

    `F_GETFL'
          Return the file status flags for FID.  The following codes
          may be returned (some of the flags may be undefined on some
          systems).

         `O_RDONLY'
               Open for reading only.

         `O_WRONLY'
               Open for writing only.

         `O_RDWR'
               Open for reading and writing.

         `O_APPEND'
               Append on each write.

         `O_CREAT'
               Create the file if it does not exist.

         `O_NONBLOCK'
               Nonblocking mode.

         `O_SYNC'
               Wait for writes to complete.

         `O_ASYNC'
               Asynchronous I/O.

    `F_SETFL'
          Set the file status flags for FID to the value specified by
          ARG.  The only flags that can be changed are `O_APPEND' and
          `O_NONBLOCK'.

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

 -- Built-in Function: [ERR, MSG] = kill (PID, SIG)
     Send signal SIG to process PID.

     If PID is positive, then signal SIG is sent to PID.

     If PID is 0, then signal SIG is sent to every process in the
     process group of the current process.

     If PID is -1, then signal SIG is sent to every process except
     process 1.

     If PID is less than -1, then signal SIG is sent to every process
     in the process group -PID.

     If SIG is 0, then no signal is sent, but error checking is still
     performed.

     Return 0 if successful, otherwise return -1.

 -- Built-in Function:  SIG ()
     Return a structure containing Unix signal names and their defined
     values.


File: octave.info,  Node: Process ID Information,  Next: Environment Variables,  Prev: Controlling Subprocesses,  Up: System Utilities

35.6 Process, Group, and User IDs
=================================

 -- Built-in Function: pgid = getpgrp ()
     Return the process group id of the current process.

 -- Built-in Function: pid = getpid ()
     Return the process id of the current process.

 -- Built-in Function: pid = getppid ()
     Return the process id of the parent process.

 -- Built-in Function: euid = geteuid ()
     Return the effective user id of the current process.

 -- Built-in Function: uid = getuid ()
     Return the real user id of the current process.

 -- Built-in Function: egid = getegid ()
     Return the effective group id of the current process.

 -- Built-in Function: gid = getgid ()
     Return the real group id of the current process.


File: octave.info,  Node: Environment Variables,  Next: Current Working Directory,  Prev: Process ID Information,  Up: System Utilities

35.7 Environment Variables
==========================

 -- Built-in Function:  getenv (VAR)
     Return the value of the environment variable VAR.  For example,

          getenv ("PATH")

     returns a string containing the value of your path.

 -- Built-in Function:  putenv (VAR, VALUE)
 -- Built-in Function:  setenv (VAR, VALUE)
     Set the value of the environment variable VAR to VALUE.


File: octave.info,  Node: Current Working Directory,  Next: Password Database Functions,  Prev: Environment Variables,  Up: System Utilities

35.8 Current Working Directory
==============================

 -- Command: cd dir
 -- Command: chdir dir
     Change the current working directory to DIR.  If DIR is omitted,
     the current directory is changed to the user's home directory.
     For example,

          cd ~/octave

     Changes the current working directory to `~/octave'.  If the
     directory does not exist, an error message is printed and the
     working directory is not changed.

     *See also:* mkdir, rmdir, dir.

 -- Command: ls options
     List directory contents.  For example,

          ls -l
          -| total 12
          -| -rw-r--r--   1 jwe  users  4488 Aug 19 04:02 foo.m
          -| -rw-r--r--   1 jwe  users  1315 Aug 17 23:14 bar.m

     The `dir' and `ls' commands are implemented by calling your
     system's directory listing command, so the available options may
     vary from system to system.

     *See also:* dir, stat, readdir, glob, filesep, ls_command.

 -- Function File: [OLD_CMD = ls_command (CMD)
     Set or return the shell command used by Octave's `ls' command.
     The value of CMD must be a character string.  With no arguments,
     simply return the previous value.

     *See also:* ls.

 -- Function File:  dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.  If a return value
     is requested, return a structure array with the fields

          name
          bytes
          date
          isdir
          statinfo

     in which `statinfo' is the structure returned from `stat'.

     If DIRECTORY is not a directory, return information about the
     named FILENAME.  DIRECTORY may be a list of directories specified
     either by name or with wildcard characters (like * and ?)  which
     will be expanded with glob.

     Note that for symbolic links, `dir' returns information about the
     file that a symbolic link points to instead of the link itself.
     However, if the link points to a nonexistent file, `dir' returns
     information about the link.

     *See also:* ls, stat, lstat, readdir, glob, filesep.

 -- Built-in Function:  pwd ()
     Return the current working directory.

     *See also:* dir, ls.


File: octave.info,  Node: Password Database Functions,  Next: Group Database Functions,  Prev: Current Working Directory,  Up: System Utilities

35.9 Password Database Functions
================================

Octave's password database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`uid'
     The numeric user id.

`gid'
     The numeric group id.

`gecos'
     The GECOS field.

`dir'
     The home directory.

`shell'
     The initial shell.

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

 -- Loadable Function: PW_STRUCT =  getpwent ()
     Return a structure containing an entry from the password database,
     opening it if necessary. Once the end of the data has been reached,
     `getpwent' returns 0.

 -- Loadable Function: PW_STRUCT =  getpwuid (UID).
     Return a structure containing the first entry from the password
     database with the user ID UID.  If the user ID does not exist in
     the database, `getpwuid' returns 0.

 -- Loadable Function: PW_STRUCT =  getpwnam (NAME)
     Return a structure containing the first entry from the password
     database with the user name NAME.  If the user name does not exist
     in the database, `getpwname' returns 0.

 -- Loadable Function:  setpwent ()
     Return the internal pointer to the beginning of the password
     database.

 -- Loadable Function:  endpwent ()
     Close the password database.


File: octave.info,  Node: Group Database Functions,  Next: System Information,  Prev: Password Database Functions,  Up: System Utilities

35.10 Group Database Functions
==============================

Octave's group database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`gid'
     The numeric group id.

`mem'
     The members of the group.

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

 -- Loadable Function: GRP_STRUCT = getgrent ()
     Return an entry from the group database, opening it if necessary.
     Once the end of the data has been reached, `getgrent' returns 0.

 -- Loadable Function: GRP_STRUCT = getgrgid (GID).
     Return the first entry from the group database with the group ID
     GID.  If the group ID does not exist in the database, `getgrgid'
     returns 0.

 -- Loadable Function: GRP_STRUCT = getgrnam (NAME)
     Return the first entry from the group database with the group name
     NAME.  If the group name does not exist in the database,
     `getgrname' returns 0.

 -- Loadable Function:  setgrent ()
     Return the internal pointer to the beginning of the group database.

 -- Loadable Function:  endgrent ()
     Close the group database.


File: octave.info,  Node: System Information,  Next: Hashing Functions,  Prev: Group Database Functions,  Up: System Utilities

35.11 System Information
========================

 -- Function File: [C, MAXSIZE, ENDIAN] = computer ()
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the kind of computer Octave is running on.  If invoked with an
     output argument, the value is returned instead of printed.  For
     example,

          computer ()
          -| i586-pc-linux-gnu

          x = computer ()
          => x = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.

     If three output arguments are requested, also return the byte order
     of the current system as a character (`"B"' for big-endian or
     `"L"' for little-endian).

 -- Built-in Function: [UTS, ERR, MSG] = uname ()
     Return system information in the structure.  For example,

          uname ()
               => {
                     sysname = x86_64
                     nodename = segfault
                     release = 2.6.15-1-amd64-k8-smp
                     version = Linux
                     machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006
                   }

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

 -- Function File:  ispc ()
     Return 1 if Octave is running on a Windows system and 0 otherwise.

     *See also:* ismac, isunix.

 -- Function File:  isunix ()
     Return 1 if Octave is running on a Unix-like system and 0
     otherwise.

     *See also:* ismac, ispc.

 -- Built-in Function:  isieee ()
     Return 1 if your computer claims to conform to the IEEE standard
     for floating point calculations.

 -- Built-in Function:  OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory.

 -- Built-in Function:  OCTAVE_VERSION ()
     Return the version number of Octave, as a string.

 -- Function File:  version ()
     Return Octave's version number as a string.  This is also the
     value of the built-in variable `OCTAVE_VERSION'.

 -- Function File:  ver ()
     Display a header containing the current Octave version number,
     license string and operating system.

     *See also:* license, version.

 -- Built-in Function:  octave_config_info (OPTION)
     Return a structure containing configuration and installation
     information for Octave.

     if OPTION is a string, return the configuration information for the
     specified option.


 -- Loadable Function:  getrusage ()
     Return a structure containing a number of statistics about the
     current Octave process.  Not all fields are available on all
     systems.  If it is not possible to get CPU time statistics, the
     CPU time slots are set to zero.  Other missing data are replaced
     by NaN.  Here is a list of all the possible fields that can be
     present in the structure returned by `getrusage':

    `idrss'
          Unshared data size.

    `inblock'
          Number of block input operations.

    `isrss'
          Unshared stack size.

    `ixrss'
          Shared memory size.

    `majflt'
          Number of major page faults.

    `maxrss'
          Maximum data size.

    `minflt'
          Number of minor page faults.

    `msgrcv'
          Number of messages received.

    `msgsnd'
          Number of messages sent.

    `nivcsw'
          Number of involuntary context switches.

    `nsignals'
          Number of signals received.

    `nswap'
          Number of swaps.

    `nvcsw'
          Number of voluntary context switches.

    `oublock'
          Number of block output operations.

    `stime'
          A structure containing the system CPU time used.  The
          structure has the elements `sec' (seconds) `usec'
          (microseconds).

    `utime'
          A structure containing the user CPU time used.  The structure
          has the elements `sec' (seconds) `usec' (microseconds).


File: octave.info,  Node: Hashing Functions,  Prev: System Information,  Up: System Utilities

35.12 Hashing Functions
=======================

It is often necessary to find if two strings or files are identical.
This might be done by comparing them character by character and looking
for differences. However, this can be slow, and so comparing a hash of
the string or file can be a rapid way of finding if the files differ.

   Another use of the hashing function is to check for file integrity.
The user can check the hash of the file against a known value and find
if the file they have is the same as the one that the original hash was
produced with.

   Octave supplies the `md5sum' function to perform MD5 hashes on
strings and files. An example of the use of `md5sum' function might be

     if exist (file, "file")
       hash = md5sum (file);
     else
       # Treat the variable "file" as a string
       hash = md5sum (file, true);
     endif

 -- Loadable Function:  md5sum (FILE)
 -- Loadable Function:  md5sum (STR, OPT)
     Calculates the MD5 sum of the file FILE. If the second parameter
     OPT exists and is true, then calculate the MD5 sum of the string
     STR.


File: octave.info,  Node: Packages,  Next: Dynamically Linked Functions,  Prev: System Utilities,  Up: Top

36 Packages
***********

Since Octave is Free Software users are encouraged to share their
programs amongst each other. To aid this sharing Octave supports the
installation of extra packages. The `Octave-Forge' project is a
community-maintained set of packages that can be downloaded and
installed in Octave. At the time of writing the `Octave-Forge' project
can be found on-line at `http://octave.sourceforge.net', but since the
Internet is an ever-changing place this may not be true at the time of
reading. Therefore it is recommended to see the Octave website for an
updated reference.

* Menu:

* Installing and Removing Packages::
* Using Packages::
* Administrating Packages::
* Creating Packages::


File: octave.info,  Node: Installing and Removing Packages,  Next: Using Packages,  Up: Packages

36.1 Installing and Removing Packages
=====================================

Assuming a package is available in the file `image-1.0.0.tar.gz' it can
be installed from the Octave prompt by writing

     pkg install image-1.0.0.tar.gz

If the package is installed successfully nothing will be printed on the
prompt, but if an error occurred during installation it will be
reported. It is possible to install several packages at once by writing
several package files after the `pkg install' command.  If a different
version of the package is already installed it will be removed prior to
installing the new package. This makes it easy to upgrade and downgrade
the version of a package, but makes it impossible to have several
versions of the same package installed at once.

   To see which packages are installed type

     pkg list
     -| Package Name  | Version | Installation directory
     -| --------------+---------+-----------------------
     -|        image *|   1.0.0 | /home/jwe/octave/image-1.0.0

In this case only version 1.0.0 of the `image' package is installed.
The '*' character next to the package name shows that the image package
is loaded and ready for use.

   It is possible to remove a package from the system using the `pkg
uninstall' command like this

     pkg uninstall image

If the package is removed successfully nothing will be printed in the
prompt, but if an error occurred it will be reported. It should be
noted that the package file used for installation is not needed for
removal, and that only the package name as reported by `pkg list'
should be used when removing a package. It is possible to remove
several packages at once by writing several package names after the
`pkg uninstall' command.

   To minimize the amount of code duplication between packages it is
possible that one package depends on another one. If a package depends
on another, it will check if that package is installed during
installation. If it is not, an error will be reported and the package
will not be installed. This behaviour can be disabled by passing the
`-nodeps' flag to the `pkg install' command

     pkg install -nodeps my_package_with_dependencies.tar.gz

Since the installed package expects its dependencies to be installed it
may not function correctly. Because of this it is not recommended to
disable dependency checking.


File: octave.info,  Node: Using Packages,  Next: Administrating Packages,  Prev: Installing and Removing Packages,  Up: Packages

36.2 Using Packages
===================

By default installed packages are available from the Octave prompt, but
it is possible to control this using the `pkg load' and `pkg unload'
commands. The functions from a package can be removed from the Octave
path by typing

     pkg unload package_name

where `package_name' is the name of the package to be removed from the
path.

   In much the same way a package can be added to the Octave path by
typing

     pkg load package_name


File: octave.info,  Node: Administrating Packages,  Next: Creating Packages,  Prev: Using Packages,  Up: Packages

36.3 Administrating Packages
============================

On UNIX-like systems it is possible to make both per-user and
system-wide installations of a package. If the user performing the
installation is `root' the packages will be installed in a system-wide
directory that defaults to `OCTAVE_HOME/share/octave/packages/'. If the
user is not `root' the default installation directory is `~/octave/'.
Packages will be installed in a subdirectory of the installation
directory that will be named after the package. It is possible to
change the installation directory by using the `pkg prefix' command

     pkg prefix new_installation_directory

The current installation directory can be retrieved by typing

     current_installation_directory = pkg prefix

   To function properly the package manager needs to keep some
information about the installed packages. For per-user packages this
information is by default stored in the file `~/.octave_packages' and
for system-wide installations it is stored in
`OCTAVE_HOME/share/octave/octave_packages'. The path to the per-user
file can be changed with the `pkg local_list' command

     pkg local_list /path/to/new_file

For system-wide installations this can be changed in the same way using
the `pkg global_list' command. If these commands are called without a
new path, the current path will be returned.


File: octave.info,  Node: Creating Packages,  Prev: Administrating Packages,  Up: Packages

36.4 Creating Packages
======================

Internally a package is simply a gzipped tar file that contains a top
level directory of any given name. This directory will in the following
be referred to as `package' and may contain the following files


`package/DESCRIPTION'
     This is a required file containing information about the package.
     *Note The DESCRIPTION File::, for details on this file.

`package/COPYING'
     This is a required file containing the license of the package. No
     restrictions is made on the license in general. If however the
     package contains dynamically linked functions the license must be
     compatible with the GNU General Public License.

`package/INDEX'
     This is an optional file describing the functions provided by the
     package. If this file is not given then one with be created
     automatically from the functions in the package and the
     `Categories' keyword in the `DESCRIPTION' file.  *Note The INDEX
     file::, for details on this file.

`package/PKG_ADD'
     An optional file that includes commands that are run when the
     package is added to the users path. Note that `PKG_ADD' directives
     in the source code of the package will also be added to this file
     by the Octave package manager. Note that symbolic links are to be
     avoided in packages, as symbolic links do not exist on some file
     systems, and so a typical use for this file is the replacement of
     the symbolic link

          ln -s foo.oct bar.oct

     with an autoload directive like

          autoload ('bar', which ('foo'));

     *Note PKG_ADD and PKG_DEL directives::, for details on `PKG_ADD'
     directives.

`package/PKG_DEL'
     An optional file that includes commands that are run when the
     package is removed from the users path. Note that `PKG_DEL'
     directives in the source code of the package will also be added to
     this file by the Octave package manager.  *Note PKG_ADD and
     PKG_DEL directives::, for details on `PKG_DEL' directives.

`package/pre_install.m'
     This is an optional script that is run prior to the installation
     of a package.

`package/post_install.m'
     This is an optional script that is run after the installation of a
     package.

`package/on_uninstall.m'
     This is an optional script that is run prior to the removal of a
     package.

   Besides the above mentioned files, a package can also contain on or
more of the following directories


`package/inst'
     An optional directory containing any files that are directly
     installed by the package. Typically this will include any
     `m'-files.

`package/src'
     An optional directory containing code that must be built prior to
     the packages installation. The Octave package manager will execute
     `./configure' in this directory if this script exists, and will
     then call `make' if a file `Makefile' exists in this directory.
     `make install' will however not be called. If a file called
     `FILES' exist all files listed there will be copied to the `inst'
     directory, so they also will be installed. If the `FILES' file
     doesn't exist, `src/*.m' and `src/*.oct' will be copied to the
     `inst' directory.

`package/doc'
     An optional directory containing documentation for the package. The
     files in this directory will be directly installed in a
     sub-directory of the installed package for future reference.

`package/bin'
     An optional directory containing files that will be added to the
     Octave `EXEC_PATH' when the package is loaded. This might contain
     external scripts, etc, called by functions within the package.

* Menu:

* The DESCRIPTION File::
* The INDEX file::
* PKG_ADD and PKG_DEL directives::


File: octave.info,  Node: The DESCRIPTION File,  Next: The INDEX file,  Up: Creating Packages

36.4.1 The DESCRIPTION File
---------------------------

The `DESCRIPTION' file contains various information about the package,
such as it's name, author, and version. This file has a very simple
format


   * Lines starting with `#' are comments.

   * Lines starting with a blank character are continuations from the
     previous line.

   * Everything else is of the form `NameOfOption: ValueOfOption'.

The following is a simple example of a `DESCRIPTION' file

     Name: The name of my package
     Version: 1.0.0
     Date: 2007-18-04
     Author: The name (and possibly email) of the package author.
     Maintainer: The name (and possibly email) of the current
      package maintainer.
     Title: The title of the package
     Description: A short description of the package. If this
      description gets too long for one line it can continue
      on the next by adding a space to the beginning of the
      following lines.
     License: GPL version 3 or later

   The package manager currently recognizes the following keywords


`Name'
     Name of the package.

`Version'
     Version of the package.

`Date'
     Date of last update.

`Author'
     Original author of the package.

`Maintainer'
     Maintainer of the package.

`Title'
     A one line description of the package.

`Description'
     A one paragraph description of the package.

`Categories'
     Optional keyword describing the package (if no `INDEX' file is
     given this is mandatory).

`Problems'
     Optional list of known problems.

`Url'
     Optional list of homepages related to the package.

`Autoload'
     Optional field that sets the default loading behavior for the
     package.  If set to `yes', `true' or `on', then Octave will
     automatically load the package when starting. Otherwise the package
     must be manually loaded with the pkg load command. This default
     behavior can be overridden when the package is installed.

`Depends'
     A list of other Octave packages that this package depends on. This
     can include dependencies on particular versions, with a format

          Depends: package (>= 1.0.0)

     Possible operators are `<', `<=', `==', `>=' or `>'. If the part
     of the dependency in `()' is missing, any version of the package
     is acceptable. Multiple dependencies can be defined either as a
     comma separated list or on separate `Depends' lines.

`License'
     An optional short description of the used license (e.g. GPL
     version 3 or newer). This is optional since the file `COPYING' is
     mandatory.

`SystemRequirements'
     These are the external install dependencies of the package and are
     not checked by the package manager. This is here as a hint to the
     distribution packager. They follows the same conventions as the
     `Depends' keyword.

`BuildRequires'
     These are the external build dependencies of the package and are
     not checked by the package manager. This is here as a hint to the
     distribution packager. They follows the same conventions as the
     `Depends' keyword. Note that in general, packaging systems such as
     `rpm' or `deb' and autoprobe the install dependencies from the
     build dependencies, and therefore the often a `BuildRequires'
     dependency removes the need for a `SystemRequirements' dependency.


The developer is free to add additional arguments to the `DESCRIPTION'
file for their own purposes. One further detail to aid the packager is
that the `SystemRequirements' and `BuildRequires' keywords can have
distribution dependent section, and the automatic build process will
use these. An example of the format of this is

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

where the first package name will be used as a default and if the RPMs
are built on a Mandriva distribution, then the second package name will
be used instead.


File: octave.info,  Node: The INDEX file,  Next: PKG_ADD and PKG_DEL directives,  Prev: The DESCRIPTION File,  Up: Creating Packages

36.4.2 The INDEX file
---------------------

The optional `INDEX' file provides an categorical view of the functions
in the package. This file has a very simple format


   * Lines beginning with `#' are comments.

   * The first non-comment line should look like this

          toolbox >> Toolbox name

   * Lines beginning with an alphabetical character indicates a new
     category of functions.

   * Lines starting with a white space character indicate that the
     function names on the line belong to last mentioned category.

The format can be summarized with the following example

     # A comment
     toolbox >> Toolbox name
     Category Name 1
      function1 function2 function3
      function4
     Category Name 2
      function2 function5


File: octave.info,  Node: PKG_ADD and PKG_DEL directives,  Prev: The INDEX file,  Up: Creating Packages

36.4.3 PKG_ADD and PKG_DEL directives
-------------------------------------

If the package contains files called `PKG_ADD' or `PKG_DEL' the
commands in these files will be executed when the package is added or
removed from the users path. In some situations such files are a bit
cumbersome to maintain, so the package manager supports automatic
creation of such files. If a source file in the package contains a
`PKG_ADD' or `PKG_DEL' directive they will be added to either the
`PKG_ADD' or `PKG_DEL' files.

   In `m'-files a `PKG_ADD' directive looks like this

     ## PKG_ADD: some_octave_command

Such lines should be added before the `function' keyword.  In C++ files
a `PKG_ADD' directive looks like this

     // PKG_ADD: some_octave_command

In both cases `some_octave_command' should be replaced by the command
that should be placed in the `PKG_ADD' file.  `PKG_DEL' directives work
in the same way, except the `PKG_ADD' keyword is replaced with
`PKG_DEL' and the commands get added to the `PKG_DEL' file.


File: octave.info,  Node: Dynamically Linked Functions,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A Dynamically Linked Functions
***************************************

Octave has the possibility of including compiled code as dynamically
linked extensions and then using these extensions as if they were part
of Octave itself.  Octave has the option of directly calling C++ code
through its native oct-file interface or C code through its mex
interface.  It can also indirectly call functions written in any other
language through a simple wrapper.  The reasons to write code in a
compiled language might be either to link to an existing piece of code
and allow it to be used within Octave, or to allow improved performance
for key pieces of code.

   Before going further, you should first determine if you really need
to use dynamically linked functions at all.  Before proceeding with
writing any dynamically linked function to improve performance you
should address ask yourself

   * Can I get the same functionality using the Octave scripting
     language only?

   * Is it thoroughly optimized Octave code?  Vectorization of Octave
     code, doesn't just make it concise, it generally significantly
     improves its performance.  Above all, if loops must be used, make
     sure that the allocation of space for variables takes place
     outside the loops using an assignment to a like matrix or zeros.

   * Does it make as much use as possible of existing built-in library
     routines?  These are highly optimized and many do not carry the
     overhead of being interpreted.

   * Does writing a dynamically linked function represent useful
     investment of your time, relative to staying in Octave?

   Also, as oct- and mex-files are dynamically linked to octave, they
introduce to possibility of having Octave abort due to coding errors in
the user code.  For example a segmentation violation in the user's code
will cause Octave to abort.

* Menu:

* Oct-Files::
* Mex-Files::
* Standalone Programs::


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: Dynamically Linked Functions

A.1 Oct-Files
=============

* Menu:

* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Test of Oct-Files::


File: octave.info,  Node: Getting Started with Oct-Files,  Next: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.1 Getting Started with Oct-Files
------------------------------------

The basic command to build oct-files is `mkoctfile' and it can be call
from within octave or from the command line.

 -- Function File:  mkoctfile [-options] file ...
     The `mkoctfile' function compiles source code written in C, C++,
     or Fortran.  Depending on the options used with `mkoctfile', the
     compiled code can be called within Octave or can be used as a
     stand-alone application.

     `mkoctfile' can be called from the shell prompt or from the Octave
     prompt.

     `mkoctfile' accepts the following options, all of which are
     optional except for the file name of the code you wish to compile:

    `-I DIR'
          Add the include directory DIR to compile commands.

    `-D DEF'
          Add the definition DEF to the compiler call.

    `-l LIB'
          Add the library LIB to the link command.

    `-L DIR'
          Add the library directory DIR to the link command.

    `-M'
    `--depend'
          Generate dependency files (.d) for C and C++ source files.

    `-c'
          Compile but do not link.

    `-g'
          Enable debugging options for compilers.

    `-o FILE'
    `--output FILE'
          Output file name.  Default extension is .oct (or .mex if -mex
          is specified) unless linking a stand-alone executable.

    `-p VAR'
    `--print VAR'
          Print the configuration variable VAR.  Recognized variables
          are:

                  ALL_CFLAGS                FFTW_LIBS
                  ALL_CXXFLAGS              FLIBS
                  ALL_FFLAGS                FPICFLAG
                  ALL_LDFLAGS               INCFLAGS
                  BLAS_LIBS                 LDFLAGS
                  CC                        LD_CXX
                  CFLAGS                    LD_STATIC_FLAG
                  CPICFLAG                  LFLAGS
                  CPPFLAGS                  LIBCRUFT
                  CXX                       LIBOCTAVE
                  CXXFLAGS                  LIBOCTINTERP
                  CXXPICFLAG                LIBREADLINE
                  DEPEND_EXTRA_SED_PATTERN  LIBS
                  DEPEND_FLAGS              OCTAVE_LIBS
                  DL_LD                     RDYNAMIC_FLAG
                  DL_LDFLAGS                RLD_FLAG
                  F2C                       SED
                  F2CFLAGS                  XTRA_CFLAGS
                  F77                       XTRA_CXXFLAGS
                  FFLAGS

    `--link-stand-alone'
          Link a stand-alone executable file.

    `--mex'
          Assume we are creating a MEX file.  Set the default output
          extension to ".mex".

    `-s'
    `--strip'
          Strip the output file.

    `-v'
    `--verbose'
          Echo commands as they are executed.

    `file'
          The file to compile or link. Recognised file types are

                                 .c    C source
                                 .cc   C++ source
                                 .C    C++ source
                                 .cpp  C++ source
                                 .f    Fortran source
                                 .F    Fortran source
                                 .o    object file


   Consider the short example

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>

     DEFUN_DLD (helloworld, args, nargout,
       "Hello World Help String")
     {
       int nargin = args.length ();
       octave_stdout << "Hello World has " << nargin
             << " input arguments and "
             << nargout << " output arguments.\n";
       return octave_value_list ();
     }

   This example although short introduces the basics of writing a C++
function that can be dynamically linked to Octave.  The easiest way to
make available most of the definitions that might be necessary for an
oct-file in Octave is to use the `#include <octave/oct.h>' header.

   The macro that defines the entry point into the dynamically loaded
function is `DEFUN_DLD'.  This macro takes four arguments, these being

  1. The function name as it will be seen in Octave,

  2. The list of arguments to the function of type `octave_value_list',

  3. The number of output arguments, which can and often is omitted if
     not used, and

  4. The string that will be seen as the help text of the function.

   The return type of functions defined with `DEFUN_DLD' is always
`octave_value_list'.

   There are a couple of important considerations in the choice of
function name.  Firstly, it must be a valid Octave function name and so
must be a sequence of letters, digits and underscores, not starting
with a digit.  Secondly, as Octave uses the function name to define the
filename it attempts to find the function in, the function name in the
`DEFUN_DLD' macro must match the filename of the oct-file.  Therefore,
the above function should be in a file `helloworld.cc', and it should be
compiled to an oct-file using the command

     mkoctfile helloworld.cc

   This will create a file call helloworld.oct, that is the compiled
version of the function.  It should be noted that it is perfectly
acceptable to have more than one `DEFUN_DLD' function in a source file.
However, there must either be a symbolic link to the oct-file for each
of the functions defined in the source code with the `DEFUN_DLD' macro
or the autoload (*Note Function Files::) function should be used.

   The rest of this function then shows how to find the number of input
arguments, how to print through the octave pager, and return from the
function.  After compiling this function as above, an example of its use
is

     helloworld (1, 2, 3)
     -| Hello World has 3 input arguments and 0 output arguments.


File: octave.info,  Node: Matrices and Arrays in Oct-Files,  Next: Character Strings in Oct-Files,  Prev: Getting Started with Oct-Files,  Up: Oct-Files

A.1.2 Matrices and Arrays in Oct-Files
--------------------------------------

Octave supports a number of different array and matrix classes, the
majority of which are based on the Array class.  The exception is the
sparse matrix types discussed separately below.  There are three basic
matrix types

`Matrix'
     A double precision matrix class defined in dMatrix.h,

`ComplexMatrix'
     A complex matrix class defined in CMatrix.h, and

`BoolMatrix'
     A boolean matrix class defined in boolMatrix.h.

   These are the basic two-dimensional matrix types of octave.  In
additional there are a number of multi-dimensional array types, these
being

`NDArray'
     A double precision array class defined in `dNDArray.h'

`ComplexNDarray'
     A complex array class defined in `CNDArray.h'

`boolNDArray'
     A boolean array class defined in `boolNDArray.h'

`int8NDArray'
`int16NDArray'
`int32NDArray'
`int64NDArray'
     8, 16, 32 and 64-bit signed array classes defined in
     `int8NDArray.h', `int16NDArray.h', etc.

`uint8NDArray'
`uint16NDArray'
`uint32NDArray'
`uint64NDArray'
     8, 16, 32 and 64-bit unsigned array classes defined in
     `uint8NDArray.h', `uint16NDArray.h', etc.

   There are several basic means of constructing matrices of
multi-dimensional arrays.  Considering the `Matrix' type as an example

   * We can create an empty matrix or array with the empty constructor.
     For example

          Matrix a;

     This can be used on all matrix and array types

   * Define the dimensions of the matrix or array with a dim_vector.
     For example

          dim_vector dv (2);
          dv(0) = 2; dv(1) = 2;
          Matrix a (dv);

     This can be used on all matrix and array types

   * Define the number of rows and columns in the matrix.  For example

          Matrix a (2, 2)

     However, this constructor can only be used with the matrix types.

   These types all share a number of basic methods and operators, a
selection of which include

 -- Method: T& operator () (octave_idx_type)
 -- Method: T& elem (octave_idx_type)
     The `()' operator or `elem' method allow the values of the matrix
     or array to be read or set.  These can take a single argument,
     which is of type `octave_idx_type', that is the index into the
     matrix or array.  Additionally, the matrix type allows two
     argument versions of the `()' operator and elem method, giving the
     row and column index of the value to obtain or set.

   Note that these functions do significant error checking and so in
some circumstances the user might prefer to access the data of the
array or matrix directly through the fortran_vec method discussed below.

 -- Method: octave_idx_type nelem (void) const
     The total number of elements in the matrix or array.

 -- Method: size_t byte_size (void) const
     The number of bytes used to store the matrix or array.

 -- Method: dim_vector dims (void) const
     The dimensions of the matrix or array in value of type dim_vector.

 -- Method: void resize (const dim_vector&)
     A method taking either an argument of type `dim_vector', or in the
     case of a matrix two arguments of type `octave_idx_type' defining
     the number of rows and columns in the matrix.

 -- Method: T* fortran_vec (void)
     This method returns a pointer to the underlying data of the matrix
     or a array so that it can be manipulated directly, either within
     Octave or by an external library.

   Operators such an `+', `-', or `*' can be used on the majority of
the above types.  In addition there are a number of methods that are of
interest only for matrices such as `transpose', `hermitian', `solve',
etc.

   The typical way to extract a matrix or array from the input
arguments of `DEFUN_DLD' function is as follows

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>

     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       int nargin = args.length ();
       if (nargin != 2)
         print_usage ();
       else
         {
           NDArray A = args(0).array_value ();
           NDArray B = args(1).array_value ();
           if (! error_state)
             return octave_value (A + B);
         }
       return octave_value_list ();
     }

   To avoid segmentation faults causing Octave to abort, this function
explicitly checks that there are sufficient arguments available before
accessing these arguments.  It then obtains two multi-dimensional arrays
of type `NDArray' and adds these together.  Note that the array_value
method is called without using the `is_matrix_type' type, and instead
the error_state is checked before returning `A + B'.  The reason to
prefer this is that the arguments might be a type that is not an
`NDArray', but it would make sense to convert it to one.  The
`array_value' method allows this conversion to be performed
transparently if possible, and sets `error_state' if it is not.

   `A + B', operating on two `NDArray''s returns an `NDArray', which is
cast to an `octave_value' on the return from the function.  An example
of the use of this demonstration function is

     addtwomatrices (ones (2, 2), ones (2, 2))
           =>  2  2
               2  2

   A list of the basic `Matrix' and `Array' types, the methods to
extract these from an `octave_value' and the associated header is
listed below.

`RowVector'            `row_vector_value'            `dRowVector.h'
`ComplexRowVector'     `complex_row_vector_value'    `CRowVector.h'
`ColumnVector'         `column_vector_value'         `dColVector.h'
`ComplexColumnVector'  `complex_column_vector_value' `CColVector.h'
`Matrix'               `matrix_value'                `dMatrix.h'
`ComplexMatrix'        `complex_matrix_value'        `CMatrix.h'
`boolMatrix'           `bool_matrix_value'           `boolMatrix.h'
`charMatrix'           `char_matrix_value'           `chMatrix.h'
`NDArray'              `array_value'                 `dNDArray.h'
`ComplexNDArray'       `complex_array_value'         `CNDArray.h'
`boolNDArray'          `bool_array_value'            `boolNDArray.h'
`charNDArray'          `char_array_value'            `charNDArray.h'
`int8NDArray'          `int8_array_value'            `int8NDArray.h'
`int16NDArray'         `int16_array_value'           `int16NDArray.h'
`int32NDArray'         `int32_array_value'           `int32NDArray.h'
`int64NDArray'         `int64_array_value'           `int64NDArray.h'
`uint8NDArray'         `uint8_array_value'           `uint8NDArray.h'
`uint16NDArray'        `uint16_array_value'          `uint16NDArray.h'
`uint32NDArray'        `uint32_array_value'          `uint32NDArray.h'
`uint64NDArray'        `uint64_array_value'          `uint64NDArray.h'


File: octave.info,  Node: Character Strings in Oct-Files,  Next: Cell Arrays in Oct-Files,  Prev: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.3 Character Strings in Oct-Files
------------------------------------

In Octave a character string is just a special `Array' class.  Consider
the example

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>

     DEFUN_DLD (stringdemo, args, , "String Demo")
     {
       int nargin = args.length();
       octave_value_list retval;

       if (nargin != 1)
         print_usage ();
       else
         {
           charMatrix ch = args(0).char_matrix_value ();

           if (! error_state)
             {
               if (args(0).is_sq_string ())
                 retval(1) = octave_value (ch, true);
               else
                 retval(1) = octave_value (ch, true, '\'');

               octave_idx_type nr = ch.rows();
               for (octave_idx_type i = 0; i < nr / 2; i++)
                 {
                   std::string tmp = ch.row_as_string (i);
                   ch.insert (ch.row_as_string(nr-i-1).c_str(),
     			 i, 0);
                   ch.insert (tmp.c_str(), nr-i-1, 0);
                 }
               retval(0) = octave_value (ch, true);
             }
         }
       return retval;
     }

   An example of the of the use of this function is

     s0 = ["First String"; "Second String"];
     [s1,s2] = stringdemo (s0)
     => s1 = Second String
             First String

     => s2 = First String
             Second String

     typeinfo (s2)
     => sq_string
     typeinfo (s1)
     => string

   One additional complication of strings in Octave is the difference
between single quoted and double quoted strings.  To find out if an
`octave_value' contains a single or double quoted string an example is

         if (args(0).is_sq_string ())
           octave_stdout <<
             "First argument is a singularly quoted string\n";
         else if (args(0).is_dq_string ())
           octave_stdout <<
             "First argument is a doubly quoted string\n";

   Note however, that both types of strings are represented by the
`charNDArray' type, and so when assigning to an `octave_value', the
type of string should be specified.  For example

     octave_value_list retval;
     charNDArray c;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch, true, '\'');

     // Create a double quoted string
     retval(0) = octave_value (ch, true);


File: octave.info,  Node: Cell Arrays in Oct-Files,  Next: Structures in Oct-Files,  Prev: Character Strings in Oct-Files,  Up: Oct-Files

A.1.4 Cell Arrays in Oct-Files
------------------------------

Octave's cell type is equally accessible within oct-files.  A cell
array is just an array of `octave_value's, and so each element of the
cell array can then be treated just like any other `octave_value'.  A
simple example is

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>
     #include <octave/Cell.h>

     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           Cell c = args (0).cell_value ();
           if (! error_state)
             for (octave_idx_type i = 0; i < c.nelem (); i++)
               retval(i) = c.elem (i);
         }
       return retval;
     }

   Note that cell arrays are used less often in standard oct-files and
so the `Cell.h' header file must be explicitly included.  The rest of
this example extracts the `octave_value's one by one from the cell
array and returns be as individual return arguments.  For example
consider

     [b1, b2, b3] = celldemo ({1, [1, 2], "test"})
     =>
     b1 =  1
     b2 =

        1   2

     b3 = test


File: octave.info,  Node: Structures in Oct-Files,  Next: Sparse Matrices in Oct-Files,  Prev: Cell Arrays in Oct-Files,  Up: Oct-Files

A.1.5 Structures in Oct-Files
-----------------------------

A structure in Octave is map between a number of fields represented and
their values.  The Standard Template Library `map' class is used, with
the pair consisting of a `std::string' and an octave `Cell' variable.

   A simple example demonstrating the use of structures within
oct-files is

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>
     #include <octave/ov-struct.h>

     DEFUN_DLD (structdemo, args, , "Struct demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 2)
         print_usage ();
       else
         {
           Octave_map arg0 = args(0).map_value ();
           std::string arg1 = args(1).string_value ();

           if (! error_state && arg0.contains (arg1))
             {
               // The following two lines might be written as
               //    octave_value tmp;
               //    for (Octave_map::iterator p0 =
     	  //        arg0.begin();
               //        p0 != arg0.end(); p0++ )
               //      if (arg0.key (p0) == arg1)
               //        {
               //          tmp = arg0.contents (p0) (0);
               //          break;
               //        }
               // though using seek is more concise.
               Octave_map::const_iterator p1 = arg0.seek (arg1);
               octave_value tmp =  arg0.contents(p1)(0);
               Octave_map st;
               st.assign ("selected", tmp);
               retval = octave_value (st);
             }
         }
       return retval;
     }

   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     => selected = test

   The commented code above demonstrates how to iterate over all of the
fields of the structure, where as the following code demonstrates
finding a particular field in a more concise manner.

   As can be seen the `contents' method of the `Octave_map' class
returns a `Cell' which allows structure arrays to be represented.
Therefore, to obtain the underlying `octave_value' we write

     octave_value tmp = arg0.contents (p1) (0);

   where the trailing (0) is the () operator on the `Cell' object.  We
can equally iterate of the elements of the Cell array to address the
elements of the structure array.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

`SparseMatrix'
     A double precision sparse matrix class

`SparseComplexMatrix'
     A complex sparse matrix class

`SparseBoolMatrix'
     A boolean sparse matrix class

   All of these classes inherit from the `Sparse<T>' template class,
and so all have similar capabilities and usage.  The `Sparse<T>' class
was based on Octave `Array<T>' class, and so users familiar with
Octave's `Array' classes will be comfortable with the use of the sparse
classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing `Array' classes.  However,
there are a few differences due the different nature of sparse objects,
and these will be described.  Firstly, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse
classes do not allow them at this time.  So all operations of the
sparse classes must be 2-dimensional.  This means that in fact
`SparseMatrix' is similar to Octave's `Matrix' class rather than its
`NDArray' class.

* Menu:

* Array and Sparse Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 The Differences between the Array and Sparse Classes
............................................................

The number of elements in a sparse matrix is considered to be the number
of non-zero elements rather than the product of the dimensions.
Therefore

     SparseMatrix sm;
     ...
     int nel = sm.nelem ();

   returns the number of non-zero elements.  If the user really
requires the number of elements in the matrix, including the non-zero
elements, they should use `numel' rather than `nelem'.  Note that for
very large matrices, where the product of the two dimensions is larger
than the representation of an unsigned int, then `numel' can overflow.
An example is `speye(1e6)' which will create a matrix with a million
rows and columns, but only a million non-zero elements.  Therefore the
number of rows by the number of columns in this case is more than two
hundred times the maximum value that can be represented by an unsigned
int.  The use of `numel' should therefore be avoided useless it is known
it won't overflow.

   Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function.  The reason is that if a
sparse object is non-const, then Octave will assume that a request for
a zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore a piece of code like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j)
                   << std::endl;

   is a great way of turning the sparse matrix into a dense one, and a
very slow way at that since it reallocates the sparse object at each
zero element in the matrix.

   An easy way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix.  So this is not a costly operation.  For example,
the above would become

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j)
                   << std::endl;

   Finally, as the sparse types aren't just represented as a contiguous
block of memory, the `fortran_vec' method of the `Array<T>' is not
available.  It is however replaced by three separate methods `ridx',
`cidx' and `data', that access the raw compressed column format that
the Octave sparse matrices are stored in.  Additionally, these methods
can be used in a manner similar to `elem', to allow the matrix to be
accessed or filled.  However, in that case it is up to the user to
respect the sparse matrix compressed column format discussed previous.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Differences,  Up: Sparse Matrices in Oct-Files

A.1.6.2 Creating Sparse Matrices in Oct-Files
.............................................

You have several alternatives for creating a sparse matrix.  You can
first create the data as three vectors representing the row and column
indexes and the data, and from those create the matrix.  Or
alternatively, you can create a sparse matrix with the appropriate
amount of space and then fill in the values.  Both techniques have their
advantages and disadvantages.

   Here is an example of how to create a small sparse matrix with the
first technique

     int nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 0; ridx(1) = 0; ridx(2) = 1; ridx(3) = 2;
     cidx(0) = 0; cidx(1) = 1; cidx(2) = 3; cidx(3) = 3;
     data(0) = 1; data(1) = 2; data(2) = 3; data(3) = 4;

     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *Note Storage::.  Note that
the compressed matrix format is not used at the time of the creation of
the matrix itself, however it is used internally.

   As previously mentioned, the values of the sparse matrix are stored
in increasing column-major ordering.  Although the data passed by the
user does not need to respect this requirement, the pre-sorting the
data significantly speeds up the creation of the sparse matrix.

   The disadvantage of this technique of creating a sparse matrix is
that there is a brief time where two copies of the data exists.
Therefore for extremely memory constrained problems this might not be
the right technique to create the sparse matrix.

   The alternative is to first create the sparse matrix with the desired
number of non-zero elements and then later fill those elements in.  The
easiest way to do this is

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, nz);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

   That creates the same matrix as previously.  Again, although it is
not strictly necessary, it is significantly faster if the sparse matrix
is created in this manner that the elements are added in column-major
ordering.  The reason for this is that if the elements are inserted at
the end of the current list of known elements then no element in the
matrix needs to be moved to allow the new element to be inserted.  Only
the column indexes need to be updated.

   There are a few further points to note about this technique of
creating a sparse matrix.  Firstly, it is possible to create a sparse
matrix with fewer elements than are actually inserted in the matrix.
Therefore

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, 0);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

is perfectly valid.  However it is a very bad idea.  The reason is that
as each new element is added to the sparse matrix the space allocated
to it is increased by reallocating the memory.  This is an expensive
operation, that will significantly slow this means of creating a sparse
matrix.  Furthermore, it is possible to create a sparse matrix with too
much storage, so having NZ above equaling 6 is also valid.  The
disadvantage is that the matrix occupies more memory than strictly
needed.

   It is not always easy to know the number of non-zero elements prior
to filling a matrix.  For this reason the additional storage for the
sparse matrix can be removed after its creation with the
"maybe_compress" function.  Furthermore, the maybe_compress can
deallocate the unused storage, but it can equally remove zero elements
from the matrix.  The removal of zero elements from the matrix is
controlled by setting the argument of the "maybe_compress" function to
be `true'.  However, the cost of removing the zeros is high because it
implies resorting the elements.  Therefore, if possible it is better is
the user doesn't add the zeros in the first place.  An example of the
use of "maybe_compress" is

       int nz = 6, nr = 3, nc = 4;

       SparseMatrix sm1 (nr, nc, nz);
       sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
       sm1.maybe_compress ();  // No zero elements were added

       SparseMatrix sm2 (nr, nc, nz);
       sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
       sm1(1,3) = 3; sm1(2,3) = 4;
       sm2.maybe_compress (true);  // Zero elements were added

   The use of the "maybe_compress" function should be avoided if
possible, as it will slow the creation of the matrices.

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this technique might
be

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a-priori
                            // the final no of nz.

which is probably the most efficient means of creating the sparse
matrix.

   Finally, it might sometimes arise that the amount of storage
initially created is insufficient to completely store the sparse
matrix.  Therefore, the method `change_capacity' exists to reallocate
the sparse memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_mutate ();  // If don't know a-priori
                          // the final no of nz.

   Note that both increasing and decreasing the number of non-zero
elements in a sparse matrix is expensive, as it involves memory
reallocation.  Also as parts of the matrix, though not its entirety,
exist as the old and new copy at the same time, additional memory is
needed.  Therefore if possible this should be avoided.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.3 Using Sparse Matrices in Oct-Files
..........................................

Most of the same operators and functions on sparse matrices that are
available from the Octave are equally available with oct-files.  The
basic means of extracting a sparse matrix from an `octave_value' and
returning them as an `octave_value', can be seen in the following
example

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm =
         args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an octave-value is handled by the sparse
`octave_value' constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can easily be accessed with oct-files using the
support functions `get_global_value' and `set_global_value'.
`get_global_value' takes two arguments, the first is a string
representing the variable name to obtain.  The second argument is a
boolean argument specifying what to do in the case that no global
variable of the desired name is found.  An example of the use of these
two functions is

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>

     DEFUN_DLD (globaldemo, args, , "Global demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage ();
       else
         {
           std::string s = args(0).string_value ();
           if (! error_state)
             {
               octave_value tmp = get_global_value (s, true);
               if (tmp.is_defined ())
                 retval = tmp;
               else
                 retval = "Global variable not found";

               set_global_value ("a", 42.0);
             }
         }
       return retval;
     }

   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     => 10
     globaldemo ("c")
     => "Global variable not found"
     num2str (a)
     => 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another octave function from
within an oct-file, and there are many examples of such within octave
itself.  For example the `quad' function is an oct-file that calculates
the definite integral by quadrature over a user supplied function.

   There are also many ways in which a function might be passed.  It
might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. Inline Function

  4. String

   The example below demonstrates an example that accepts all four
means of passing a function to an oct-file.

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>
     #include <octave/parse.h>

     DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
     {
       int nargin = args.length();
       octave_value_list retval;

       if (nargin < 2)
         print_usage ();
       else
         {
           octave_value_list newargs;
           for (octave_idx_type i = nargin - 1; i > 0; i--)
             newargs (i - 1) = args(i);
           if (args(0).is_function_handle ()
               || args(0).is_inline_function ())
             {
               octave_function *fcn = args(0).function_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else if (args(0).is_string ())
             {
               std::string fcn = args (0).string_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else
             error ("funcdemo: expected string,",
     	       " inline or function handle");
         }
       return retval;
     }

   The first argument to this demonstration is the user supplied
function and the following arguments are all passed to the user
function.

     funcdemo (@sin,1)
     => 0.84147
     funcdemo (@(x) sin(x), 1)
     => 0.84147
     funcdemo (inline ("sin(x)"), 1)
     => 0.84147
     funcdemo ("sin",1)
     => 0.84147
     funcdemo (@atan2, 1, 1)
     => 0.78540

   When the user function is passed as a string, the treatment of the
function is different.  In some cases it is necessary to always have the
user supplied function as an `octave_function' object.  In that case
the string argument can be used to create a temporary function like

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fname = "function y = ";
     fname.append (fcn_name);
     fname.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fname, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  The number of
input arguments to the user function is fixed, and in the above is a
single argument, and secondly to avoid leaving the temporary function
in the Octave symbol table it should be cleared after use.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
the declarations of the external C functions might need to be explicitly
defined as C functions to the compiler.  If the declarations of the
external C functions are in the header `foo.h', then the manner in
which to ensure that the C++ compiler treats these declarations as C
code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code however can pose some difficulties.  This is
due to differences in the manner in compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies a number of macros
that allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the `XSTOPX' function to
replace the Fortran `STOP' function.  `XSTOPX' uses the Octave
exception handler to treat failing cases in the fortran code
explicitly.  Note that Octave supplies its own replacement blas
`XERBLA' function, which uses `XSTOPX'.

   If the underlying code calls `XSTOPX', then the `F77_XFCN' macro
should be used to call the underlying fortran function.  The Fortran
exception state can then be checked with the global variable
`f77_exception_encountered'.  If `XSTOPX' will not be called, then the
`F77_FCN' macro should be used instead to call the Fortran code.

   There is no harm in using `F77_XFCN' in all cases, except that for
Fortran code that is short running and executes a large number of times,
there is potentially an overhead in doing so.  However, if `F77_FCN' is
used with code that calls `XSTOP', Octave can generate a segmentation
fault.

   An example of the inclusion of a Fortran function in an oct-file is
given in the following example, where the C++ wrapper is

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortsub, FORTSUB)
             (const int&, double*, F77_CHAR_ARG_DECL
              F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortdemo , args , , "Fortran Demo.")
     {
       octave_value_list retval;
       int nargin = args.length();
       if (nargin != 1)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           if (! error_state)
             {
               double *av = a.fortran_vec ();
               octave_idx_type na = a.nelem ();
               OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

               F77_XFCN (fortsub, FORTSUB, (na, av, ctmp
                         F77_CHAR_ARG_LEN (128)));

               if (f77_exception_encountered)
                 error ("fortdemo: error in fortran");
               else
                 {
                   retval(1) = std::string (ctmp);
                   retval(0) = a;
                 }
             }
         }
       return retval;
     }

and the fortran function is

     c Copyright (C) 2007 John W. Eaton
     c
     c This file is part of Octave.
     c
     c Octave is free software; you can redistribute it and/or
     c modify it under the terms of the GNU General Public
     c License as published by the Free Software Foundation;
     c either version 3 of the License, or (at your option) any
     c later version.
     c
     c Octave is distributed in the hope that it will be useful,
     c but WITHOUT ANY WARRANTY; without even the implied
     c warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     c PURPOSE. See the GNU General Public License for more
     c details.
     c
     c You should have received a copy of the GNU General Public
     c License along with Octave; see the file COPYING.  If not,
     c see <http://www.gnu.org/licenses/>.

           subroutine fortsub (n, a, s)
           implicit none
           character*(*) s
           real*8 a(*)
           integer*4 i, n, ioerr
           do i = 1, n
             if (a(i) .eq. 0d0) then
               call xstopx ('fortsub: divide by zero')
             else
               a(i) = 1d0 / a(i)
             endif
           enddo
           write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
          $       'There are ', n,
          $       ' values in the input vector', char(0)
           if (ioerr .ne. 0) then
             call xstopx ('fortsub: error writing string')
           endif
           return
           end

   This example demonstrates most of the features needed to link to an
external Fortran function, including passing arrays and strings, as well
as exception handling.  An example of the behavior of this function is

     [b, s] = fortdemo (1:3)
     =>
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortdemo(0:3)
     error: fortsub:divide by zero
     error: exception encountered in Fortran subroutine fortsub_
     error: fortdemo: error in fortran


File: octave.info,  Node: Allocating Local Memory in Oct-Files,  Next: Input Parameter Checking in Oct-Files,  Prev: Calling External Code from Oct-Files,  Up: Oct-Files

A.1.10 Allocating Local Memory in Oct-Files
-------------------------------------------

Allocating memory within an oct-file might seem easy as the C++
new/delete operators can be used.  However, in that case care must be
taken to avoid memory leaks.  The preferred manner in which to allocate
memory for use locally is to use the `OCTAVE_LOCAL_BUFFER' macro.  An
example of its use is

     OCTAVE_LOCAL_BUFFER (double, tmp, len)

   that returns a pointer `tmp' of type `double *' of length `len'.


File: octave.info,  Node: Input Parameter Checking in Oct-Files,  Next: Exception and Error Handling in Oct-Files,  Prev: Allocating Local Memory in Oct-Files,  Up: Oct-Files

A.1.11 Input Parameter Checking in Oct-Files
--------------------------------------------

As oct-files are compiled functions they have the possibility of causing
Octave to abort abnormally.  It is therefore important that each and
every function has the minimum of parameter checking needed to ensure
that Octave behaves well.

   The minimum requirement, as previously discussed, is to check the
number of input arguments before using them to avoid referencing a non
existent argument.  However, it some case this might not be sufficient
as the underlying code imposes further constraints.  For example an
external function call might be undefined if the input arguments are not
integers, or if one of the arguments is zero.  Therefore, oct-files
often need additional input parameter checking.

   There are several functions within Octave that might be useful for
the purposes of parameter checking.  These include the methods of the
octave_value class like `is_real_matrix', etc, but equally include more
specialized functions.  Some of the more common ones are demonstrated
in the following example

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>

     DEFUN_DLD (paramdemo, args, nargout,
     	   "Parameter Check Demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage();
       else if (nargout != 0)
         error ("paramdemo: function has no output arguments");
       else
         {
           NDArray m = args(0).array_value();
           double min_val = -10.0;
           double max_val = 10.0;
           octave_stdout << "Properties of input array:\n";
           if (m.any_element_is_negative ())
             octave_stdout << "  includes negative values\n";
           if (m.any_element_is_inf_or_nan())
             octave_stdout << "  includes Inf or NaN values\n";
           if (m.any_element_not_one_or_zero())
             octave_stdout <<
     	  "  includes other values than 1 and 0\n";
           if (m.all_elements_are_int_or_inf_or_nan())
             octave_stdout <<
     	  "  includes only int, Inf or NaN values\n";
           if (m.all_integers (min_val, max_val))
             octave_stdout <<
     	  "  includes only integers in [-10,10]\n";
         }
       return retval;
     }

and an example of its use is

     paramdemo ([1, 2, NaN, Inf])
     => Properties of input array:
           includes Inf or NaN values
           includes other values than 1 and 0
           includes only int, Inf or NaN values


File: octave.info,  Node: Exception and Error Handling in Oct-Files,  Next: Documentation and Test of Oct-Files,  Prev: Input Parameter Checking in Oct-Files,  Up: Oct-Files

A.1.12 Exception and Error Handling in Oct-Files
------------------------------------------------

Another important feature of Octave is its ability to react to the user
typing `Control-C' even during calculations.  This ability is based on
the C++ exception handler, where memory allocated by the C++ new/delete
methods are automatically released when the exception is treated.  When
writing an oct-file, to allow Octave to treat the user typing
`Control-C', the `OCTAVE_QUIT' macro is supplied.  For example

     for (octave_idx_type i = 0; i < a.nelem (); i++)
       {
         OCTAVE_QUIT;
         b.elem(i) = 2. * a.elem(i);
       }

   The presence of the `OCTAVE_QUIT' macro in the inner loop allows
Octave to treat the user request with the `Control-C'.  Without this
macro, the user must either wait for the function to return before the
interrupt is processed, or press `Control-C' three times to force
Octave to exit.

   The `OCTAVE_QUIT' macro does impose a very small speed penalty, and
so for loops that are known to be small it might not make sense to
include `OCTAVE_QUIT'.

   When creating an oct-file that uses an external libraries, the
function might spend a significant portion of its time in the external
library.  It is not generally possible to use the `OCTAVE_QUIT' macro in
this case.  The alternative in this case is

     BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
     ...  some code that calls a "foreign" function ...
     END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;

   The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated.  Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
fortran_vec method or the `OCTAVE_LOCAL_BUFFER' macro.

   The Octave unwind_protect mechanism (*Note The unwind_protect
Statement::) can also be used in oct-files.  In conjunction with the
exception handling of Octave, it is important to enforce that certain
code is run to allow variables, etc to be restored even if an exception
occurs.  An example of the use of this mechanism is

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <octave/oct.h>
     #include <octave/unwind-prot.h>

     void
     err_hand (const char *fmt, ...)
     {
       // Do nothing!!
     }

     DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
     {
       int nargin = args.length();
       octave_value retval;
       if (nargin < 2)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           NDArray b = args(1).array_value ();

           if (! error_state)
             {
               unwind_protect::begin_frame ("Funwinddemo");
               unwind_protect_ptr
     	    (current_liboctave_warning_handler);
               set_liboctave_warning_handler(err_hand);
               retval = octave_value (quotient (a, b));
               unwind_protect::run_frame ("Funwinddemo");
             }
         }
       return retval;
     }

   As can be seen in the example

     unwinddemo (1, 0)
     => Inf
     1 / 0
     => warning: division by zero
        Inf

   The division by zero (and in fact all warnings) is disabled in the
`unwinddemo' function.


File: octave.info,  Node: Documentation and Test of Oct-Files,  Prev: Exception and Error Handling in Oct-Files,  Up: Oct-Files

A.1.13 Documentation and Test of Oct-Files
------------------------------------------

The documentation of an oct-file is the fourth string parameter of the
`DEFUN_DLD' macro.  This string can be formatted in the same manner as
the help strings for user functions (*Note Documentation Tips::),
however there are some issue that are particular to the formatting of
help strings within oct-files.

   The major issue is that the help string will typically be longer
than a single line of text, and so the formatting of long help strings
need to be taken into account.  There are several manners in which to
treat this issue, but the most common is illustrated in the following
example

     DEFUN_DLD (do_what_i_want, args, nargout,
       "-*- texinfo -*-\n\
     @deftypefn {Function File} {} do_what_i_say (@var{n})\n\
     A function that does what the user actually wants rather\n\
     than what they requested.\n\
     @end deftypefn")
     {
     ...
     }

where, as can be seen, end line of text within the help string is
terminated by `\n\' which is an an embedded new-line in the string
together with a C++ string continuation character.  Note that the final
`\' must be the last character on the line.

   Octave also includes the ability to embed the test and demonstration
code for a function within the code itself (*Note Test and Demo
Functions::).  This can be used from within oct-files (or in fact any
file) with certain provisos.  Firstly, the test and demo functions of
Octave look for a `%!' as the first characters on a new-line to
identify test and demonstration code.  This is equally a requirement for
oct-files.  Furthermore the test and demonstration code must be included
in a comment block of the compiled code to avoid it being interpreted by
the compiler.  Finally, the Octave test and demonstration code must have
access to the source code of the oct-file and not just the compiled code
as the tests are stripped from the compiled code.  An example in an
oct-file might be

     /*

     %!error (sin())
     %!error (sin(1,1))
     %!assert (sin([1,2]),[sin(1),sin(2)])

     */


File: octave.info,  Node: Mex-Files,  Next: Standalone Programs,  Prev: Oct-Files,  Up: Dynamically Linked Functions

A.2 Mex-Files
=============

Octave includes an interface to allow legacy mex-files to be compiled
and used with Octave.  This interface can also be used to share code
between Octave and non Octave users.  However, as mex-files expose the
internal API of an alternative product to Octave, and the internal
structure of Octave is different to this product, a mex-file can never
have the same performance in Octave as the equivalent oct-file.  In
particular to support the manner in which mex-files access the variables
passed to mex functions, there are a significant number of additional
copies of memory when calling or returning from a mex function.  For
this reason, new code should be written using the oct-file interface
discussed above if possible.

* Menu:

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::


File: octave.info,  Node: Getting Started with Mex-Files,  Next: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.1 Getting Started with Mex-Files
------------------------------------

The basic command to build a mex-file is either `mkoctfile --mex' or
`mex'.  The first can either be used from within Octave or from the
commandline.  However, to avoid issues with the installation of other
products, the use of the command `mex' is limited to within Octave.

 -- Function File:  mex [options] file ...
     Compile source code written in C, C++, or Fortran, to a MEX file.
     This is equivalent to `mkoctfile --mex [options] file'.

     *See also:* mkoctfile.

 -- Function File:  mexext ()
     Return the filename extension used for MEX files.

   One important difference between the use of mex with other products
and with Octave is that the header file "matrix.h" is implicitly
included through the inclusion of "mex.h".  This is to avoid a conflict
with the Octave file "Matrix.h" with operating systems and compilers
that don't distinguish between filenames in upper and lower case

   Consider the short example

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mxArray *v = mxCreateDoubleMatrix (1, 1, mxREAL);
       double *data = mxGetPr (v);
       *data = 1.23456789;
       plhs[0] = v;
     }

   This simple example demonstrates the basics of writing a mex-file.
The entry point into the mex-file is defined by `mexFunction'.  Note
that the function name is not explicitly included in the `mexFunction'
and so there can only be a single `mexFunction' entry point per-file.
Also the name of the function is determined by the name of the mex-file
itself.  Therefore if the above function is in the file
`firstmexdemo.c', it can be compiled with

     mkoctfile --mex firstmexdemo.c

which creates a file `firstmexdemo.mex'.  The function can then be run
from Octave as

     firstmexdemo()
     => 1.2346

   It should be noted that the mex-file contains no help string for the
functions it contains.  To document mex-files, there should exist an
m-file in the same directory as the mex-file itself.  Taking the above
as an example, we would therefore have a file `firstmexdemo.m' that
might contain the text

     %FIRSTMEXDEMO Simple test of the functionality of a mex-file.

   In this case, the function that will be executed within Octave will
be given by the mex-file, while the help string will come from the
m-file.  This can also be useful to allow a sample implementation of the
mex-file within the Octave language itself for testing purposes.

   Although we can not have multiple entry points into a single
mex-file, we can use the `mexFunctionName' function to determine what
name the mex-file was called with.  This can be used to alter the
behavior of the mex-file based on the function name.  For example if

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       const char *nm;
       nm = mexFunctionName ();
       mexPrintf ("You called function: %s\n", nm);
       if (strcmp (nm, "myfunc") == 0)
         mexPrintf ("This is the principal function\n", nm);
       return;
     }

is in file `myfunc.c', and it is compiled with

     mkoctfile --mex myfunc.c
     ln -s myfunc.mex myfunc2.mex

   Then as can be seen by

     myfunc()
     => You called function: myfunc
         This is the principal function
     myfunc2()
     => You called function: myfunc2

the behavior of the mex-file can be altered depending on the functions
name.

   Allow the user should only include `mex.h' in their code, Octave
declares additional functions, typedefs, etc, available to the user to
write mex-files in the headers `mexproto.h' and `mxarray.h'.


File: octave.info,  Node: Working with Matrices and Arrays in Mex-Files,  Next: Character Strings in Mex-Files,  Prev: Getting Started with Mex-Files,  Up: Mex-Files

A.2.2 Working with Matrices and Arrays in Mex-Files
---------------------------------------------------

The basic mex type of all variables is `mxArray'.  All variables, such
as matrices, cell arrays or structures are all stored in this basic
type, and this type serves basically the same purpose as the
octave_value class in oct-files.  That is it acts as a container for the
more specialized types.

   The `mxArray' structure contains at a minimum, the variable it
represents name, its dimensions, its type and whether the variable is
real or complex.  It can however contain a number of additional fields
depending on the type of the `mxArray'.  There are a number of
functions to create `mxArray' structures, including
`mxCreateCellArray', `mxCreateSparse' and the generic
`mxCreateNumericArray'.

   The basic functions to access the data contained in an array is
`mxGetPr'.  As the mex interface assumes that the real and imaginary
parts of a complex array are stored separately, there is an equivalent
function `mxGetPi' that get the imaginary part.  Both of these
functions are for use only with double precision matrices.  There also
exists the generic function `mxGetData' and `mxGetImagData' that
perform the same operation on all matrix types.  For example

     mxArray *m;
     mwSize *dims;
     UINT32_T *pr;

     dims = (mwSize *) mxMalloc (2 * sizeof(mwSize));
     dims[0] = 2;
     dims[1] = 2;
     m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
     pr =  = (UINT32_T *) mxGetData (m);

   There are also the functions `mxSetPr', etc, that perform the
inverse, and set the data of an Array to use the block of memory pointed
to by the argument of `mxSetPr'.

   Note the type `mwSize' used above, and `mwIndex' are defined as the
native precision of the indexing in Octave on the platform on which the
mex-file is built. This allows both 32- and 64-bit platforms to support
mex-files. `mwSize' is used to define array dimension and maximum
number or elements, while `mwIndex' is used to define indexing into
arrays.

   An example that demonstration how to work with arbitrary real or
complex double precision arrays is given by the file `mypow2.c' as given
below.

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       mwIndex i;
       mwSize n;
       double *vri, *vro;

       if (nrhs != 1 || ! mxIsNumeric (prhs[0]))
         mexErrMsgTxt ("expects matrix");

       n = mxGetNumberOfElements (prhs[0]);
       plhs[0] = (mxArray *) mxCreateNumericArray
         (mxGetNumberOfDimensions (prhs[0]),
          mxGetDimensions (prhs[0]), mxGetClassID (prhs[0]),
          mxIsComplex (prhs[0]));
       vri = mxGetPr (prhs[0]);
       vro = mxGetPr (plhs[0]);

       if (mxIsComplex (prhs[0]))
         {
           double *vii, *vio;
           vii = mxGetPi (prhs[0]);
           vio = mxGetPi (plhs[0]);

           for (i = 0; i < n; i++)
     	{
     	  vro [i] = vri [i] * vri [i] - vii [i] * vii [i];
     	  vio [i] = 2 * vri [i] * vii [i];
     	}
         }
       else
         {
           for (i = 0; i < n; i++)
     	vro [i] = vri [i] * vri [i];
         }
     }

with an example of its use

     b = randn(4,1) + 1i * randn(4,1);
     all(b.^2 == mypow2(b))
     => 1

   The example above uses the functions `mxGetDimensions',
`mxGetNumberOfElements', and `mxGetNumberOfDimensions' to work with the
dimensions of multi-dimensional arrays.  The functions `mxGetM', and
`mxGetN' are also available to find the number of rows and columns in a
matrix.


File: octave.info,  Node: Character Strings in Mex-Files,  Next: Cell Arrays with Mex-Files,  Prev: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.3 Character Strings in Mex-Files
------------------------------------

As mex-files do not make the distinction between single and double
quoted strings within Octave, there is perhaps less complexity in the
use of strings and character matrices in mex-files.  An example of their
use, that parallels the demo in `stringdemo.cc', is given in the file
`mystring.c', as seen below.

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include <string.h>
     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mwIndex i, j;
       mwSize m, n;
       mxChar *pi, *po;

       if (nrhs != 1 || ! mxIsChar (prhs[0]) ||
           mxGetNumberOfDimensions (prhs[0]) > 2)
         mexErrMsgTxt ("expecting char matrix");

       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       pi = mxGetChars (prhs[0]);
       plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS,
     				   mxREAL);
       po = mxGetChars (plhs[0]);

       for (j = 0; j < n; j++)
         for (i = 0; i < m; i++)
           po [j*m + m - 1 - i] = pi [j*m + i];
     }

An example of its expected output is

     mystring(["First String"; "Second String"])
     => s1 = Second String
             First String

   Other functions in the mex interface for handling character strings
are `mxCreateString', `mxArrayToString', and
`mxCreateCharMatrixFromStrings'.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an
arbitrary distinction as the data in the mxArray for the matrix is
consecutive in any case.


File: octave.info,  Node: Cell Arrays with Mex-Files,  Next: Structures with Mex-Files,  Prev: Character Strings in Mex-Files,  Up: Mex-Files

A.2.4 Cell Arrays with Mex-Files
--------------------------------

We can perform exactly the same operations in Cell arrays in mex-files
as we can in oct-files.  An example that reduplicates the functional of
the `celldemo.cc' oct-file in a mex-file is given by `mycell.c' as below

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       mwSize n;
       mwIndex i;

       if (nrhs != 1 || ! mxIsCell (prhs[0]))
         mexErrMsgTxt ("expects cell");

       n = mxGetNumberOfElements (prhs[0]);
       n = (n > nlhs ? nlhs : n);

       for (i = 0; i < n; i++)
         plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
     }

which as can be seen below has exactly the same behavior as the oct-file
version.

     [b1, b2, b3] = mycell ({1, [1, 2], "test"})
     =>
     b1 =  1
     b2 =

        1   2

     b3 = test

   Note in the example the use of the `mxDuplicateArry' function.  This
is needed as the `mxArray' pointer returned by `mxGetCell' might be
deallocated.  The inverse function to `mxGetCell' is `mcSetCell' and is
defined as

     void mxSetCell (mxArray *ptr, int idx, mxArray *val);

   Finally, to create a cell array or matrix, the appropriate functions
are

     mxArray *mxCreateCellArray (int ndims, const int *dims);
     mxArray *mxCreateCellMatrix (int m, int n);


File: octave.info,  Node: Structures with Mex-Files,  Next: Sparse Matrices with Mex-Files,  Prev: Cell Arrays with Mex-Files,  Up: Mex-Files

A.2.5 Structures with Mex-Files
-------------------------------

The basic function to create a structure in a mex-file is
`mxCreateStructMatrix', which creates a structure array with a two
dimensional matrix, or `mxCreateStructArray'.

     mxArray *mxCreateStructArray (int ndims, int *dims,
                                   int num_keys,
                                   const char **keys);
     mxArray *mxCreateStructMatrix (int rows, int cols,
                                    int num_keys,
                                    const char **keys);

   Accessing the fields of the structure can then be performed with the
`mxGetField' and `mxSetField' or alternatively with the
`mxGetFieldByNumber' and `mxSetFieldByNumber' functions.

     mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                          const char *key);
     mxArray *mxGetFieldByNumber (const mxArray *ptr,
                                  mwIndex index, int key_num);
     void mxSetField (mxArray *ptr, mwIndex index,
                      const char *key, mxArray *val);
     void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                              int key_num, mxArray *val);

   A difference between the oct-file interface to structures and the
mex-file version is that the functions to operate on structures in
mex-files directly include an `index' over the elements of the arrays
of elements per `field'.  Whereas the oct-file structure includes a
Cell Array per field of the structure.

   An example that demonstrates the use of structures in mex-file can be
found in the file `mystruct.c', as seen below

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       int i;
       mwIndex j;
       mxArray *v;
       const char *keys[] = { "this", "that" };

       if (nrhs != 1 || ! mxIsStruct (prhs[0]))
         mexErrMsgTxt ("expects struct");

       for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
         for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
           {
             mexPrintf ("field %s(%d) = ",
                        mxGetFieldNameByNumber (prhs[0], i), j);
             v = mxGetFieldByNumber (prhs[0], j, i);
             mexCallMATLAB (0, 0, 1, &v, "disp");
           }

       v = mxCreateStructMatrix (2, 2, 2, keys);

       mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
       mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
       mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
       mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
       mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
       mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
       mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
       mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));

       if (nlhs)
         plhs[0] = v;
     }

   An example of the behavior of this function within Octave is then

     a(1).f1 = "f11"; a(1).f2 = "f12";
     a(2).f1 = "f21"; a(2).f2 = "f22";
     b = mystruct(a)
     => field f1(0) = f11
         field f1(1) = f21
         field f2(0) = f12
         field f2(1) = f22
         b =
         {
           this =

           (,
             [1] = this1
             [2] = this2
             [3] = this3
             [4] = this4
           ,)

           that =

           (,
             [1] = that1
             [2] = that2
             [3] = that3
             [4] = that4
           ,)

         }


File: octave.info,  Node: Sparse Matrices with Mex-Files,  Next: Calling Other Functions in Mex-Files,  Prev: Structures with Mex-Files,  Up: Mex-Files

A.2.6 Sparse Matrices with Mex-Files
------------------------------------

The Octave format for sparse matrices is identical to the mex format in
that it is a compressed column sparse format.  Also in both, sparse
matrices are required to be two dimensional.  The only difference is
that the real and imaginary parts of the matrix are stored separately.

   The mex-file interface, as well as using `mxGetM', `mxGetN',
`mxSetM', `mxSetN', `mxGetPr', `mxGetPi', `mxSetPr' and `mxSetPi', the
mex-file interface supplies the functions

     mwIndex *mxGetIr (const mxArray *ptr);
     mwIndex *mxGetJc (const mxArray *ptr);
     mwSize mxGetNzmax (const mxArray *ptr);

     void mxSetIr (mxArray *ptr, mwIndex *ir);
     void mxSetJc (mxArray *ptr, mwIndex *jc);
     void mxSetNzmax (mxArray *ptr, mwSize nzmax);

`mxGetNzmax' gets the maximum number of elements that can be stored in
the sparse matrix.  This is not necessarily the number of non-zero
elements in the sparse matrix.  `mxGetJc' returns an array with one
additional value than the number of columns in the sparse matrix.  The
difference between consecutive values of the array returned by
`mxGetJc' define the number of non-zero elements in each column of the
sparse matrix.  Therefore

     mwSize nz, n;
     mwIndex *Jc;
     mxArray *m;
     ...
     n = mxGetN (m);
     Jc = mxGetJc (m);
     nz = Jc[n];

returns the actual number of non-zero elements stored in the matrix in
`nz'.  As the arrays returned by `mxGetPr' and `mxGetPi' only contain
the non-zero values of the matrix, we also need a pointer to the rows
of the non-zero elements, and this is given by `mxGetIr'.  A complete
example of the use of sparse matrices in mex-files is given by the file
`mysparse.c' as seen below

     /*

     Copyright (C) 2006, 2007 David Bateman

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mwSize n, m, nz;
       mxArray *v;
       mwIndex i;
       double *pr, *pi;
       double *pr2, *pi2;
       mwIndex *ir, *jc;
       mwIndex *ir2, *jc2;

       if (nrhs != 1 || ! mxIsSparse (prhs[0]))
         mexErrMsgTxt ("expects sparse matrix");

       m = mxGetM (prhs [0]);
       n = mxGetN (prhs [0]);
       nz = mxGetNzmax (prhs [0]);

       if (mxIsComplex (prhs[0]))
         {
           mexPrintf ("Matrix is %d-by-%d complex",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           pi = mxGetPi (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) =",
     		 ir[nz-1]+ 1, i);
           mexPrintf (" (%g, %g)\n", pr[nz-1], pi[nz-1]);

           v = mxCreateSparse (m, n, nz, mxCOMPLEX);
           pr2 = mxGetPr (v);
           pi2 = mxGetPi (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               pi2[i] = 2 * pi[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else if (mxIsLogical (prhs[0]))
         {
           bool *pbr, *pbr2;
           mexPrintf ("Matrix is %d-by-%d logical",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pbr = mxGetLogicals (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) = %d\n",
                      ir[nz-1]+ 1, i, pbr[nz-1]);

           v = mxCreateSparseLogicalMatrix (m, n, nz);
           pbr2 = mxGetLogicals (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pbr2[i] = pbr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else
         {
           mexPrintf ("Matrix is %d-by-%d real",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) = %g\n",
                     ir[nz-1]+ 1, i, pr[nz-1]);

           v = mxCreateSparse (m, n, nz, mxREAL);
           pr2 = mxGetPr (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
     }


File: octave.info,  Node: Calling Other Functions in Mex-Files,  Prev: Sparse Matrices with Mex-Files,  Up: Mex-Files

A.2.7 Calling Other Functions in Mex-Files
------------------------------------------

It is also possible call other Octave functions from within a mex-file
using `mexCallMATLAB'.  An example of the use of `mexCallMATLAB' can be
see in the example below

     /*

     Copyright (C) 2006, 2007 John W. Eaton

     This file is part of Octave.

     Octave is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     as published by the Free Software Foundation; either
     version 3  of the License, or (at your option) any later
     version.

     Octave is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty
     of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     See the GNU General Public License for more details.

     You should have received a copy of the GNU General Public
     License along with Octave; see the file COPYING.  If not,
     see <http://www.gnu.org/licenses/>.

     */

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       char *str;

       mexPrintf ("Hello, World!\n");

       mexPrintf ("I have %d inputs and %d outputs\n", nrhs,
     	     nlhs);

       if (nrhs < 1 || ! mxIsString (prhs[0]))
         mexErrMsgTxt ("function name expected");

       str = mxArrayToString (prhs[0]);

       mexPrintf ("I'm going to call the function %s\n", str);

       mexCallMATLAB (nlhs, plhs, nrhs-1, prhs+1, str);

       mxFree (str);
     }

   If this code is in the file `myfeval.c', and is compiled to
`myfeval.mex', then an example of its use is

     myfeval("sin", 1)
     a = myfeval("sin", 1)
     => Hello, World!
         I have 2 inputs and 1 outputs
         I'm going to call the interpreter function sin
         a =  0.84147

   Note that it is not possible to use function handles or inline
functions within a mex-file.


File: octave.info,  Node: Standalone Programs,  Prev: Mex-Files,  Up: Dynamically Linked Functions

A.3 Standalone Programs
=======================

The libraries Octave itself uses, can be utilized in standalone
applications.  These applications then have access, for example, to the
array and matrix classes as well as to all the Octave algorithms.  The
following C++ program, uses class Matrix from liboctave.a or
liboctave.so.

     #include <iostream>
     #include <octave/oct.h>
     int
     main (void)
     {
       std::cout << "Hello Octave world!\n";
       int n = 2;
       Matrix a_matrix = Matrix (n, n);
       for (octave_idx_type i = 0; i < n; i++)
         {
           for (octave_idx_type j = 0; j < n; j++)
             {
               a_matrix (i, j) = (i + 1) * 10 + (j + 1);
             }
         }
       std::cout << a_matrix;
       return 0;
     }

mkoctfile can then be used to build a standalone application with a
command like

     $ mkoctfile --link-stand-alone standalone.cc -o standalone
     $ ./standalone
     Hello Octave world!
       11 12
       21 22
     $

   Note that the application `hello' will be dynamically linked against
the octave libraries and any octave support libraries. The above allows
the Octave math libraries to be used by an application. It does not
however allow the script files, oct-files or builtin functions of
Octave to be used by the application. To do that the Octave interpreter
needs to be initialized first. An example of how to do this can then be
seen in the code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/octave.h>
     #include <octave/parse.h>
     int
     main (void)
     {
       string_vector argv (2);
       argv(0) = "embedded";
       argv(1) = "-q";

       octave_main (2, argv.c_str_vec(), 1);

       octave_idx_type n = 2;
       Matrix a_matrix = Matrix (1, 2);

       std::cout << "GCD of [";
       for (octave_idx_type i = 0; i < n; i++)
         {
           a_matrix (i) = 5 * (i + 1);
           if (i != 0)
     	std::cout << ", " << 5 * (i + 2);
           else
     	std::cout << 5 * (i + 2);
         }
       std::cout << "] is ";

       octave_value_list in = octave_value (a_matrix);
       octave_value_list out = feval ("gcd", in, 1);

       if (!error_state && out.length () > 0)
         {
           a_matrix = out(0).matrix_value ();
           if (a_matrix.numel () == 1)
     	std::cout << a_matrix(0) << "\n";
           else
     	std::cout << "invalid\n";
         }
       else
         std::cout << "invalid\n";

       return 0;
     }

which is compiled and run as before as a standalone application with

     $ mkoctfile --link-stand-alone embedded.cc -o embedded
     $ ./embedded
     GCD of [10, 15] is 5
     $


File: octave.info,  Node: Test and Demo Functions,  Next: Tips,  Prev: Dynamically Linked Functions,  Up: Top

Appendix B Test and Demo Functions
**********************************

Octave includes a number of functions to allow the integration of
testing and demonstration code in the source code of the functions
themselves.

* Menu:

* Test Functions::
* Demonstration Functions::


File: octave.info,  Node: Test Functions,  Next: Demonstration Functions,  Up: Test and Demo Functions

B.1 Test Functions
==================

 -- Function File:  test NAME
 -- Function File:  test NAME quiet|normal|verbose
 -- Function File:  test ('NAME', 'quiet|normal|verbose', FID)
 -- Function File:  test ([], 'explain', FID)
 -- Function File: SUCCESS = test (...)
 -- Function File: [N, MAX] = test (...)
 -- Function File: [CODE, IDX] = test ('NAME','grabdemo')
     Perform tests from the first file in the loadpath matching NAME.
     `test' can be called as a command or as a function. Called with a
     single argument NAME, the tests are run interactively and stop
     after the first error is encountered.

     With a second argument the tests which are performed and the
     amount of output is selected.

    'quiet'
          Don't report all the tests as they happen, just the errors.

    'normal'
          Report all tests as they happen, but don't do tests which
          require user interaction.

    'verbose'
          Do tests which require user interaction.

     The argument FID can be used to allow batch processing. Errors can
     be written to the already open file defined by FID, and hopefully
     when octave crashes this file will tell you what was happening
     when it did. You can use `stdout' if you want to see the results as
     they happen.  You can also give a file name rather than an FID, in
     which case the contents of the file will be replaced with the log
     from the current test.

     Called with a single output argument SUCCESS, `test' returns true
     if all of the tests were successful. Called with two output
     arguments N and MAX, the number of successful tests and the total
     number of tests in the file NAME are returned.

     If the second argument is the string 'grabdemo', the contents of
     the demo blocks are extracted but not executed. Code for all code
     blocks is concatenated and returned as CODE with IDX being a
     vector of positions of the ends of the demo blocks.

     If the second argument is 'explain', then NAME is ignored and an
     explanation of the line markers used is written to the file FID.

     *See also:* error, assert, fail, demo, example.

   `test' scans the named script file looking for lines which start
with `%!'. The prefix is stripped off and the rest of the line is
processed through the octave interpreter. If the code generates an
error, then the test is said to fail.

   Since `eval()' will stop at the first error it encounters, you must
divide your tests up into blocks, with anything in a separate block
evaluated separately.  Blocks are introduced by the keyword `test'
immediately following the `%!'.  For example,

        %!test error ("this test fails!");
        %!test "test doesn't fail. it doesn't generate an error";

   When a test fails, you will see something like:

          ***** test error ('this test fails!')
        !!!!! test failed
        this test fails!

   Generally, to test if something works, you want to assert that it
produces a correct value.  A real test might look something like

        %!test
        %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
        %! expect = [ A ; 2*A ];
        %! get = kron (B, A);
        %! if (any(size(expect) != size(get)))
        %!    error ("wrong size: expected %d,%d but got %d,%d",
        %!           size(expect), size(get));
        %! elseif (any(any(expect!=get)))
        %!    error ("didn't get what was expected.");
        %! endif

   To make the process easier, use the `assert' function.  For example,
with `assert' the previous test is reduced to:

        %!test
        %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
        %! assert (kron (B, A), [ A; 2*A ]);

   `assert' can accept a tolerance so that you can compare results
absolutely or relatively. For example, the following all succeed:

        %!test assert (1+eps, 1, 2*eps)          # absolute error
        %!test assert (100+100*eps, 100, -2*eps) # relative error

   You can also do the comparison yourself, but still have assert
generate the error:

        %!test assert (isempty([]))
        %!test assert ([ 1,2; 3,4 ] > 0)

   Because `assert' is so frequently used alone in a test block, there
is a shorthand form:

        %!assert (...)

   which is equivalent to:

        %!test assert (...)

   Sometimes during development there is a test that should work but is
known to fail.  You still want to leave the test in because when the
final code is ready the test should pass, but you may not be able to
fix it immediately.  To avoid unnecessary bug reports for these known
failures, mark the block with `xtest' rather than `test':

        %!xtest assert (1==0)
        %!xtest fail ('success=1','error'))

   Another use of `xtest' is for statistical tests which should pass
most of the time but are known to fail occasionally.

   Each block is evaluated in its own function environment, which means
that variables defined in one block are not automatically shared with
other blocks.  If you do want to share variables, then you must declare
them as `shared' before you use them.  For example, the following
declares the variable A, gives it an initial value (default is empty),
then uses it in several subsequent tests.

        %!shared A
        %! A = [1, 2, 3; 4, 5, 6];
        %!assert (kron ([1; 2], A), [ A; 2*A ]);
        %!assert (kron ([1, 2], A), [ A, 2*A ]);
        %!assert (kron ([1,2; 3,4], A), [ A,2*A; 3*A,4*A ]);

   You can share several variables at the same time:

        %!shared A, B

   You can also share test functions:

        %!function A = fn(B)
        %!  A = 2*B;
        %!assert (A(2),4);

   Note that all previous variables and values are lost when a new
shared block is declared.

   Error and warning blocks are like test blocks, but they only succeed
if the code generates an error.  You can check the text of the error is
correct using an optional regular expression `<pattern>'.  For example:

        %!error <passes!> error('this test passes!');

   If the code doesn't generate an error, the test fails. For example,

        %!error "this is an error because it succeeds.";

   produces

        ***** error "this is an error because it succeeds.";
        !!!!! test failed: no error

   It is important to automate the tests as much as possible, however
some tests require user interaction.  These can be isolated into demo
blocks, which if you are in batch mode, are only run when called with
`demo' or `verbose'. The code is displayed before it is executed. For
example,

        %!demo
        %! T=[0:0.01:2*pi]; X=sin(T);
        %! plot(T,X);
        %! you should now see a sine wave in your figure window

   produces

        > T=[0:0.01:2*pi]; X=sin(T);
        > plot(T,X);
        > you should now see a sine wave in your figure window
        Press <enter> to continue:

   Note that demo blocks cannot use any shared variables.  This is so
that they can be executed by themselves, ignoring all other tests.

   If you want to temporarily disable a test block, put `#' in place of
the block type.  This creates a comment block which is echoed in the
log file, but is not executed.  For example:

        %!#demo
        %! T=[0:0.01:2*pi]; X=sin(T);
        %! plot(T,X);
        %! you should now see a sine wave in your figure window

   Block type summary:

`%!test'
     check that entire block is correct

`%!error'
     check for correct error message

`%!warning'
     check for correct warning message

`%!demo'
     demo only executes in interactive mode

`%!#'
     comment: ignore everything within the block

`%!shared x,y,z'
     declares variables for use in multiple tests

`%!function'
     defines a function value for a shared variable

`%!assert (x, y, tol)'
     shorthand for %!test assert (x, y, tol)

   You can also create test scripts for builtins and your own C++
functions. Just put a file of the function name on your path without
any extension and it will be picked up by the test procedure.  You can
even embed tests directly in your C++ code:

        #if 0
        %!test disp('this is a test')
        #endif

   or

        /*
        %!test disp('this is a test')
        */

   but then the code will have to be on the load path and the user will
have to remember to type test('name.cc').  Conversely, you can separate
the tests from normal octave script files by putting them in plain
files with no extension rather than in script files.

 -- Function File:  assert (COND)
 -- Function File:  assert (OBSERVED,EXPECTED)
 -- Function File:  assert (OBSERVED,EXPECTED,TOL)
     Produces an error if the condition is not met. `assert' can be
     called in three different ways.

    `assert (COND)'
          Called with a single argument COND, `assert' produces an
          error if COND is zero.

    `assert (OBSERVED, EXPECTED)'
          Produce an error if observed is not the same as expected.
          Note that observed and expected can be strings, scalars,
          vectors, matrices, lists or structures.

    `assert(OBSERVED, EXPECTED, TOL)'
          Accept a tolerance when comparing numbers.  If TOL is
          positive use it as an absolute tolerance, will produce an
          error if `abs(OBSERVED - EXPECTED) > abs(TOL)'.  If TOL is
          negative use it as a relative tolerance, will produce an
          error if `abs(OBSERVED - EXPECTED) > abs(TOL * EXPECTED)'.
          If EXPECTED is zero TOL will always be used as an absolute
          tolerance.


     *See also:* test.

 -- Function File:  fail (CODE,PATTERN)
 -- Function File:  fail (CODE,'warning',PATTERN)
     Return true if CODE fails with an error message matching PATTERN,
     otherwise produce an error. Note that CODE is a string and if CODE
     runs successfully, the error produced is:

                    expected error but got none

     If the code fails with a different error, the message produced is:

                    expected <pattern>
                    but got <text of actual error>

     The angle brackets are not part of the output.

     Called with three arguments, the behavior is similar to
     `fail(CODE, PATTERN)', but produces an error if no warning is
     given during code execution or if the code fails.



File: octave.info,  Node: Demonstration Functions,  Prev: Test Functions,  Up: Test and Demo Functions

B.2 Demonstration Functions
===========================

 -- Function File:  demo ('NAME',N)
     Runs any examples associated with the function 'NAME'.  Examples
     are stored in the script file, or in a file with the same name but
     no extension somewhere on your path.  To keep them separate from
     the usual script code, all lines are prefixed by `%!'. Each
     example is introduced by the keyword 'demo' flush left to the
     prefix, with no intervening spaces.  The remainder of the example
     can contain arbitrary octave code. For example:

             %!demo
             %! t=0:0.01:2*pi; x = sin(t);
             %! plot(t,x)
             %! %-------------------------------------------------
             %! % the figure window shows one cycle of a sine wave

     Note that the code is displayed before it is executed, so a simple
     comment at the end suffices.  It is generally not necessary to use
     disp or printf within the demo.

     Demos are run in a function environment with no access to external
     variables. This means that all demos in your function must use
     separate initialization code. Alternatively, you can combine your
     demos into one huge demo, with the code:

             %! input("Press <enter> to continue: ","s");

     between the sections, but this is discouraged.  Other techniques
     include using multiple plots by saying figure between each, or
     using subplot to put multiple plots in the same window.

     Also, since demo evaluates inside a function context, you cannot
     define new functions inside a demo.  Instead you will have to use
     `eval(example('function',n))' to see them.  Because eval only
     evaluates one line, or one statement if the statement crosses
     multiple lines, you must wrap your demo in "if 1 <demo stuff>
     endif" with the 'if' on the same line as 'demo'. For example,

            %!demo if 1
            %!  function y=f(x)
            %!    y=x;
            %!  endfunction
            %!  f(3)
            %! endif


     *See also:* test, example.

 -- Function File:  example ('NAME',N)
 -- Function File: [X, IDX] = example ('NAME',N)
     Display the code for example N associated with the function
     'NAME', but do not run it. If N is not given, all examples are
     displayed.

     Called with output arguments, the examples are returned in the
     form of a string X, with IDX indicating the ending position of the
     various examples.

     See `demo' for a complete explanation.

     *See also:* demo, test.

 -- Function File:  speed (F, INIT, MAX_N, F2, TOL)
 -- Function File: [ORDER, N, T_F, T_F2] = speed (...)
     Determine the execution time of an expression for various N.  The
     N are log-spaced from 1 to MAX_N.  For each N, an initialization
     expression is computed to create whatever data are needed for the
     test.  If a second expression is given, the execution times of the
     two expressions will be compared.  Called without output arguments
     the results are presented graphically.

    `F'
          The expression to evaluate.

    `MAX_N'
          The maximum test length to run. Default value is 100.
          Alternatively, use `[min_n,max_n]' or for complete control,
          `[n1,n2,...,nk]'.

    `INIT'
          Initialization expression for function argument values.  Use K
          for the test number and N for the size of the test.  This
          should compute values for all variables listed in args.  Note
          that init will be evaluated first for k=0, so things which
          are constant throughout the test can be computed then. The
          default value is `X = randn (N, 1);'.

    `F2'
          An alternative expression to evaluate, so the speed of the two
          can be compared. Default is `[]'.

    `TOL'
          If TOL is `Inf', then no comparison will be made between the
          results of expression F and expression F2.  Otherwise,
          expression F should produce a value V and expression F2
          should produce a value V2, and these shall be compared using
          `assert(V,V2,TOL)'. If TOL is positive, the tolerance is
          assumed to be absolute. If TOL is negative, the tolerance is
          assumed to be relative. The default is `eps'.

    `ORDER'
          The time complexity of the expression `O(a n^p)'.  This is a
          structure with fields `a' and `p'.

    `N'
          The values N for which the expression was calculated and the
          execution time was greater than zero.

    `T_F'
          The nonzero execution times recorded for the expression F in
          seconds.

    `T_F2'
          The nonzero execution times recorded for the expression F2 in
          seconds.  If it is needed, the mean time ratio is just
          `mean(T_f./T_f2)'.


     The slope of the execution time graph shows the approximate power
     of the asymptotic running time `O(n^p)'.  This power is plotted
     for the region over which it is approximated (the latter half of
     the graph).  The estimated power is not very accurate, but should
     be sufficient to determine the general order of your algorithm.
     It should indicate if for example your implementation is
     unexpectedly `O(n^2)' rather than `O(n)' because it extends a
     vector each time through the loop rather than preallocating one
     which is big enough.  For example, in the current version of
     Octave, the following is not the expected `O(n)':

            speed("for i=1:n,y{i}=x(i); end", "", [1000,10000])

     but it is if you preallocate the cell array `y':

            speed("for i=1:n,y{i}=x(i);end", ...
                  "x=rand(n,1);y=cell(size(x));", [1000,10000])

     An attempt is made to approximate the cost of the individual
     operations, but it is wildly inaccurate.  You can improve the
     stability somewhat by doing more work for each `n'.  For example:

            speed("airy(x)", "x=rand(n,10)", [10000,100000])

     When comparing a new and original expression, the line on the
     speedup ratio graph should be larger than 1 if the new expression
     is faster.  Better algorithms have a shallow slope.  Generally,
     vectorizing an algorithm will not change the slope of the execution
     time graph, but it will shift it relative to the original.  For
     example:

            speed("v=sum(x)", "", [10000,100000], ...
                  "v=0;for i=1:length(x),v+=x(i);end")

     A more complex example, if you had an original version of `xcorr'
     using for loops and another version using an FFT, you could
     compare the run speed for various lags as follows, or for a fixed
     lag with varying vector lengths as follows:

            speed("v=xcorr(x,n)", "x=rand(128,1);", 100, ...
                  "v2=xcorr_orig(x,n)", -100*eps)
            speed("v=xcorr(x,15)", "x=rand(20+n,1);", 100, ...
                  "v2=xcorr_orig(x,n)", -100*eps)

     Assuming one of the two versions is in XCORR_ORIG, this would
     compare their speed and their output values.  Note that the FFT
     version is not exact, so we specify an acceptable tolerance on the
     comparison `100*eps', and the errors should be computed
     relatively, as `abs((X - Y)./Y)' rather than absolutely as `abs(X
     - Y)'.

     Type `example('speed')' to see some real examples. Note for
     obscure reasons, you can't run examples 1 and 2 directly using
     `demo('speed')'. Instead use, `eval(example('speed',1))' and
     `eval(example('speed',2))'.


File: octave.info,  Node: Tips,  Next: Trouble,  Prev: Test and Demo Functions,  Up: Top

Appendix C Tips and Standards
*****************************

This chapter describes no additional features of Octave.  Instead it
gives advice on making effective use of the features described in the
previous chapters.

* Menu:

* Style Tips::                  Writing clean and robust programs.
* Coding Tips::                 Making code run faster.
* Comment Tips::                Conventions for writing comments.
* Function Headers::            Standard headers for functions.
* Documentation Tips::          Writing readable documentation strings.


File: octave.info,  Node: Style Tips,  Next: Coding Tips,  Up: Tips

C.1 Writing Clean Octave Programs
=================================

Here are some tips for avoiding common errors in writing Octave code
intended for widespread use:

   * Since all global variables share the same name space, and all
     functions share another name space, you should choose a short word
     to distinguish your program from other Octave programs.  Then take
     care to begin the names of all global variables, constants, and
     functions with the chosen prefix.  This helps avoid name conflicts.

     If you write a function that you think ought to be added to Octave
     under a certain name, such as `fiddle_matrix', don't call it by
     that name in your program.  Call it `mylib_fiddle_matrix' in your
     program, and send mail to <maintainers@octave.org> suggesting that
     it be added to Octave.  If and when it is, the name can be changed
     easily enough.

     If one prefix is insufficient, your package may use two or three
     alternative common prefixes, so long as they make sense.

     Separate the prefix from the rest of the symbol name with an
     underscore `_'.  This will be consistent with Octave itself and
     with most Octave programs.

   * When you encounter an error condition, call the function `error'
     (or `usage').  The `error' and `usage' functions do not return.
     *Note Errors::.

   * Please put a copyright notice on the file if you give copies to
     anyone.  Use the same lines that appear at the top of the function
     files distributed with Octave.  If you have not signed papers to
     assign the copyright to anyone else, then place your name in the
     copyright notice.


File: octave.info,  Node: Coding Tips,  Next: Comment Tips,  Prev: Style Tips,  Up: Tips

C.2 Tips for Making Code Run Faster.
====================================

Here are some ways of improving the execution speed of Octave programs.

   * Avoid looping wherever possible.

   * Use iteration rather than recursion whenever possible.  Function
     calls are slow in Octave.

   * Avoid resizing matrices unnecessarily.  When building a single
     result matrix from a series of calculations, set the size of the
     result matrix first, then insert values into it.  Write

          result = zeros (big_n, big_m)
          for i = over:and_over
            r1 = ...
            r2 = ...
            result (r1, r2) = new_value ();
          endfor

     instead of

          result = [];
          for i = ever:and_ever
            result = [ result, new_value() ];
          endfor

   * Avoid calling `eval' or `feval' whenever possible, because they
     require Octave to parse input or look up the name of a function in
     the symbol table.

     If you are using `eval' as an exception handling mechanism and not
     because you need to execute some arbitrary text, use the `try'
     statement instead.  *Note The try Statement::.

   * If you are calling lots of functions but none of them will need to
     change during your run, set the variable
     `ignore_function_time_stamp' to `"all"' so that Octave doesn't
     waste a lot of time checking to see if you have updated your
     function files.


File: octave.info,  Node: Comment Tips,  Next: Function Headers,  Prev: Coding Tips,  Up: Tips

C.3 Tips on Writing Comments
============================

Here are the conventions to follow when writing comments.

`#'
     Comments that start with a single sharp-sign, `#', should all be
     aligned to the same column on the right of the source code.  Such
     comments usually explain how the code on the same line does its
     job.  In the Emacs mode for Octave, the `M-;'
     (`indent-for-comment') command automatically inserts such a `#' in
     the right place, or aligns such a comment if it is already present.

`##'
     Comments that start with a double sharp-sign, `##', should be
     aligned to the same level of indentation as the code.  Such
     comments usually describe the purpose of the following lines or
     the state of the program at that point.

The indentation commands of the Octave mode in Emacs, such as `M-;'
(`indent-for-comment') and `TAB' (`octave-indent-line') automatically
indent comments according to these conventions, depending on the number
of semicolons.  *Note Manipulating Comments: (emacs)Comments.

